text:
function permutation_search(mapf::MAPF, initial_permutation)
    A = nb_agents(mapf)
    permutation = copy(initial_permutation)
    solution = cooperative_astar(mapf, permutation)
    indep_solution = independent_astar(mapf)
    cost = flowtime(solution, mapf)
    lower_bound = flowtime(indep_solution, mapf)
    improvement_found = true
    prog = ProgressUnknown("Local search steps:")
    while true
        gap = round(100 * (cost - lower_bound) / lower_bound; sigdigits=3)
        ProgressMeter.next!(prog; showvalues=[(:objective, cost), (:gap, gap)])
        improvement_found = false
        for i in shuffle(1:A), j in shuffle((i + 1):A)
            new_permutation = copy(permutation)
            new_permutation[i], new_permutation[j] = new_permutation[j], new_permutation[i]
            new_solution = cooperative_astar(mapf, new_permutation)
            new_cost = flowtime(new_solution, mapf)
            if new_cost < cost
                permutation = new_permutation
                cost = new_cost
                improvement_found = true
                break
            end
        end
        if !improvement_found
            ProgressMeter.finish!(prog)
            break
        end
    end
    final_solution = cooperative_astar(mapf, permutation)
    return final_solution
end


text:
module Storage

end

ext: jl


text:
# This file is a part of Julia. License is MIT: https://julialang.org/license

# Conversion/Promotion

"""
    Date(dt::DateTime) -> Date

Converts a `DateTime` to a `Date`. The hour, minute, second, and millisecond parts of
the `DateTime` are truncated, so only the year, month and day parts are used in
construction.
"""
Date(dt::TimeType) = convert(Date, dt)

"""
    DateTime(dt::Date) -> DateTime

Converts a `Date` to a `DateTime`. The hour, minute, second, and millisecond parts of
the new `DateTime` are assumed to be zero.
"""
DateTime(dt::TimeType) = convert(DateTime, dt)

"""
    Time(dt::DateTime) -> Time

Converts a `DateTime` to a `Time`. The hour, minute, second, and millisecond parts of
the `DateTime` are used to create the new `Time`. Microsecond and nanoseconds are zero by default.
"""
Time(dt::DateTime) = convert(Time, dt)

Base.convert(::Type{DateTime}, dt::Date) = DateTime(UTM(value(dt) * 86400000))
Base.convert(::Type{Date}, dt::DateTime) = Date(UTD(days(dt)))
Base.convert(::Type{Time}, dt::DateTime) = Time(Nanosecond((value(dt) % 86400000) * 1000000))

Base.convert(::Type{DateTime},x::Millisecond)  = DateTime(Dates.UTInstant(x))  # Converts Rata Die milliseconds to a DateTime
Base.convert(::Type{Millisecond},dt::DateTime) = Millisecond(value(dt))        # Converts DateTime to Rata Die milliseconds
Base.convert(::Type{Date},x::Day)  = Date(Dates.UTInstant(x))  # Converts Rata Die days to a Date
Base.convert(::Type{Day},dt::Date) = Day(value(dt))            # Converts Date to Rata Die days

### External Conversions
const UNIXEPOCH = value(DateTime(1970)) #Rata Die milliseconds for 1970-01-01T00:00:00

"""
    unix2datetime(x) -> DateTime

Takes the number of seconds since unix epoch `1970-01-01T00:00:00` and converts to the
corresponding `DateTime`.
"""
function unix2datetime(x)
    rata = UNIXEPOCH + round(Int64, Int64(1000) * x)
    return DateTime(UTM(rata))
end
"""
    datetime2unix(dt::DateTime) -> Float64

Takes the given `DateTime` and returns the number of seconds
since the unix epoch `1970-01-01T00:00:00` as a `Float64`.
"""
datetime2unix(dt::DateTime) = (value(dt) - UNIXEPOCH) / 1000.0

"""
    now() -> DateTime

Returns a `DateTime` corresponding to the user's system time including the system timezone
locale.
"""
function now()
    tv = Libc.TimeVal()
    tm = Libc.TmStruct(tv.sec)
    return DateTime(tm.year + 1900, tm.month + 1, tm.mday, tm.hour, tm.min, tm.sec, div(tv.usec, 1000))
end

"""
    today() -> Date

Returns the date portion of `now()`.
"""
today() = Date(now())

"""
    now(::Type{UTC}) -> DateTime

Returns a `DateTime` corresponding to the user's system time as UTC/GMT.
"""
now(::Type{UTC}) = unix2datetime(time())

"""
    rata2datetime(days) -> DateTime

Takes the number of Rata Die days since epoch `0000-12-31T00:00:00` and returns the
corresponding `DateTime`.
"""
rata2datetime(days) = DateTime(yearmonthday(days)...)

"""
    datetime2rata(dt::TimeType) -> Int64

Returns the number of Rata Die days since epoch from the given `Date` or `DateTime`.
"""
datetime2rata(dt::TimeType) = days(dt)

# Julian conversions
const JULIANEPOCH = value(DateTime(-4713, 11, 24, 12))

"""
    julian2datetime(julian_days) -> DateTime

Takes the number of Julian calendar days since epoch `-4713-11-24T12:00:00` and returns the
corresponding `DateTime`.
"""
function julian2datetime(f)
    rata = JULIANEPOCH + round(Int64, Int64(86400000) * f)
    return DateTime(UTM(rata))
end

"""
    datetime2julian(dt::DateTime) -> Float64

Takes the given `DateTime` and returns the number of Julian calendar days since the julian
epoch `-4713-11-24T12:00:00` as a `Float64`.
"""
datetime2julian(dt::DateTime) = (value(dt) - JULIANEPOCH) / 86400000.0

max_stars_repo_name: odow/julia

max_issues_repo_name: odow/julia

max_forks_repo_name: odow/julia


text:
using Queryverse
using Test

@testset "Queryverse" begin

df = load(joinpath(@__DIR__, "testdata.csv")) |>
@query(i, begin
@select {i.Count, i.Year}
end) |>
@tee(save("testoutput.csv")) |>
# @tee(begin
#     data_values() |>
#     mark_point() |>
#     encoding_x_ord(:Year) |>
#     encoding_y_quant(:Count) |>
#     save("testoutput.pdf")
# end) |>
DataFrame

@test size(df) == (2,2)

io = IOBuffer()
f(x) = print(io, sum(x + x))
1:10 |> @tee(f) |> x -> print(io, " ", sum(x))
@test String(take!(io)) == "110 55"

end


text:
import Base: muladd, fma

"""
    two_sum(a, b)
Computes `hi = fl(a+b)` and `lo = err(a+b)`.
"""
@inline function two_sum(a::T, b::T) where {T<:AbstractFloat}
    hi = a + b
    a1 = hi - b
    b1 = hi - a1
    lo = (a - a1) + (b - b1)
    return hi, lo
end

"""
    two_hilo_sum(a, b)
*unchecked* requirement `|a| ≥ |b|`
Computes `s = fl(a+b)` and `e = err(a+b)`.
"""
@inline function two_hilo_sum(a::T, b::T) where {T<:AbstractFloat}
    s = a + b
    e = b - (s - a)
    return s, e
end

@inline function two_prod(a::T, b::T) where {T<:AbstractFloat}
    s = a * b
    t = fma(a, b, -s)
    return s, t
end

function fma(xhi::T, xlo::T, yhi::T, ylo::T, zhi::T, zlo::T) where {T<:AbstractFloat}
   chi, c1 = two_prod(xhi, yhi)
   t0 = xlo * ylo
   t1 = fma(xhi, ylo, t0)
   c2 = fma(xlo, yhi, t1)
   c3 = c1 + c2
   dhi, dlo = two_hilo_sum(chi, c3)

   shi, slo = two_sum(zhi, dhi)
   thi, tlo = two_sum(zlo, dlo)
   c = slo + thi
   vhi, vlo = two_hilo_sum(shi, c)
   w = tlo + vlo
   hi, lo = two_hilo_sum(vhi, w)
   return DoubleFloat{T}(hi, lo)
end

@inline function fma(x::DoubleFloat{T}, y::DoubleFloat{T}, z::DoubleFloat{T}) where {T<:AbstractFloat}
   return fma(x.hi, x.lo, y.hi, y.lo, z.hi, z.lo)
end

@inline function fma(x::DoubleFloat{T}, y::DoubleFloat{T}, z::Tuple{T,T}) where {T<:AbstractFloat}
   return fma(x.hi, x.lo, y.hi, y.lo, z[1], z[2])
end
@inline function fma(x::DoubleFloat{T}, y::Tuple{T,T}, z::DoubleFloat{T}) where {T<:AbstractFloat}
   return fma(x.hi, x.lo, y[1], y[2], z.hi, z.lo)
end
@inline function fma(x::Tuple{T,T}, y::DoubleFloat{T}, z::DoubleFloat{T}) where {T<:AbstractFloat}
   return fma(x[1], x[2], y.hi, y.lo, z.hi, z.lo)
end
@inline function fma(x::DoubleFloat{T}, y::Tuple{T,T}, z::Tuple{T,T}) where {T<:AbstractFloat}
   return fma(x.hi, x.lo, y[1], y[2], z[1], z[2])
end
@inline function fma(x::Tuple{T,T}, y::Tuple{T,T}, z::DoubleFloat{T}) where {T<:AbstractFloat}
   return fma(x[1], x[2], y[1], y[2], z.hi, z.lo)
end
@inline function fma(x::Tuple{T,T}, y::DoubleFloat{T}, z::Tuple{T,T}) where {T<:AbstractFloat}
   return fma(x[1], x[2], y.hi, y.lo, z[1], z[2])
end
@inline function fma(x::Tuple{T,T}, y::Tuple{T,T}, z::Tuple{T,T}) where {T<:AbstractFloat}
   return fma(x[1], x[2], y[1], y[2], z[1], z[2])
end

function muladd(xhi::T, xlo::T, yhi::T, ylo::T, zhi::T, zlo::T) where {T<:AbstractFloat}
   chi, c1 = two_prod(xhi, yhi)
   t0 = xlo * ylo
   c2 = fma(xlo, yhi, t0)
   c3 = c1 + c2
   dhi, dlo = two_hilo_sum(chi, c3)

   shi, slo = two_sum(zhi, dhi)
   thi, tlo = two_sum(zlo, dlo)
   c = slo + thi
   vhi, vlo = two_hilo_sum(shi, c)
   w = tlo + vlo
   hi, lo = two_hilo_sum(vhi, w)
   return DoubleFloat{T}(hi, lo)
end

@inline function muladd(x::DoubleFloat{T}, y::DoubleFloat{T}, z::DoubleFloat{T}) where {T<:AbstractFloat}
   return muladd(x.hi, x.lo, y.hi, y.lo, z.hi, z.lo)
end

@inline function muladd(x::DoubleFloat{T}, y::DoubleFloat{T}, z::Tuple{T,T}) where {T<:AbstractFloat}
   return muladd(x.hi, x.lo, y.hi, y.lo, z[1], z[2])
end
@inline function muladd(x::DoubleFloat{T}, y::Tuple{T,T}, z::DoubleFloat{T}) where {T<:AbstractFloat}
   return muladd(x.hi, x.lo, y[1], y[2], z.hi, z.lo)
end
@inline function muladd(x::Tuple{T,T}, y::DoubleFloat{T}, z::DoubleFloat{T}) where {T<:AbstractFloat}
   return muladd(x[1], x[2], y.hi, y.lo, z.hi, z.lo)
end
@inline function muladd(x::DoubleFloat{T}, y::Tuple{T,T}, z::Tuple{T,T}) where {T<:AbstractFloat}
   return muladd(x.hi, x.lo, y[1], y[2], z[1], z[2])
end
@inline function muladd(x::Tuple{T,T}, y::Tuple{T,T}, z::DoubleFloat{T}) where {T<:AbstractFloat}
   return muladd(x[1], x[2], y[1], y[2], z.hi, z.lo)
end
@inline function muladd(x::Tuple{T,T}, y::DoubleFloat{T}, z::Tuple{T,T}) where {T<:AbstractFloat}
   return muladd(x[1], x[2], y.hi, y.lo, z[1], z[2])
end
@inline function muladd(x::Tuple{T,T}, y::Tuple{T,T}, z::Tuple{T,T}) where {T<:AbstractFloat}
   return muladd(x[1], x[2], y[1], y[2], z[1], z[2])
end


text:
# Note that this script can accept some limited command-line arguments, run
# `julia build_tarballs.jl --help` to see a usage message.
using BinaryBuilder

name = "Qt5Tools"
version = v"5.15.2"

# Collection of sources required to build qt5
sources = [
    ArchiveSource("https://download.qt.io/official_releases/qt/$(version.major).$(version.minor)/$version/submodules/qttools-everywhere-src-$version.tar.xz",
                  "c189d0ce1ff7c739db9a3ace52ac3e24cb8fd6dbf234e49f075249b38f43c1cc"),
]

script = raw"""
cd $WORKSPACE/srcdir
mkdir build
cd build/

qtsrcdir=`ls -d ../qttools-*`

case "$target" in
    *apple-darwin*)
        ln -s $libdir/QtCore.framework/Headers $includedir/QtCore
        ;;
    *freebsd*)
        echo "LIBS += -lxml2 -lz -liconv" >> $qtsrcdir/src/qdoc/qdoc.pro
        ;;
esac

export LLVM_INSTALL_DIR=/opt/x86_64-linux-musl
export QDOC_USE_STATIC_LIBCLANG=true

qmake $qtsrcdir
make -j${nproc}

# It appends the root path here with the qmake dir, which is /workspace/artifacts/blah...
make INSTALL_ROOT=$PWD/dummyroot install
rsync -ua dummyroot/workspace/*/artifacts/*/* $prefix

install_license $qtsrcdir/LICENSE.LGPL3

case "$target" in
    *apple-darwin*)
        rm $includedir/QtCore
        ;;
    *mingw*)
        chmod +x $bindir/*.exe
        ;;
esac
"""

# These are the platforms we will build for by default, unless further
# platforms are passed in on the command line
platforms = [
    Platform("aarch64", "linux"; libc="glibc"),
    Platform("armv7l", "linux"; libc="glibc"),
    Platform("x86_64", "linux"; libc="glibc"),
    Platform("i686", "linux"; libc="glibc"),
    Platform("x86_64", "freebsd"),
    Platform("powerpc64le", "linux"; libc="glibc"),
    Platform("x86_64", "windows"),
    Platform("i686", "windows"),
    Platform("x86_64", "macos"),
]

platforms = expand_cxxstring_abis(platforms)

# The products that we will ensure are always built
products = [
    ExecutableProduct("qdbus", :qdbus),
    ExecutableProduct("qtdiag", :qtdiag),
    ExecutableProduct("qtpaths", :qtpaths),
    ExecutableProduct("qtplugininfo", :qtplugininfo),
]

# Dependencies that must be installed before this package can be built
dependencies = [
    Dependency("Glib_jll", v"2.59.0"; compat="2.59.0"),
    Dependency("Qt5Base_jll"),
]

include("../../fancy_toys.jl")

# Must match GCC versions of Qt5Base
platforms_win = filter(p -> p.tags["os"] == "windows", platforms)
if any(should_build_platform.(triplet.(platforms_win)))
    build_tarballs(ARGS, name, version, sources, script, platforms, products, dependencies; preferred_gcc_version = v"8")
else
    build_tarballs(ARGS, name, version, sources, script, platforms, products, dependencies; preferred_gcc_version = v"7")
end

max_stars_repo_name: sharanry/Yggdrasil

max_issues_repo_name: sharanry/Yggdrasil

max_forks_repo_name: sharanry/Yggdrasil


text:
"""
Fused Lasso Solver for tree graphs, i.e. we aim to **minimize** the following objective function

```math
f(x) = \\frac{1}{2} \\sum_{i=1}^n \\mu_i (x_i - y_i)^2 + \\sum_{(i,j) \\in E} \\lambda_{ij} |x_i - x_j|
```
Hereby is
- ``y_i`` the input signal for node ``i``,
- ``\\mu_i \\geq 0`` is the node weight for node ``i``,
- ``E`` the edges of a tree, and
- ``\\lambda_{ij} > 0`` is the edge weight for ``(i,j)``.
"""
module TreeLas
import GraphIdx

include("cxx.jl")
include("utils.jl")
include("dual.jl")
include("pwl.jl")
include("line_dp.jl")
include("tree_dp.jl")
include("treeflow.jl")
include("mgt.jl")

include("cycle.jl")

include("gaplas.jl")
include("cyclegap.jl")
include("momentum.jl")

include("precompile.jl")
# _precompile_()

end

max_stars_repo_name: EQt/treelas

max_issues_repo_name: EQt/treelas

max_forks_repo_name: EQt/treelas


text:
const CMat = Ptr{Cvoid}
const CMatType = Cstring

"""
    AbstractMat{PetscLib <: PetscLibType}

Abstract type of PETSc vectors.

Manual: [`Mat`](https://petsc.org/release/docs/manualpages/Mat/Mat.html)
"""
abstract type AbstractMat{T, PetscLib <: PetscLibType{T}} <: AbstractMatrix{T} end
Base.eltype(::Type{V}) where {V <: AbstractMat{T}} where {T} = T
Base.eltype(v::AbstractMat{T}) where {T} = T

# allows us to pass XXMat objects directly into CMat ccall signatures
Base.cconvert(::Type{CMat}, obj::AbstractMat) = obj.__ptr__

# allows us to pass XXMat objects directly into Ptr{CMat} ccall signatures
Base.unsafe_convert(::Type{Ptr{CMat}}, obj::AbstractMat) =
    convert(Ptr{CMat}, pointer_from_objref(obj))

mutable struct MatAIJ{
    T,
    PetscLib <: PetscLibType{T},
    CT <: Union{MPI.Comm, Nothing},
} <: AbstractMat{T, PetscLib}
    __ptr__::CMat
    __possible_comm_ref::CT
    function MatAIJ{T, PetscLib}(; comm::CT = nothing) where {PetscLib, T, CT}
        new{T, PetscLib, CT}(C_NULL, comm)
    end
end

@for_libpetsc function view(
    mat::AbstractMat{$PetscScalar, $PetscLib},
    viewer::AbstractViewer{$PetscLib} = ViewerStdout($PetscLib),
)
    @chk ccall(
        (:MatView, $petsc_library),
        PetscErrorCode,
        (CMat, CPetscViewer),
        mat,
        viewer,
    )
    return nothing
end
Base.show(io::IO, mat::AbstractMat) = _show(io, mat)

"""
    destroy(A::AbstractMat)

Destroy the PETSc matrix `A`

Manual: [`MatDestroy`](https://petsc.org/release/docs/manualpages/Mat/MatDestroy.html)
"""
destroy(::AbstractMat)

@for_libpetsc function destroy(petsc_A::AbstractMat{$PetscScalar, $PetscLib})
    Finalized($PetscLib) || @chk ccall(
        (:MatDestroy, $petsc_library),
        PetscErrorCode,
        (Ptr{CMat},),
        petsc_A,
    )

    # Zero the pointer so that if MatDestroy gets called multiple times we
    # do not artificially decrease the internal petsc ref counter
    petsc_A.__ptr__ = C_NULL
    return nothing
end

"""
    MatAIJ(petsclib, m::Int, n::Int, nz::Union{Int, Vector{PetscInt}}

A sequentially-stored `m × n` serial PETSc sparse matrix in compressed row
storage with `nz` zeros per row; if `nz` is a vector then the `nz[i]` is the
number of non-zeros for row `i`.

Manual: [`MatCreateSeqAIJ`](https://petsc.org/release/docs/manualpages/Mat/MatCreateSeqAIJ.html)

!!! note
    Since the `MatAIJ` is inherently serial `destroy` will be called by the
    garbage collector
"""
MatAIJ(_, ::Int, ::Int, ::Union{Int, Vector{Int}})

@for_libpetsc function MatAIJ(
    ::$UnionPetscLib,
    num_rows::Int,
    num_cols::Int,
    nz_per_row::Union{Int, Vector{$PetscInt}},
)
    @assert Initialized($PetscLib)
    petsc_A = MatAIJ{$PetscScalar, $PetscLib}()

    if nz_per_row isa Int
        array_nz_per_row = C_NULL
    else
        array_nz_per_row = nz_per_row
        @assert length(array_nz_per_row) >= num_rows
        nz_per_row = 0
    end

    @chk ccall(
        (:MatCreateSeqAIJ, $petsc_library),
        PetscErrorCode,
        (
            MPI.MPI_Comm,
            $PetscInt,
            $PetscInt,
            $PetscInt,
            Ptr{$PetscInt},
            Ptr{CMat},
        ),
        MPI.COMM_SELF,
        num_rows,
        num_cols,
        nz_per_row,
        array_nz_per_row,
        petsc_A,
    )

    finalizer(destroy, petsc_A)
    return petsc_A
end

"""
    assemblybegin!(mat::AbstractMat)

Begin assembling `mat`

Manual: [`MatAssemblyBegin`](https://petsc.org/release/docs/manualpages/Mat/MatAssemblyBegin.html)
"""
assemblybegin!(::AbstractMat)

"""
    assemblyend!(mat::AbstractMat)

Finish assembling `mat`

Manual: [`MatAssemblyEnd`](https://petsc.org/release/docs/manualpages/Mat/MatAssemblyEnd.html)
"""
assemblyend!(::AbstractMat)

@for_libpetsc function assemblybegin!(
    mat::AbstractMat{$PetscScalar, $PetscLib},
    type = MAT_FINAL_ASSEMBLY,
)
    @assert Initialized($PetscLib)
    @chk ccall(
        (:MatAssemblyBegin, $petsc_library),
        PetscErrorCode,
        (CMat, MatAssemblyType),
        mat,
        type,
    )

    return mat
end

@for_libpetsc function assemblyend!(
    mat::AbstractMat{$PetscScalar, $PetscLib},
    type = MAT_FINAL_ASSEMBLY,
)
    @assert Initialized($PetscLib)
    @chk ccall(
        (:MatAssemblyEnd, $petsc_library),
        PetscErrorCode,
        (CMat, MatAssemblyType),
        mat,
        type,
    )

    return mat
end

@for_libpetsc function Base.size(mat::AbstractMat{$PetscScalar, $PetscLib})
    r_m = Ref{$PetscInt}()
    r_n = Ref{$PetscInt}()
    @chk ccall(
        (:MatGetSize, $petsc_library),
        PetscErrorCode,
        (CMat, Ptr{$PetscInt}, Ptr{$PetscInt}),
        mat,
        r_m,
        r_n,
    )
    return (r_m[], r_n[])
end

"""
    ownershiprange(mat::AbstractMat)

The range of global rows owned by this MPI rank, assuming that the matrix
is laid out with the first `n1` rows on the first processor, next `n2`
rows on the second, etc. For certain parallel layouts this range may not be
well defined.

Manual: [`MatGetOwnershipRange`](https://petsc.org/release/docs/manualpages/Mat/MatGetOwnershipRange.html)

!!! note
    The range returned is inclusive (`idx_first:idx_last`) with 0-based indexing
"""
ownershiprange(::AbstractMat)

@for_libpetsc function ownershiprange(vec::AbstractMat{$PetscScalar})
    r_lo = Ref{$PetscInt}()
    r_hi = Ref{$PetscInt}()
    @chk ccall(
        (:MatGetOwnershipRange, $petsc_library),
        PetscErrorCode,
        (CMat, Ptr{$PetscInt}, Ptr{$PetscInt}),
        vec,
        r_lo,
        r_hi,
    )
    return r_lo[]:(r_hi[] - $PetscInt(1))
end

"""
    setvalues!(
        mat::AbstractMat{PetscScalar, PetscLib},
        rows::Vector{PetscInt},
        cols::Vector{PetscInt},
        vals::Array{PetscScalar},
        insertmode::InsertMode,
    )

Assign the values `vals` in 0-based global `indices` of `vec`. The `insertmode`
can be `INSERT_VALUES` or `ADD_VALUES`.

!!! warning
    This function uses 0-based indexing!

Manual: [`MatSetValues`](https://petsc.org/release/docs/manualpages/Mat/MatSetValues.html)
"""
setvalues!(::AbstractMat)

@for_libpetsc function setvalues!(
    v::AbstractMat{$PetscScalar, $PetscLib},
    rows::Vector{$PetscInt},
    cols::Vector{$PetscInt},
    vals::Array{$PetscScalar},
    insertmode::InsertMode,
)
    @assert length(vals) >= length(rows) * length(cols)
    @chk ccall(
        (:MatSetValues, $petsc_library),
        PetscErrorCode,
        (
            CMat,
            $PetscInt,
            Ptr{$PetscInt},
            $PetscInt,
            Ptr{$PetscInt},
            Ptr{$PetscScalar},
            InsertMode,
        ),
        v,
        length(rows),
        rows,
        length(cols),
        cols,
        vals,
        insertmode,
    )
    return nothing
end

"""
    getvalues!(
        vals::Array{PetscScalar},
        mat::AbstractMat{PetscScalar, PetscLib},
        rows::Vector{PetscInt},
        cols::Vector{PetscInt},
    )

Get the 0-based global `rows` and `cols` of `mat` into the preallocated array
`vals`.

!!! warning
    This function uses 0-based indexing!

Manual: [`MatGetValues`](https://petsc.org/release/docs/manualpages/Mat/MatGetValues.html)
"""
getvalues!(::AbstractMat)

@for_libpetsc function getvalues!(
    vals::Array{$PetscScalar},
    v::AbstractMat{$PetscScalar, $PetscLib},
    rows::Vector{$PetscInt},
    cols::Vector{$PetscInt},
)
    @assert length(vals) >= length(rows) * length(cols)
    @chk ccall(
        (:MatGetValues, $petsc_library),
        PetscErrorCode,
        (
            CMat,
            $PetscInt,
            Ptr{$PetscInt},
            $PetscInt,
            Ptr{$PetscInt},
            Ptr{$PetscScalar},
        ),
        v,
        length(rows),
        rows,
        length(cols),
        cols,
        vals,
    )
    return vals
end


text:
# ---
# title: 705. Design HashSet
# id: problem705
# author: Qling
# date: 2021-03-14
# difficulty: Easy
# categories: Hash Table, Design
# link: <https://leetcode.com/problems/design-hashset/description/>
# hidden: true
# ---
#
# Design a HashSet without using any built-in hash table libraries.
#
# To be specific, your design should include these functions:
#
#   * `add(value)`: Insert a value into the HashSet.
#   * `contains(value)` : Return whether the value exists in the HashSet or not.
#   * `remove(value)`: Remove a value in the HashSet. If the value does not exist in the HashSet, do nothing.
#
#
# **Example:**
#
#
#
#     MyHashSet hashSet = new MyHashSet();
#     hashSet.add(1);
#     hashSet.add(2);
#     hashSet.contains(1);    // returns true
#     hashSet.contains(3);    // returns false (not found)
#     hashSet.add(2);
#     hashSet.contains(2);    // returns true
#     hashSet.remove(2);
#     hashSet.contains(2);    // returns false (already removed)
#
#
#
# **Note:**
#
#   * All values will be in the range of `[0, 1000000]`.
#   * The number of operations will be in the range of `[1, 10000]`.
#   * Please do not use the built-in HashSet library.
#
#
## @lc code=start
using LeetCode

struct MyHashSet
    buckets::Int
    table::Vector{Vector{T}} where {T}
    MyHashSet() = new(1009, [[] for _ = 1:1009])
end

hash_705(hash_set::MyHashSet, key::Int) = mod1(key, hash_set.buckets)

function add_705!(hash_set::MyHashSet, key)
    hash_key = hash_705(hash_set, key)

    key ∈ hash_set.table[hash_key] && return

    push!(hash_set.table[hash_key], key)
    return
end

function remove_705!(hash_set::MyHashSet, key::Int)
    hash_key = hash_705(hash_set, key)

    key ∉ hash_set.table[hash_key] && return

    deleteat!(hash_set.table[hash_key], hash_set.table[hash_key] .== key)
end

function contains_705(hash_set::MyHashSet, key::Int)
    hash_key = hash_705(hash_set, key)

    return key ∈ hash_set.table[hash_key]
end
## @lc code=end


text:
flat_2D_lc = environment_2D_flat()
flat_3D_lc = environment_3D_flat()

flat_2D_nc = environment_2D_flat(cone = NonlinearCone)
flat_3D_nc = environment_3D_flat(cone = NonlinearCone)


text:
using JuMP; using NCDatasets; using AxisArrays; using CalliopeJuMP.Util;

function load_milp_constraints(model_dict)
    sets = model_dict["sets"]
    constraint_dict = Dict()
    backend_model = model_dict["backend_model"]

    if haskey(sets, "loc_techs_milp")
        constraint_dict["unit_commitment_constraint"] = build_constraint(
            ["loc_techs_unit_commitment_constraint", "timesteps"],
            "unit_commitment_constraint", model_dict
        )

        constraint_dict["carrier_production_max_milp_constraint"] = build_constraint(
            ["loc_tech_carriers_carrier_production_max_conversion_plus_milp_constraint_rule",
            "timesteps"],"carrier_production_max_milp", model_dict
        )

        constraint_dict["carrier_consumption_max_milp_constraint"] = build_constraint(
            ["loc_tech_carriers_carrier_consumption_max_milp_constraint",
            "timesteps"], "carrier_consumption_max_milp", model_dict
        )
    end

    if haskey(sets, "loc_tech_carriers_carrier_production_min_milp_constraint")
        constraint_dict["carrier_production_min_milp_constraint"] = build_constraint(
            ["loc_tech_carriers_carrier_production_min_milp_constraint",
            "timesteps"], "carrier_production_min_milp", model_dict
        )
    end

    if haskey(sets, "loc_techs_storage_capacity_milp_constraint")
        constraint_dict["storage_capacity_milp_constraint"] = build_constraint(
            ["loc_techs_storage_capacity_milp_constraint"],
            "storage_capacity_milp", model_dict
        )
    end

    if haskey(sets, "loc_techs_energy_capacity_units_constraint")
        constraint_dict["energy_capacity_units_constraint"] = build_constraint(
            ["loc_techs_energy_capacity_units_constraint"],
            "energy_capacity_units", model_dict
        )
    end

    if haskey(sets, "loc_techs_update_costs_investment_units_constraint")
        for loc_tech=sets["loc_techs_update_costs_investment_units_constraint"], cost=sets["costs"]

            update_costs_investment_units_constraint(backend_model, loc_tech, cost)
        end
    end

    if haskey(sets, "loc_techs_update_costs_investment_purchase_constraint")
        for loc_tech=sets["loc_techs_update_costs_investment_purchase_constraint"], cost=sets["costs"]

            update_costs_investment_purchase_constraint(model_dict, loc_tech, cost)
        end
    end

    if haskey(sets, "loc_techs_energy_capacity_max_purchase_constraint")
        constraint_dict["energy_capacity_max_purchase_constraint"] = build_constraint(
            ["loc_techs_energy_capacity_max_purchase_constraint"],
            "energy_capacity_max_purchase", model_dict
        )
    end

    if haskey(sets, "loc_techs_energy_capacity_min_purchase_constraint")
        constraint_dict["energy_capacity_min_purchase_constraint"] = build_constraint(
            ["loc_techs_energy_capacity_min_purchase_constraint"],
            "energy_capacity_min_purchase", model_dict
        )
    end

    return constraint_dict
end

function unit_commitment_constraint_rule(backend_model, set_indices, model_dict)
    """
    Constraining the number of integer units
    """
    loc_tech, timestep = set_indices
    variables = model_dict["variables"]
    return @constraint(backend_model,
        variables["operating_units"][loc_tech, timestep] <= variables["units"][loc_tech]
    )
end

function carrier_production_max_milp_constraint_rule(backend_model, set_indices, model_dict)
    """
    Set maximum carrier production of MILP techs that aren"t conversion plus
    """
    loc_tech_carrier, timestep = set_indices
    variables = model_dict["variables"]
    loc_tech = get_loc_tech(loc_tech_carrier)
    timestep_resolution = model_dict["parameters"]["timestep_resolution"][timestep]
    parasitic_eff = get_param(model_dict, "parasitic_eff", [loc_tech], timestep)
    e_cap = get_param(model_dict, "energy_cap_per_unit", [loc_tech])

    return @constraint(backend_model,
        variables["carrier_prod"][loc_tech_carrier, timestep] <=
        variables["operating_units"][loc_tech, timestep] * timestep_resolution * e_cap
        * parasitic_eff
    )
end

function carrier_production_max_conversion_plus_milp_constraint_rule(backend_model, set_indices, model_dict)
    """
    Set maximum carrier production of conversion_plus MILP techs
    """
    loc_tech, timestep = set_indices
    variables = model_dict["variables"]
    timestep_resolution = model_dict["parameters"]["timestep_resolution"][timestep]
    e_cap = get_param(model_dict, "energy_cap_per_unit", [loc_tech])
    loc_tech_carriers_out = split_comma_list(get_param(
        backend_model, "lookup_loc_techs_conversion_plus", (loc_tech, "out")
    ))

    c_prod = sum(variables["carrier_prod"][loc_tech_carrier, timestep]
                 for loc_tech_carrier in loc_tech_carriers_out)

    return @constraint(backend_model,
        c_prod <= variables["operating_units"][loc_tech, timestep] * timestep_resolution * e_cap
    )
end

function carrier_production_min_milp_constraint_rule(backend_model, set_indices, model_dict)
    """
    Set minimum carrier production of MILP techs that aren"t conversion plus
    """
    loc_tech_carrier, timestep = set_indices
    variables = model_dict["variables"]
    loc_tech = get_loc_tech(loc_tech_carrier)
    timestep_resolution = model_dict["parameters"]["timestep_resolution"][timestep]
    min_use = get_param(model_dict, "energy_cap_min_use", [loc_tech], timestep)
    e_cap = get_param(model_dict, "energy_cap_per_unit", [loc_tech])

    return @constraint(backend_model,
        variables["carrier_prod"][loc_tech_carrier, timestep] >=
        variables["operating_units"][loc_tech, timestep] * timestep_resolution
        * e_cap * min_use
    )
end

function carrier_consumption_max_milp_constraint_rule(backend_model, set_indices, model_dict)
    """
    Set maximum carrier consumption of demand, storage, && tranmission MILP techs
    """
    loc_tech_carrier, timestep = set_indices
    variables = model_dict["variables"]
    loc_tech = get_loc_tech(loc_tech_carrier)
    timestep_resolution = model_dict["parameters"]["timestep_resolution"][timestep]
    e_cap = get_param(model_dict, "energy_cap_per_unit", [loc_tech])

    return @constraint(backend_model,
        variables["carrier_con"][loc_tech_carrier, timestep] >= -1 *
        variables["operating_units"][loc_tech, timestep] * timestep_resolution
        * e_cap
    )
end

function energy_capacity_units_constraint_rule(backend_model, set_indices, model_dict)
    """
    Set energy capacity decision variable as a function of purchased units
    """
    loc_tech = set_indices
    variables = model_dict["variables"]
    return @constraint(backend_model,
        variables["energy_cap"][loc_tech] == variables["units"][loc_tech] *
        get_param(model_dict, "energy_cap_per_unit", [loc_tech])
    )
end

function energy_capacity_max_purchase_constraint_rule(backend_model, set_indices, model_dict)
    """
    Set maximum energy capacity decision variable upper bound as a function of
    binary purchase variable
    """
    loc_tech = set_indices
    variables = model_dict["variables"]
    energy_cap_max = get_param(model_dict, "energy_cap_max", [loc_tech])
    energy_cap_equals = get_param(model_dict, "energy_cap_equals", [loc_tech])
    energy_cap_scale = get_param(model_dict, "energy_cap_scale", [loc_tech])

    if energy_cap_equals > 0
        return @constraint(backend_model,
            variables["energy_cap"][loc_tech] ==
            energy_cap_equals * energy_cap_scale * variables["purchased"][loc_tech]
        )

    elseif isinf(energy_cap_max)
        return

    else
        return @constraint(backend_model,
            variables["energy_cap"][loc_tech] <=
            energy_cap_max * energy_cap_scale * variables["purchased"][loc_tech]
        )
    end
end

function energy_capacity_min_purchase_constraint_rule(backend_model, set_indices, model_dict)
    """
    Set minimum energy capacity decision variable upper bound as a function of
    binary purchase variable
    """
    loc_tech = set_indices
    variables = model_dict["variables"]
    energy_cap_min = get_param(model_dict, "energy_cap_min", [loc_tech])
    energy_cap_equals = get_param(model_dict, "energy_cap_equals", [loc_tech])
    energy_cap_scale = get_param(model_dict, "energy_cap_scale", [loc_tech])

    return @constraint(backend_model,
        variables["energy_cap"][loc_tech] >=
        energy_cap_min * energy_cap_scale * variables["purchased"][loc_tech]
    )
end

function storage_capacity_milp_constraint_rule(backend_model, set_indices, model_dict)
    """
    Set maximum storage capacity. Supply_plus & storage techs only
    This can be set by either storage_cap (kWh) or by
    energy_cap (charge/discharge capacity) * charge rate.
    If storage_cap.equals and energy_cap.equals are set for the technology, then
    storage_cap * charge rate = energy_cap must hold. Otherwise, take the lowest capacity
    capacity defined by storage_cap.max or energy_cap.max / charge rate.
    """
    loc_tech = set_indices
    variables = model_dict["variables"]
    # FIXME? energy_cap_equals could be already dealt with in preprocessing, to
    # either be energy_cap_equals or units_equals * energy_cap_per_unit. Similarly for
    # storage_cap_equals
    units_equals = get_param(model_dict, "units_equals", [loc_tech])
    storage_cap_per_unit = get_param(model_dict, "storage_cap_per_unit", [loc_tech])
    energy_cap_per_unit = get_param(model_dict, "energy_cap_per_unit", [loc_tech])

    scale = get_param(model_dict, "energy_cap_scale", [loc_tech])
    charge_rate = get_param(model_dict, "charge_rate", [loc_tech])

    # First, set the variable with "==" is unit numbers are set in stone
    if units_equals > 0 && storage_cap_per_unit > 0
        return @constraint(backend_model,
            variables["storage_cap"][loc_tech] == storage_cap_per_unit * units_equals
        )

    elseif units_equals > 0 && energy_cap_per_unit > 0 && charge_rate > 0
        return @constraint(backend_model,
            variables["storage_cap"][loc_tech] ==
            energy_cap_per_unit * scale * units_equals / charge_rate
        )

    # If not set in stone, use the variable "units" to set maximum
    elseif storage_cap_per_unit > 0
        s_cap = variables["units"][loc_tech] * storage_cap_per_unit
        return @constraint(backend_model, variables["storage_cap"][loc_tech] <= s_cap)

    elseif energy_cap_per_unit > 0 && charge_rate > 0
        e_cap = variables["units"][loc_tech] * energy_cap_per_unit * scale / charge_rate
        return @constraint(backend_model, variables["storage_cap"][loc_tech] <= e_cap)

    # if insufficient "per_unit" information is given, assume there is no capacity
    else
        return
    end
end

function update_costs_investment_units_constraint(model_dict, loc_tech, cost)
    """
    Add MILP investment costs (cost * number of units purchased)
    """
    variables = model_dict["variables"]
    ts_weight = get_timestep_weight(model_dict)
    sets = model_dict["sets"]
    depreciation_rate = model_dict["parameters"]["cost_depreciation_rate"][loc_tech, cost]

    cost_purchase = get_param(model_dict, "cost_purchase", [cost, loc_tech])
    cost_of_purchase = (
        variables["units"][loc_tech] * cost_purchase * ts_weight * depreciation_rate
    )

    append!(model_dict["expressions"]["investment_rhs"][cost, loc_tech], cost_of_purchase)

    loc_tech_index = findin(sets["loc_carriers"], [loc_tech])
    cost_index = findin(sets["loc_carriers"], [cost])
    model_dict["constraints"]["cost_investment_constraint"][cost_index, loc_tech_index] = (
        @constraint(model_dict["backend_model"],
            variables["cost_investment"][cost, loc_tech] ==
            model_dict["expressions"]["investment_rhs"][cost, loc_tech]
        )
    )
    return
end

function update_costs_investment_purchase_constraint(model_dict, loc_tech, cost)
    """
    Add binary investment costs (cost * binary_purchased_unit)
    """
    variables = model_dict["variables"]
    sets = model_dict["sets"]
    ts_weight = get_timestep_weight(model_dict)
    depreciation_rate = model_dict["parameters"]["cost_depreciation_rate"][loc_tech, cost]

    cost_purchase = get_param(model_dict, "cost_purchase", [cost, loc_tech])
    cost_of_purchase = (
        variables["purchased"][loc_tech] * cost_purchase * ts_weight * depreciation_rate
    )

    append!(backend_model.investment_rhs[cost, loc_tech], cost_of_purchase)

    loc_tech_index = findin(sets["loc_carriers"], [loc_tech])
    cost_index = findin(sets["loc_carriers"], [cost])
    model_dict["constraints"]["cost_investment_constraint"][cost_index, loc_tech_index] = (
        @constraint(model_dict["backend_model"],
            variables["cost_investment"][cost, loc_tech] ==
            model_dict["expressions"]["investment_rhs"][cost, loc_tech]
        )
    )
    return
end

max_stars_repo_name: calliope-project/CalliopeJuMP

max_issues_repo_name: calliope-project/CalliopeJuMP

max_forks_repo_name: calliope-project/CalliopeJuMP


text:
# Error type and decoding functionality

export CuError

#
# Versioning error
#

struct CuVersionError <: Exception
    symbol::Symbol
    minver::VersionNumber
end

function Base.showerror(io::IO, err::CuVersionError)
    @printf(io, "CUDA API version mismatch: use of %s requires at least CUDA %s",
            err.symbol, err.minver)
end

#
# API errors
#

# forward declaration in base.jl

Base.:(==)(x::CuError,y::CuError) = x.code == y.code

# NOTE: `name` and `description` require CUDA to be initialized
#       (and do they work in case of error 100 or 999?)

"""
    name(err::CuError)

Gets the string representation of an error code.

This name can often be used as a symbol in source code to get an instance of this error.
For example:

```jldoctest
julia> using CUDAdrv

julia> err = CuError(1)
CuError(1, ERROR_INVALID_VALUE)

julia> name(err)
"ERROR_INVALID_VALUE"

julia> CUDAdrv.ERROR_INVALID_VALUE
CuError(1, ERROR_INVALID_VALUE)
```
"""
function name(err::CuError)
    str_ref = Ref{Cstring}()
    @apicall(:cuGetErrorName, (CuError_t, Ptr{Cstring}), err.code, str_ref)
    unsafe_string(str_ref[])[6:end]
end

"""
    description(err::CuError)

Gets the string description of an error code.
"""
function description(err::CuError)
    str_ref = Ref{Cstring}()
    @apicall(:cuGetErrorString, (CuError_t, Ptr{Cstring}), err.code, str_ref)
    unsafe_string(str_ref[])
end

function Base.showerror(io::IO, err::CuError)
    @printf(io, "CUDA error: %s (code #%d, %s)", description(err), err.code, name(err))

    if err.meta != nothing
        print(io, "\n")
        print(io, err.meta)
    end
end

Base.show(io::IO, err::CuError) = @printf(io, "CuError(%d, %s)", err.code, name(err))

# known error constants
const return_codes = Dict{CuError_t,Symbol}(
    0   => :SUCCESS,

    1   => :ERROR_INVALID_VALUE,
    2   => :ERROR_OUT_OF_MEMORY,
    3   => :ERROR_NOT_INITIALIZED,
    4   => :ERROR_DEINITIALIZED,
    5   => :ERROR_PROFILER_DISABLED,
    6   => :ERROR_PROFILER_NOT_INITIALIZED,
    7   => :ERROR_PROFILER_ALREADY_STARTED,
    8   => :ERROR_PROFILER_ALREADY_STOPPED,
    100 => :ERROR_NO_DEVICE,
    101 => :ERROR_INVALID_DEVICE,
    200 => :ERROR_INVALID_IMAGE,
    201 => :ERROR_INVALID_CONTEXT,
    202 => :ERROR_CONTEXT_ALREADY_CURRENT,
    205 => :ERROR_MAP_FAILED,
    206 => :ERROR_UNMAP_FAILED,
    207 => :ERROR_ARRAY_IS_MAPPED,
    208 => :ERROR_ALREADY_MAPPED,
    209 => :ERROR_NO_BINARY_FOR_GPU,
    210 => :ERROR_ALREADY_ACQUIRED,
    211 => :ERROR_NOT_MAPPED,
    212 => :ERROR_NOT_MAPPED_AS_ARRAY,
    213 => :ERROR_NOT_MAPPED_AS_POINTER,
    214 => :ERROR_ECC_UNCORRECTABLE,
    215 => :ERROR_UNSUPPORTED_LIMIT,
    216 => :ERROR_CONTEXT_ALREADY_IN_USE,
    217 => :ERROR_PEER_ACCESS_UNSUPPORTED,
    218 => :ERROR_INVALID_PTX,
    300 => :ERROR_INVALID_SOURCE,
    301 => :ERROR_FILE_NOT_FOUND,
    302 => :ERROR_SHARED_OBJECT_SYMBOL_NOT_FOUND,
    303 => :ERROR_SHARED_OBJECT_INIT_FAILED,
    304 => :ERROR_OPERATING_SYSTEM,
    400 => :ERROR_INVALID_HANDLE,
    500 => :ERROR_NOT_FOUND,
    600 => :ERROR_NOT_READY,
    700 => :ERROR_ILLEGAL_ADDRESS,
    701 => :ERROR_LAUNCH_OUT_OF_RESOURCES,
    702 => :ERROR_LAUNCH_TIMEOUT,
    703 => :ERROR_LAUNCH_INCOMPATIBLE_TEXTURING,
    704 => :ERROR_PEER_ACCESS_ALREADY_ENABLED,
    705 => :ERROR_PEER_ACCESS_NOT_ENABLED,
    708 => :ERROR_PRIMARY_CONTEXT_ACTIVE,
    709 => :ERROR_CONTEXT_IS_DESTROYED,
    710 => :ERROR_ASSERT,
    711 => :ERROR_TOO_MANY_PEERS,
    712 => :ERROR_HOST_MEMORY_ALREADY_REGISTERED,
    713 => :ERROR_HOST_MEMORY_NOT_REGISTERED,
    714 => :ERROR_HARDWARE_STACK_ERROR,
    715 => :ERROR_ILLEGAL_INSTRUCTION,
    716 => :ERROR_MISALIGNED_ADDRESS,
    717 => :ERROR_INVALID_ADDRESS_SPACE,
    718 => :ERROR_INVALID_PC,
    719 => :ERROR_LAUNCH_FAILED,
    800 => :ERROR_NOT_PERMITTED,
    801 => :ERROR_NOT_SUPPORTED,
    999 => :ERROR_UNKNOWN
)
for code in return_codes
    @eval const $(code[2]) = CuError($(code[1]))
end


text:
fatalerrors = length(ARGS) > 0 && ARGS[1] == "-f"
quiet = length(ARGS) > 0 && ARGS[1] == "-q"
errorfound = false

load_file = joinpath("src", "simulation", "load.jl")
include(normpath(joinpath(Base.source_dir(),"..",load_file)))

using Base.Test
using DataStructures
using ColorBrewer
using Gadfly
using Compat
using CSV
import Compat: UTF8String, ASCIIString, view

println("Running tests:")
filenames = ["kdrelationships.jl",
             "qualitymetrics.jl",
             "diffcrisprtransfection.jl",
             "processing.jl",
             "growth.jl",
             "selectionmethods.jl",
             "cmdline.jl"]

for filename in filenames
    try
        include(filename)
        println("\t\033[1m\033[32mPASSED\033[0m:  $(filename)")
    catch e
        errorfound = true
        println("\t\033[1m\033[31mFAILED\033[0m:  $(filename)")
        if fatalerrors
            rethrow(e)
        elseif !quiet
            showerror(STDOUT, e, backtrace())
            println()
        end
    end
end

analyses_path = normpath(joinpath(Base.source_dir(),"..",joinpath("src", "exps")))
analyses = readdir(analyses_path)
analyses = analyses[find(x -> x != "common.jl", analyses)]
# load common file first
include(joinpath(analyses_path, "common.jl"))
skipped = 0

for analysis in analyses
    try
        # skip testing with Gadfly on 32-bit machines, this is an
        # upstream problem
        if analysis == "gen_plots.jl" && Sys.WORD_SIZE != 64
            println("\t\033[1m\033[33mSKIPPED\033[0m: $(analysis)" *
            " # plotting library broken on 32bit machines")
            skipped+=1
            continue
        end
        include(joinpath(analyses_path, analysis))
        tempfile = tempname()
        func_name = Symbol(splitext(analysis)[1])
        getfield(Main, func_name)(tempfile, debug=true, quiet=true)
        println("\t\033[1m\033[32mPASSED\033[0m:  $(analysis)")
    catch e
        errorfound = true
        println("\t\033[1m\033[31mFAILED\033[0m:  $(analysis)")
        if fatalerrors
            rethrow(e)
        elseif !quiet
            showerror(STDOUT, e, backtrace())
            println()
        end
    end
end

if errorfound
    throw("Tests failed")
else
    println("All tests pass, $skipped test$(skipped == 1 ? "" : "s") skipped")
end