text:
Base.@kwdef mutable struct PNConstraintParams{T}
    solveropts::SolverOptions{T} = SolverOptions{T}()
    active_set_tolerance::T = 1e-3
    usedefault::Dict{Symbol,Bool} = Dict(:active_set_tolerance=>true)
end

function setparams!(conopts::PNConstraintParams; kwargs...)
    for (key,val) in pairs(kwargs)
        if key == :active_xet_tolerance
            conopts.active_set_tolerance = val
            conopts.usedefault[:active_set_tolerance] = false
        end
    end
end

function reset!(conopts::PNConstraintParams)
    if conopts.usedefault[:active_set_tolerance]
        conopts.active_set_tolerance = conopts.solveropts.active_set_tolerance_pn
    end
end

struct PNConstraint{T, C<:TO.StageConstraint, R<:SampledTrajectory}
    nx::Vector{Int}  # state dimension    # TODO: can we get rid of these fields?
    nu::Vector{Int}  # control dimension
    con::C
    sig::FunctionSignature
    diffmethod::DiffMethod
    inds::Vector{Int}             # knot point indices for constraint
    vals::Vector{VectorView{T,Int}}
    jac::Vector{Matrix{T}}
    jacviews::Vector{SparseBlockView{T,Int}}
    active::Vector{SubArray{Bool, 1, BitVector, Tuple{UnitRange{Int}}, true}}
    opts::PNConstraintParams{T}
    Z::Vector{R}
end

function PNConstraint(Z::R, con::TO.StageConstraint,
                      inds::AbstractVector{<:Integer}, d, a,
                      jacviews::Vector{<:SparseBlockView};
                      sig::FunctionSignature=RD.default_signature(con),
                      diffmethod::DiffMethod=RD.default_diffmethod(con),
                      solveropts::SolverOptions=SolverOptions()
    ) where {R<:SampledTrajectory}
    T = eltype(d)
    nx,nu,N = RD.dims(Z)
    p = RD.output_dim(con)
    P = length(inds)
    Np = RD.num_vars(Z)
    cinds = [view.block.block.i2 for view in jacviews]

    @assert length(cinds) == P
    @assert all(x->length(x) == p, cinds)

    # xi(k) = (k-1)*(n+m) .+ (1:n)
    # ui(k) = n + (k-1)*(n+m) .+ (1:m)
    # zi(k) = (k-1)*(n+m) .+ (k == N ? (1:n) : (1:n+m))
    vals = [view(d, ci .- Np) for ci in cinds]
    # jac = [view(D, cinds[i], zi(k)) for (i,k) in enumerate(inds)]
    jac = [zeros(T, size(view')) for view in jacviews]
    active = [view(a, ci .- Np) for ci in cinds]

    conopts = PNConstraintParams(solveropts=solveropts)
    reset!(conopts)
    PNConstraint(nx[inds], nu[inds], con, sig, diffmethod, collect(inds), vals, jac, jacviews, active, conopts, [Z])
end

function evaluate_constraints!(pncon::PNConstraint)
    # TODO: move this to a single check that runs before the solve
    if TO.sense(pncon.con) == TO.SecondOrderCone()
        error("ProjectedNewtonSolver doesn't support SecondOrderCone constraints.")
    end
    Z = pncon.Z[1]
    TO.evaluate_constraints!(pncon.sig, pncon.con, pncon.vals, Z, pncon.inds)
end

function constraint_jacobians!(pncon::PNConstraint)
    Z = pncon.Z[1]
    sig = function_signature(pncon)
    diff = pncon.diffmethod
    for (i,k) in enumerate(pncon.inds)
        jac = pncon.jac[i]
        jacview = pncon.jacviews[i]'
        RD.jacobian!(sig, diff, pncon.con, jac, pncon.vals[i], Z[k])
        jacview .= jac  # efficient copy to sparse array
    end
end

RD.vectype(pncon::PNConstraint) = RD.vectype(eltype(pncon.Z[1]))
settraj!(pncon::PNConstraint, Z::SampledTrajectory) = pncon.Z[1] = Z

function update_active_set!(pncon::PNConstraint)
    _update_active_set!(TO.sense(pncon.con), pncon)
    return nothing
end

_update_active_set!(::Equality, pncon::PNConstraint) = nothing
_update_active_set!(::SecondOrderCone, pncon::PNConstraint) = error("Cannot compute active set for SecondOrderCone constraints.")

function _update_active_set!(::Inequality, pncon::PNConstraint)
    tol = pncon.opts.active_set_tolerance
    p = RD.output_dim(pncon.con)
    c, a = pncon.vals, pncon.active
    for i in eachindex(pncon.inds)
        for j = 1:p
            a[i][j] = c[i][j] > -tol
        end
    end
end

function _update_active_set!(::TO.PositiveOrthant, pncon::PNConstraint)
    tol = pncon.opts.active_set_tolerance
    p = RD.output_dim(pncon.con)
    c, a = pncon.vals, pncon.active
    for i in eachindex(pncon.inds)
        for j = 1:p
            a[i][j] = c[i][j] < tol
        end
    end
end

function reset!(pncon::PNConstraint)
    reset!(pncon.opts)
end


text:
@testset "VariableCapacityBinPacking2BinPacking: $(fct_type), $(n_bins) bin, 2 items, $(T)" for fct_type in ["vector of variables", "vector affine function"], n_bins in [1, 2], T in [Int, Float64]
    mock = MOIU.MockOptimizer(BinPackingModel{T}())
    model = COIB.VariableCapacityBinPacking2BinPacking{T}(mock)

    if T == Int
        @test MOI.supports_constraint(model, MOI.VariableIndex, MOI.Integer)
    end
    @test MOI.supports_constraint(
        model,
        MOI.ScalarAffineFunction{T},
        MOI.LessThan{T},
    )
    @test MOI.supports_constraint(
        model,
        MOI.VectorOfVariables,
        CP.BinPacking{CP.NO_CAPACITY_BINPACKING, T},
    )
    @test MOIB.supports_bridging_constraint(
        model,
        MOI.VectorOfVariables,
        CP.BinPacking{CP.VARIABLE_CAPACITY_BINPACKING, T},
    )

    n_items = 2
    weights = T[3, 2]

    if T == Int
        x_load_1, _ = MOI.add_constrained_variable(model, MOI.Integer())
        x_capa_1, _ = MOI.add_constrained_variable(model, MOI.Integer())
        if n_bins == 1
            x_load_2 = nothing
            x_capa_2 = nothing
        elseif n_bins == 2
            x_load_2, _ = MOI.add_constrained_variable(model, MOI.Integer())
            x_capa_2, _ = MOI.add_constrained_variable(model, MOI.Integer())
        else
            @assert false
        end
    elseif T == Float64
        x_load_1 = MOI.add_variable(model)
        x_capa_1 = MOI.add_variable(model)
        if n_bins == 1
            x_load_2 = nothing
            x_capa_2 = nothing
        elseif n_bins == 2
            x_load_2 = MOI.add_variable(model)
            x_capa_2 = MOI.add_variable(model)
        else
            @assert false
        end
    end
    x_bin_1, _ = MOI.add_constrained_variable(model, MOI.Integer())
    x_bin_2, _ = MOI.add_constrained_variable(model, MOI.Integer())

    fct = if fct_type == "vector of variables"
        if n_bins == 1
            MOI.VectorOfVariables([x_load_1, x_capa_1, x_bin_1, x_bin_2])
        elseif n_bins == 2
            MOI.VectorOfVariables([x_load_1, x_load_2, x_capa_1, x_capa_2, x_bin_1, x_bin_2])
        else
            @assert false
        end
    elseif fct_type == "vector affine function"
        if n_bins == 1
            MOIU.vectorize([x_load_1, x_capa_1, x_bin_1, x_bin_2])
        elseif n_bins == 2
            MOIU.vectorize([x_load_1, x_load_2, x_capa_1, x_capa_2, x_bin_1, x_bin_2])
        else
            @assert false
        end
    else
        @assert false
    end
    c = MOI.add_constraint(model, fct, CP.BinPacking{CP.VARIABLE_CAPACITY_BINPACKING}(n_bins, n_items, weights))

    @test MOI.is_valid(model, x_load_1)
    if n_bins >= 2
        @test MOI.is_valid(model, x_load_2)
    end
    @test MOI.is_valid(model, x_bin_1)
    @test MOI.is_valid(model, x_bin_2)
    @test MOI.is_valid(model, c)

    bridge = MOIBC.bridges(model)[MOI.ConstraintIndex{MOI.VectorOfVariables, CP.BinPacking{CP.VARIABLE_CAPACITY_BINPACKING, T}}(-1)]

    @testset "Bridge properties" begin
        @test MOIBC.concrete_bridge_type(typeof(bridge), MOI.VectorOfVariables, CP.BinPacking{CP.VARIABLE_CAPACITY_BINPACKING, T}) == typeof(bridge)
        @test MOIB.added_constrained_variable_types(typeof(bridge)) == Tuple{Type}[]
        @test Set(MOIB.added_constraint_types(typeof(bridge))) == Set([
            (MOI.VectorAffineFunction{T}, CP.BinPacking{CP.NO_CAPACITY_BINPACKING, T}),
            (MOI.ScalarAffineFunction{T}, MOI.LessThan{T}),
        ])

        @test MOI.get(bridge, MOI.NumberOfVariables()) == zero(T)
        @test MOI.get(bridge, MOI.NumberOfConstraints{MOI.ScalarAffineFunction{T}, MOI.LessThan{T}}()) == n_bins
        @test MOI.get(bridge, MOI.NumberOfConstraints{MOI.VectorAffineFunction{T}, CP.BinPacking{CP.NO_CAPACITY_BINPACKING, T}}()) == 1

        @test MOI.get(bridge, MOI.ListOfConstraintIndices{MOI.ScalarAffineFunction{T}, MOI.LessThan{T}}()) == bridge.capa
        @test MOI.get(bridge, MOI.ListOfConstraintIndices{MOI.VectorAffineFunction{T}, CP.BinPacking{CP.NO_CAPACITY_BINPACKING, T}}()) == [bridge.bp]
    end

    @testset "BinPacking constraint" begin
        @test MOI.is_valid(model, bridge.bp)
        f = MOI.get(model, MOI.ConstraintFunction(), bridge.bp)
        @test length(f.terms) == n_items + n_bins
        for i in 1:n_items + n_bins
            @test f.terms[i].output_index == i
            @test f.terms[i].scalar_term.coefficient == 1
        end
        @test f.terms[1].scalar_term.variable == x_load_1
        if n_bins == 1
            @test f.terms[2].scalar_term.variable == x_bin_1
            @test f.terms[3].scalar_term.variable == x_bin_2
        elseif n_bins == 2
            @test f.terms[2].scalar_term.variable == x_load_2
            @test f.terms[3].scalar_term.variable == x_bin_1
            @test f.terms[4].scalar_term.variable == x_bin_2
        else
            @assert false
        end
        @test MOI.get(model, MOI.ConstraintSet(), bridge.bp) == CP.BinPacking{CP.NO_CAPACITY_BINPACKING}(n_bins, n_items, weights)
    end

    @testset "Capacity constraints" begin
        @test length(bridge.capa) == n_bins
        for i in 1:n_bins
            @test MOI.is_valid(model, bridge.capa[i])
            f = MOI.get(model, MOI.ConstraintFunction(), bridge.capa[i])
            @test length(f.terms) == 2
            @test f.terms[1].coefficient == 1
            @test f.terms[1].variable == ((i == 1) ? x_load_1 : x_load_2)
            @test f.terms[2].coefficient == -1
            @test f.terms[2].variable == ((i == 1) ? x_capa_1 : x_capa_2)
            @test MOI.get(model, MOI.ConstraintSet(), bridge.capa[i]) == MOI.LessThan(zero(T))
        end
    end
end

ext: jl


text:
module IOmodule
    using JLD2
    using ..Gaugefields
    import ..Gaugefields:GaugeFields,SU2GaugeFields,SU3GaugeFields,SUNGaugeFields
    #import Main.LatticeQCD.Gaugefields:GaugeFields

    function saveU(filename,x::Array{T,1}) where T <: Gaugefields.GaugeFields
        NX=x[1].NX
        NY=x[1].NY
        NZ=x[1].NZ
        NT=x[1].NT
        NC=x[1].NC
        NDW=x[1].NDW
        NV=x[1].NV
        save(filename,"NX",NX,"NY",NY,"NZ",NZ,"NT",NT,"NC",NC,"NDW",NDW,"NV",NV,"U",x)
        return
    end

    function loadU!(filename,U) #where T <: Gaugefields.GaugeFields

        NX=load(filename, "NX")
        NY=load(filename, "NY")
        NZ=load(filename, "NZ")
        NT=load(filename, "NT")
        NC=load(filename, "NC")
        NDW=load(filename, "NDW")
        NV=load(filename, "NV")

        @assert NX==U[1].NX
        @assert NY==U[1].NY
        @assert NZ==U[1].NZ
        @assert NT==U[1].NT
        @assert NC==U[1].NC
        @assert NDW==U[1].NDW
        @assert NV==U[1].NV

        #=
        if NC == 3
            Unew = Array{SU3GaugeFields,1}(undef,4)
        elseif NC == 2
            Unew = Array{SU2GaugeFields,1}(undef,4)
        elseif NC ≥ 4
            Unew = Array{SUNGaugeFields,1}(undef,4)
        end
        =#

        #Unew = jldopen(filename, "r") do file
        #    read(file, "U")
        #end

        Unew = load(filename, "U")
        for μ=1:4
            U[μ] = Unew[μ]
        end
        return
    end

    function loadU(filename) where T <: Gaugefields.GaugeFields
        NX=load(filename, "NX")
        NY=load(filename, "NY")
        NZ=load(filename, "NZ")
        NT=load(filename, "NT")
        NC=load(filename, "NC")
        NDW=load(filename, "NDW")
        NV=load(filename, "NV")

        return  load(filename, "U")

    end

    function loadU(filename,NX,NY,NZ,NT,NC) where T <: Gaugefields.GaugeFields
        @assert NX == load(filename, "NX") "NX in file $filename is $(load(filename, "NX")) but NX = $NX is set"
        @assert NY == load(filename, "NY") "NY in file $filename is $(load(filename, "NY")) but NY = $NY is set"
        @assert NZ == load(filename, "NZ") "NZ in file $filename is $(load(filename, "NZ")) but NZ = $NZ is set"
        @assert NT == load(filename, "NT") "NT in file $filename is $(load(filename, "NY")) but NT = $NT is set"
        @assert NC == load(filename, "NC") "NC in file $filename is $(load(filename, "NC")) but NC = $NC is set"
        NDW=load(filename, "NDW")
        NV=load(filename, "NV")

        return  load(filename, "U")
    end

    abstract type IOFormat end
end


text:
using Documenter, Slurm

makedocs(;
    modules=[Slurm],
    format=Documenter.HTML(),
    pages=[
        "Home" => "index.md",
    ],
    repo="https://github.com/singularitti/Slurm.jl/blob/{commit}{path}#L{line}",
    sitename="Slurm.jl",
    authors="Qi Zhang <singularitti@outlook.com>",
    assets=String[],
)

deploydocs(;
    repo="github.com/singularitti/Slurm.jl",
)


text:
using Logging, Random
using JuMP, Gurobi
using DecisionProgramming

include("min_expected_value.jl")

Random.seed!(13)

N = 4
L = [1]
R_k = [k + 1 for k in 1:N]
A_k = [(N + 1) + k for k in 1:N]
F = [2*N + 2]
T = [2*N + 3]
L_states = ["high", "low"]
R_k_states = ["high", "low"]
A_k_states = ["yes", "no"]
F_states = ["failure", "success"]
c_k = rand(N)
b = 0.03
fortification(k, a) = [c_k[k], 0][a]

@info("Creating the influence diagram.")
S = States([
    (length(L_states), L),
    (length(R_k_states), R_k),
    (length(A_k_states), A_k),
    (length(F_states), F)
])
C = Vector{ChanceNode}()
D = Vector{DecisionNode}()
V = Vector{ValueNode}()
X = Vector{Probabilities}()
Y = Vector{Consequences}()

for j in L
    I_j = Vector{Node}()
    X_j = zeros(S[I_j]..., S[j])
    X_j[1] = rand()
    X_j[2] = 1.0 - X_j[1]
    push!(C, ChanceNode(j, I_j))
    push!(X, Probabilities(j, X_j))
end

for j in R_k
    I_j = L
    x, y = rand(2)
    X_j = zeros(S[I_j]..., S[j])
    X_j[1, 1] = max(x, 1-x)
    X_j[1, 2] = 1.0 - X_j[1, 1]
    X_j[2, 2] = max(y, 1-y)
    X_j[2, 1] = 1.0 - X_j[2, 2]
    push!(C, ChanceNode(j, I_j))
    push!(X, Probabilities(j, X_j))
end

for (i, j) in zip(R_k, A_k)
    I_j = [i]
    push!(D, DecisionNode(j, I_j))
end

for j in F
    I_j = L ∪ A_k
    x, y = rand(2)
    X_j = zeros(S[I_j]..., S[j])
    for s in paths(S[A_k])
        d = exp(b * sum(fortification(k, a) for (k, a) in enumerate(s)))
        X_j[1, s..., 1] = max(x, 1-x) / d
        X_j[1, s..., 2] = 1.0 - X_j[1, s..., 1]
        X_j[2, s..., 1] = min(y, 1-y) / d
        X_j[2, s..., 2] = 1.0 - X_j[2, s..., 1]
    end
    push!(C, ChanceNode(j, I_j))
    push!(X, Probabilities(j, X_j))
end

for j in T
    I_j = A_k ∪ F
    Y_j = zeros(S[I_j]...)
    for s in paths(S[A_k])
        cost = sum(-fortification(k, a) for (k, a) in enumerate(s))
        Y_j[s..., 1] = cost + 0
        Y_j[s..., 2] = cost + 100
    end
    push!(V, ValueNode(j, I_j))
    push!(Y, Consequences(j, Y_j))
end

validate_influence_diagram(S, C, D, V)
sort!.((C, D, V, X, Y), by = x -> x.j)

P = DefaultPathProbability(C, X)
U = DefaultPathUtility(V, Y)

@info("Creating the decision model.")
U⁺ = PositivePathUtility(S, U)

k = length(X)  # choose failure node and its probability
# Strategy changes between ϵ 0.8 and 0.9
ϵ = 0.01  # we can try different parameters values here
deviations = [
    s_I => Deviation(X[k].data[s_I..., :], ϵ) for s_I in paths(S[C[k].I_j])
]

model = Model()
z = DecisionVariables(model, S, D)
(min_ev, mpevs) = min_expected_value(deviations, model, S, C, X, U⁺, z, k)
@objective(model, Max, min_ev)

@info("Starting the optimization process.")
optimizer = optimizer_with_attributes(
    () -> Gurobi.Optimizer(Gurobi.Env()),
    "IntFeasTol"      => 1e-9,
    # "LazyConstraints" => 1,
)
set_optimizer(model, optimizer)
optimize!(model)

@info("Construct minimizing path probability")
X′ = min_probabilities(mpevs, X, k)
P = DefaultPathProbability(C, X′)

@info("Reoptimize model with minimum path probability")
model2 = Model()
z2 = DecisionVariables(model2, S, D)
π_s = PathProbabilityVariables(model2, z2, S, P; hard_lower_bound=false)
probability_cut(model2, π_s, P)
# active_paths_cut(model2, π_s, S, P)
ev = expected_value(model2, π_s, U⁺)
@objective(model2, Max, ev)

optimizer2 = optimizer_with_attributes(
    () -> Gurobi.Optimizer(Gurobi.Env()),
    "IntFeasTol"      => 1e-9,
    "LazyConstraints" => 1,
)
set_optimizer(model2, optimizer2)
optimize!(model2)

@info("Extracting results.")
Z = DecisionStrategy(z)

@info("Printing decision strategy:")
print_decision_strategy(S, Z)

@info("Printing state probabilities:")
sprobs = StateProbabilities(S, P, Z)
print_state_probabilities(sprobs, L)
print_state_probabilities(sprobs, R_k)
print_state_probabilities(sprobs, A_k)
print_state_probabilities(sprobs, F)

@info("Computing utility distribution.")
udist = UtilityDistribution(S, P, U, Z)

@info("Printing utility distribution.")
print_utility_distribution(udist)

@info("Printing statistics")
print_statistics(udist)

max_stars_repo_name: jaantollander/RobustDecisionProgramming

max_issues_repo_name: jaantollander/RobustDecisionProgramming

max_forks_repo_name: jaantollander/RobustDecisionProgramming


text:
s = open("input.txt") do file
    readlines(file)
end

function CountTrees(lines)
    treeCount = 0;

    repeat = length(lines[1]);
    x = 4;
    for i = 2:length(lines)
        println(x);
        if lines[i][x] == '#'
            treeCount += 1;
        end
        x = ((x+2) % (repeat)) + 1
    end

    return treeCount;
end

CountTrees(s)


text: include("Triangulate/triangulate.jl")


text:
using Base: @_inline_meta

"""
    windowloop(f, k::Kernel{kx}, a::AbstractArray)

Loops through `a` while calling `f(w)` at every index.
`f` is passed a kernel window `w` of size at most `kx`, potentially cropped
according to the range of `k`.

NOTE: It is assumed `kx` can fit inside `a`.
"""
@generated function windowloop(f, kernel::Kernel{kx}, acc, op, a::AbstractArray...) where {kx}
    # this assumes kx fits inside axes(x)
    wx(pos) = intersect.(kx, map((x,y) -> first(x) - y : last(x) - y, kx, pos))

    a1 = first(a)

    function loop_expr(pos)
        # current loop dimension
        d = length(kx) - length(pos)

        if d == 0
            ks = (Symbol('k', i) for i in eachindex(kx))
            ki = :( CartesianIndex($(ks...),) )
            ai = (:( Window{$(wx(pos))}(kernel, a[$i], $ki) ) for i in eachindex(a))
            return :( acc = op(acc, f( $(ai...) )) )
        end

        exprs = Expr[]
        k = Symbol('k', d)

        # lower boundary
        for i in first(kx[d]) : -1
            (a1 <: ExtensionArray && a1.parameters[4] != ExtensionNone) || break
            push!(exprs, :($k = first(axes(a1, $d)) + $(i - first(kx[d]))))
            push!(exprs, loop_expr((i, pos...)))
        end

        # interior
        push!(exprs, Expr(:for, :($k = ilo[$d] : iup[$d]), Expr(:block, loop_expr((0, pos...)))))

        # upper boundary
        for i in 1 : last(kx[d])
            (a1 <: ExtensionArray && a1.parameters[4] != ExtensionNone) || break
            push!(exprs, :($k = last(axes(a1, $d)) - $(last(kx[d]) - i)))
            push!(exprs, loop_expr((i, pos...)))
        end

        return Expr(:block, exprs...)
    end

    return quote
        Base.@_noinline_meta

        a1 = first(a)
        # lower and upper limits for interior
        ilo = first.(axes(a1)) .+ $(.-first.(kx))
        iup = last.(axes(a1)) .- $(last.(kx))

        $(loop_expr(()))

        return acc
    end
end


text:
#------------------------------------------------------------------------------
# Author: Edward Tate <edward.tate@erlang-solutions.com>
#------------------------------------------------------------------------------
module FsBert
include("types.jl")
include("encode.jl")
include("decode.jl")
end

max_stars_repo_name: esl/FsBert

max_issues_repo_name: esl/FsBert

max_forks_repo_name: esl/FsBert


text:
# Utility functions

"""
    symm(C) -> C

Return a copy of C with the upper half copied into the lower half to enforce symmetry.
"""
symm(C) = symm!(deepcopy(C))

"""
    symm!(C) -> C

Fill in the lower half of 6x6 matrix `C` with the upper half, making it symmetrical,
and returning `C`.

If `C` is an `EC`, then we assume it is symmetrical, since it is impossible to make
an asymmetrical `EC` without directly accessing its `.data` field, which is not
a supported way of manipulating `EC`s.
"""
function symm!(C)
    for i in 1:6, j in i+1:6
        C[j,i] = C[i,j]
    end
    C
end
# Because setindex! sets both upper and lower halves, assume symmetrical.
# May not be true if c.data has been accessed directly.
symm!(c::EC) = c


text:
@generated function Carray{T, N, S}(::UndefInitializer) where {T, N, S}
	init = ((zero(UInt8) for _ in 1:S)...,)
	return :(Carray{T, N, S}(undef, $(init)))
end

(::Type{CA})(args...) where {CA<:Carray} = CA(undef, args...)
function (::Type{CA})(init::Union{NTuple{N, UInt8} where {N}, CA, Cbinding{CA}, Cptrs{CA}, UndefInitializer}, args...) where {CA<:Carray}
	result =
		init isa UndefInitializer ? bitstype(CA)(undef) :
		init isa Tuple ? bitstype(CA)(undef, init) :
		init isa Cbinding ? init[] :
		init isa Cptrs ? init[] :
		init

	for arg in args
		arg::Pair
		first(arg)::Integer

		result = setindex!(result, last(arg), first(arg))
	end

	return result
end

Base.zero(::Type{CA}) where {CA<:Carray} = CA()
Base.sizeof(::Type{CA}) where {CA<:Carray} = invoke(sizeof, Tuple{Any}, bitstype(CA))
Base.size(::Type{CA}) where {T, N, CA<:Carrays{T, N}} = (N,)
Base.length(::Type{CA}) where {T, N, CA<:Carrays{T, N}} = N
Base.eltype(::Type{CA}) where {T, N, CA<:Carrays{T, N}} = T

Base.firstindex(ca::CA) where {CA<:Carrays} = 1
Base.lastindex(ca::CA) where {CA<:Carrays} = length(ca)

Base.IndexStyle(::Type{CA}) where {CA<:Carrays} = IndexLinear()
Base.size(ca::CA) where {CA<:Carrays} = size(typeof(ca))
Base.length(ca::CA) where {CA<:Carrays} = length(typeof(ca))
Base.eltype(ca::CA) where {CA<:Carrays} = eltype(typeof(ca))

Base.keys(ca::CA) where {CA<:Carrays} = firstindex(ca):lastindex(ca)
Base.values(ca::CA) where {CA<:Carrays} = iterate(ca)
Base.iterate(ca::CA, i::Integer = 1) where {CA<:Carrays} = firstindex(ca) <= i <= lastindex(ca) ? (ca[i], i+1) : nothing

Base.getindex(ptr::Cptrs{CA}, i::Integer) where {T, N, CA<:Carrays{T, N}} = Core.Intrinsics.bitcast(Cptr{isqualifiedwith(CA, Cconst) && !isqualifiedwith(T, Cconst) ? Cconst{T} : T}, ptr) + (i-1)
Base.getindex(ca::CA, i::Integer) where {T, N, CA<:Carrays{T, N}} = load(ca, field(CA, i))

Base.setindex!(ptr::Cptrs{CA}, val, i::Integer) where {T, N, CA<:Carray{T, N}} = unsafe_store!(Core.Intrinsics.bitcast(Cptr{T}, ptr) + (i-1), val)
Base.setindex!(ca::CA, val, i::Integer) where {T, N, CA<:Carray{T, N}} = store!(ca, field(CA, i), val)


text:
"""
Core SearchLight configuration / settings functionality.
"""
module Configuration

import Revise
import YAML
using SearchLight, SearchLight.Exceptions

export isdev, isprod, istest, env, Settings, DEV, PROD, TEST

# app environments
const DEV   = "dev"
const PROD  = "prod"
const TEST  = "test"

haskey(ENV, "SEARCHLIGHT_ENV") || (ENV["SEARCHLIGHT_ENV"] = DEV)

"""
    isdev()  :: Bool
    isprod() :: Bool
    istest() :: Bool

Set of utility functions that return whether or not the current environment is development, production or testing.

# Examples
```julia
julia> Configuration.isdev()
true

julia> Configuration.isprod()
false
```
"""
function isdev()::Bool
  SearchLight.config.app_env == DEV
end
function isprod()::Bool
  SearchLight.config.app_env == PROD
end
function istest()::Bool
  SearchLight.config.app_env == TEST
end

"""
    env() :: String

Returns the current environment.

# Examples
```julia
julia> Configuration.env()
"dev"
```
"""
env() :: String = SearchLight.config.app_env

"""
    read_db_connection_data(db_settings_file::String) :: Dict{Any,Any}

Attempts to read the database configuration file and returns the part corresponding to the current environment as a `Dict`.
Does not check if `db_settings_file` actually exists so it can throw errors.
If the database connection information for the current environment does not exist, it returns an empty `Dict`.

# Examples
```julia
julia> Configuration.read_db_connection_data(...)
Dict{Any,Any} with 6 entries:
  "host"     => "localhost"
  "password" => "..."
  "username" => "..."
  "port"     => 5432
  "database" => "..."
  "adapter"  => "PostgreSQL"
```
"""
function read_db_connection_data(db_settings_file::String) :: Dict{String,Any}
  db_conn_data::Dict =  if endswith(db_settings_file, ".yml")
                          open(db_settings_file) do io
                            YAML.load(io)
                          end
                        elseif endswith(db_settings_file, ".jl")
                          include(db_settings_file)
                        end

  if  haskey(db_conn_data, "env") && db_conn_data["env"] != nothing
    ENV["SEARCHLIGHT_ENV"] =  if db_conn_data["env"] == """ENV["GENIE_ENV"]"""
                                ENV["GENIE_ENV"]
                              else
                                db_conn_data["env"]
                              end

    SearchLight.config.app_env = ENV["SEARCHLIGHT_ENV"]
  end

  if  haskey(db_conn_data, SearchLight.config.app_env) && haskey(db_conn_data[SearchLight.config.app_env], "config") &&
      db_conn_data[SearchLight.config.app_env]["config"] != nothing && isa(db_conn_data[SearchLight.config.app_env]["config"], Dict)
    for (k, v) in db_conn_data[SearchLight.config.app_env]["config"]
      setfield!(SearchLight.config, Symbol(k), ((isa(v, String) && startswith(v, ":")) ? Symbol(v[2:end]) : v) )
    end
  end

  return  if haskey(db_conn_data, SearchLight.config.app_env)
            db_conn_data[SearchLight.config.app_env]
          else
            throw(MissingDatabaseConfigurationException("DB configuration for $(SearchLight.config.app_env) not found"))

            Dict{String,Any}()
          end
end

"""
    load_db_connection() :: Bool

Attempts to load the database configuration from file. Returns `true` if successful, otherwise `false`.
"""
function load_db_connection(path::Union{String,Nothing} = nothing) :: Dict{String,Any}
  load_db_connection_from_config(path)
end

function load_db_connection_from_config(path::Union{String,Nothing} = nothing) :: Dict{String,Any}
  db_config_file = path === nothing ? joinpath(SearchLight.DB_PATH, SearchLight.SEARCHLIGHT_DB_CONFIG_FILE_NAME) : path
  read_db_connection_data(db_config_file)
end

function load(path::Union{String,Nothing} = nothing) :: Dict{String,Any}
  SearchLight.config.db_config_settings = load_db_connection(path)
end

"""
    mutable struct Settings

App configuration - sets up the app's defaults. Individual options are overwritten in the corresponding environment file.
"""
mutable struct Settings
  app_env::String

  db_migrations_table_name::String
  db_migrations_folder::String
  db_config_settings::Dict{String,Any}

  log_db::Bool
  log_queries::Bool
  log_level::Symbol
  log_formatted::Bool
  log_to_file::Bool

  Settings(;
            app_env       = ENV["SEARCHLIGHT_ENV"],

            db_migrations_table_name  = SearchLight.SEARCHLIGHT_MIGRATIONS_TABLE_NAME,
            db_migrations_folder      = SearchLight.MIGRATIONS_PATH,
            db_config_settings        = Dict{String,Any}(),

            log_db        = false,
            log_queries   = true,
            log_level     = :debug,
            log_formatted = true,
            log_to_file   = true
        ) =
              new(
                  app_env,
                  db_migrations_table_name, db_migrations_folder, db_config_settings,
                  log_db, log_queries, log_level, log_formatted, log_to_file
                )
end

end


text:
#=================================================================#
# xmlreader.jl
# author : Guillaume LEGRU
# date : 25 of October 2016
#
# An reader for the instances of the 2016 MOMH project.
#
#=================================================================#

#=================================================================#
# visitorXmlReader function
# args : file_name::String
# out : (preferenceMatrix, industrialNumber, researcherNumber)::(Array{Array{Any,1},1}, Int, Int)
function visitorXmlReader(file_name)
  @assert (typeof(file_name) == String)

  # XML tags variables
  isInHeader = false
  isInComment = false
  isInVisitorList = false
  isInIndustrialList = false
  isInResearcherList = false
  isInIndustrial = false
  isInResearcher = false
  isInPreferenceList = false

  # flags variable to create the preference matrix
  isResearcherNumberKnown = false
  isIndustrialNumberKnown = false
  isPreferencesMatrixCreated = false
  currentId = 0
  currentPreferedId = 0

  # returned variables
  industrialNumber = 0
  researcherNumber = 0
  preferenceMatrix = []

  visitor_file = open(file_name)

  for line in eachline(visitor_file)
    # ignoring the header
    if contains(line, "<?xml") || isInHeader
      if !contains(line, "?>")
        isInHeader = true
      else
        isInHeader = false
      end
      continue
    end

    # ignoring comments
    if contains(line, "<!--") || isInComment
      if !contains(line, "-->")
        isInComment = true
      else
        isInComment = false
      end
      continue
    end

    # acknowledge the <visitor_list> tag
    if !isInVisitorList && contains(line, "<visitor_list>")
      isInVisitorList = true
      continue
    end

    # in the visitor_list
    if isInVisitorList
      # acknowledge the </visitor_list> closing tag
      if contains(line, "</visitor_list>")
        isInVisitorList = false
        continue
      end

      # acknowledge the number of industrials
      if !isIndustrialNumberKnown && contains(line, "<industrial_list_size>") && contains(line, "</industrial_list_size>")
        industrialNumber = parse(Int, match(r"[0-9]+", line).match)
        isIndustrialNumberKnown = true
        continue
      end

      # acknowledge the number of researcher
      if !isResearcherNumberKnown && contains(line, "<researcher_list_size>") && contains(line, "</researcher_list_size>")
        researcherNumber = parse(Int, match(r"[0-9]+", line).match)
        isResearcherNumberKnown = true
        continue
      end

      # preference matrix creation (only once then locked)
      if !isPreferencesMatrixCreated && isResearcherNumberKnown && isIndustrialNumberKnown
        for i in 1:industrialNumber
          push!(preferenceMatrix, [])
          for j in 1:researcherNumber
            push!(preferenceMatrix[i], 0)
          end
        end
        isPreferencesMatrixCreated = true
      end

      # acknowledge the <industrial_list> tag
      if !isInIndustrialList && contains(line, "<industrial_list>")
        isInIndustrialList = true
        continue
      end

      # acknowledge the <researcher_list> tag
      if !isInResearcherList && contains(line, "<researcher_list>")
        isInResearcherList = true
        continue
      end

      # in the industrial_list
      if isInIndustrialList
        # acknowledge the </industrial_list> closing tag
        if contains(line, "</industrial_list>")
          isInIndustrialList = false
          continue
        end

        #acknowledge a <industrial> tag
        if !isInIndustrial && contains(line, "<industrial>")
          isInIndustrial = true
          continue
        end

        if isInIndustrial
          #acknowledge the </industrial> closing tag
          if contains(line, "</industrial>")
            isInIndustrial = false
            continue
          end

          # acknowledge the current ID
          if contains(line, "<id>") && !isInPreferenceList
            currentId = parse(Int, match(r"[0-9]+",line).match)
            continue
          end

          # acknowledge the current name (it is ignored, actually)
          if contains(line, "<name>") && !isInPreferenceList
            continue
          end

          # acknowledge the <preference_list> tag
          if !isInPreferenceList && contains(line, "<preference_list>")
            isInPreferenceList = true
            continue
          end

          if isInPreferenceList
            # acknowledge the </preference_list> exit tag
            if contains(line, "</preference_list>")
              isInPreferenceList = false
            end

            if !isInResearcher && contains(line, "<researcher>")
              isInResearcher = true
              continue
            end

            if isInResearcher
              #acknowledge the </researcher> closing tag
              if contains(line, "</researcher>")
                isInResearcher = false
                continue
              end

              # acknowledge teh current id in the preference list
              if contains(line, "<id>")
                currentPreferedId = parse(Int, match(r"[0-9]+",line).match)
                continue
              end

              #acknowledge tha name, ignored
              if contains(line, "name")
                continue
              end

              # acknowledge the preference matrix value and stores it
              if contains(line, "<preference_value>")
                @assert (currentId > 0 && currentId <= industrialNumber)
                @assert (currentPreferedId > 0 && currentPreferedId <= researcherNumber)
                preferenceMatrix[currentId][currentPreferedId] += parse(Int, match(r"[0-9]+",line).match)
              end
            end # isInResearcher
          end # isInPreferenceList
        end # isInIndustrial
      end # isInIndustrialList

      # in the researcher_list
      if isInResearcherList
        # acknowledge the </industrial_list> closing tag
        if contains(line, "</researcher_list>")
          isInResearcherList = false
          continue
        end

        #acknowledge a <researcher> tag
        if !isInResearcher && contains(line, "<researcher>")
          isInResearcher = true
          continue
        end

        if isInResearcher
          #acknowledge the </researcher> closing tag
          if contains(line, "</researcher>")
            isInResearcher = false
            continue
          end

          # acknowledge the current ID
          if contains(line, "<id>") && !isInPreferenceList
            currentId = parse(Int, match(r"[0-9]+",line).match)
            continue
          end

          # acknowledge the current name (it is ignored, actually)
          if contains(line, "<name>") && !isInPreferenceList
            continue
          end

          # acknowledge the <preference_list> tag
          if !isInPreferenceList && contains(line, "<preference_list>")
            isInPreferenceList = true
            continue
          end

          if isInPreferenceList
            # acknowledge the </preference_list> exit tag
            if contains(line, "</preference_list>")
              isInPreferenceList = false
            end

            if !isInIndustrial && contains(line, "<industrial>")
              isInIndustrial = true
              continue
            end

            if isInIndustrial
              # acknowledge the </industrial> closing tag
              if contains(line, "</industrial>")
                isInIndustrial = false
                continue
              end

              # acknowledge the current id in the preference list
              if contains(line, "<id>")
                currentPreferedId = parse(Int, match(r"[0-9]+",line).match)
                continue
              end

              # acknowledge tha name, ignored
              if contains(line, "name")
                continue
              end

              # acknowledge the preference matrix value and stores it
              if contains(line, "<preference_value>")
                @assert (currentId > 0 && currentId <= researcherNumber)
                @assert (currentPreferedId > 0 && currentPreferedId <= industrialNumber)
                preferenceMatrix[currentPreferedId][currentId] += parse(Int, match(r"[0-9]+",line).match)
              end
            end # isInIndustrial
          end # isInPreferenceList
        end # isInResearcher
      end # isInResearcherList
    end # isInVisitorList
  end # file reading
  close(visitor_file)

  return preferenceMatrix, industrialNumber, researcherNumber
end # function visitorXmlReader

#=================================================================#
# roomXmlReader function
# args : file_name::String
# out : (preferenceMatrix, industrialNumber, researcherNumber)::(Array{Array{Any,1},1}, Int, Int)
function roomXmlReader(file_name)
  @assert (typeof(file_name) == String)

  # XML tags variables
  isInHeader = false
  isInComment = false
  isInRoomList = false
  isInDepartureRoom = false
  isInArrivalRoom = false
  isInDistancesList = false

  # flags variable to create the preference matrix
  isRoomNumberKnown = false
  isDistancesMatrixCreated = false
  currentDepartureRoom = 0
  currentArrivalRoom = 0

  # returned variables
  roomNumber = 0
  distancesMatrix = []

  room_file = open(file_name)

  for line in eachline(room_file)
    # ignoring the header
    if contains(line, "<?xml") || isInHeader
      if !contains(line, "?>")
        isInHeader = true
      else
        isInHeader = false
      end
      continue
    end

    # ignoring comments
    if contains(line, "<!--") || isInComment
      if !contains(line, "-->")
        isInComment = true
      else
        isInComment = false
      end
      continue
    end

    # acknowledge the <room_list> tag
    if !isInRoomList && contains(line, "<room_list>")
      isInRoomList = true
      continue
    end

    if isInRoomList
      # acknowledge the </room_list> closing tag
      if contains(line, "</room_list>")
        isInRoomList = false
        continue
      end

      #acknowledge the number of room
      if contains(line, "<room_number>")
        roomNumber = parse(Int, match(r"[0-9]+",line).match)
        isRoomNumberKnown = true
        continue
      end

      # create the distance matrix then lock
      if !isDistancesMatrixCreated && isRoomNumberKnown
        for i in 1:roomNumber
          push!(distancesMatrix, [])
          for j in 1:roomNumber
            push!(distancesMatrix[i], 0)
          end
        end
        isDistancesMatrixCreated = true
      end

      #acknowledge a first <room> tag
      if !isInDepartureRoom && contains(line, "<room>")
        isInDepartureRoom = true
        continue
      end

      if isInDepartureRoom
        # acknowledge the </room> closing tag
        if contains(line, "</room>") && !isInDistancesList
          isInDepartureRoom = false
          continue
        end

        # acknowledge the id of the departure room
        if contains(line, "<id>") && !isInDistancesList
          currentDepartureRoom = parse(Int, match(r"[0-9]+",line).match)
          continue
        end

        if !isInDistancesList && contains(line, "<distances_list>")
          isInDistancesList = true
          continue
        end

        if isInDistancesList
          if contains(line, "</distances_list>")
            isInDistancesList = false
            continue
          end
          #acknowledge a second <room> tag
          if !isInArrivalRoom && contains(line, "<room>")
            isInArrivalRoom = true
            continue
          end

          if isInArrivalRoom
            # acknowledge the </room> closing tag
            if contains(line, "</room>")
              isInArrivalRoom = false
              continue
            end

            # acknowledge the id of the arrival room
            if contains(line, "<id>")
              currentArrivalRoom = parse(Int, match(r"[0-9]+",line).match)
              continue
            end

            # fills the distance matrix
            # Notice that it is filled when the value in the matrix is 0, because the matrix is supposed to be symetric
            if contains(line, "<distance>")
              @assert (currentDepartureRoom  > 0 && currentDepartureRoom <= roomNumber)
              @assert (currentArrivalRoom > 0 && currentArrivalRoom <= roomNumber)
              if distancesMatrix[currentDepartureRoom][currentArrivalRoom] == 0
                distancesMatrix[currentDepartureRoom][currentArrivalRoom] = parse(Int, match(r"[0-9]+",line).match)
              end
              continue
            end
          end # arrival room
        end #distances_list
      end # departure room
    end # room_list
  end # file reading

  return distancesMatrix, roomNumber

end # function roomXmlReader


text:
# MCMCSol post-proc

"""
$(SIGNATURES)

Return h and iv at the locations where the 1D parameters
are by averaging (weighted by elevation band area).
"""
function h_iv_at_thetas(theta0::Theta0, mc_hs1d, mc_ivs1d; elebins=Float64[])
    gb = theta0.gb
    if elebins==Float64[]
        eles = []
        for k in [:btilde, :temp, :fsl]
            if haskey(theta0.th_ele, k)
                push!(eles, theta0.th_ele[k])
            end
        end
        ele = eles[findmax(length.(eles))[2]]
        elebins = [gb.bands_[1]; ele[1:end-1] + diff(ele)/2; gb.bands_[end]]
    end
    # find indices of bins
    inds = UnitRange{Int}[]
    for (b1,b2) in zip(elebins[1:end-1],elebins[2:end])
        push!(inds, findfirst(gb.ele.<=b1):findlast(gb.ele.>b2))
    end
    @assert [inds...;]==collect(1:length(gb))
    @assert all(length.(inds).>0)

    h_at_th = Array{F}(length(inds),size(mc_ivs1d,2))
    iv_at_th = Array{F}(length(inds),size(mc_ivs1d,2))
    for i=1:size(mc_ivs1d,2)
        for (j,ind) in enumerate(inds)
            h_at_th[j,i] = sum(gb.ws[ind].*gb.ls[ind].*mc_hs1d[ind,i]) /
                sum(gb.ws[ind].*gb.ls[ind])
            iv_at_th[j,i] = sum(gb.ws[ind].*gb.ls[ind].*mc_ivs1d[ind,i]) /
                sum(gb.ws[ind].*gb.ls[ind])
        end
    end
    return h_at_th, iv_at_th
end

"""
$(SIGNATURES)

Return mean h and iv weighted by elevation band area.
"""
function h_iv_mean(mc_hs1d, mc_ivs1d, theta0::Theta0)
    gb = theta0.gb

    h_mean = Vector{F}(size(mc_ivs1d,2))
    iv_mean = Vector{F}(size(mc_ivs1d,2))
    for i=1:size(mc_ivs1d,2)
        h_mean[i] = sum(gb.ws.*gb.ls.*mc_hs1d[:,i]) /
            sum(gb.ws.*gb.ls)
        iv_mean[i] = sum(gb.ws.*gb.ls.*mc_ivs1d[:,i]) /
            sum(gb.ws.*gb.ls)
    end
    return h_mean, iv_mean
end

"""
$(SIGNATURES)

Condenses the MCMCSol into something manageable.

If store2d==true, then also store 2D fields (uses lots of space)

Uses only basic Julia types for storage to enable easy writing to a
file and future-proofing it.
"""
function condense_MCMCSol(sol::MCMCSol{T}; store2d=false, store_thetas=false) where T
#    error("add h error when there is radar")

    @unpack bands_, gl = sol.theta0.gb
    @unpack x, y = gl.dem
    dx = step(x)
    out = Dict{Symbol,Any}()

    # glacier
    out[:rgi] = getrgi(gl.gid)
    out[:area_km2] = area(gl) / 1e6
    out[:volarea_km3] = volume_area_mean_h(gl) * area(gl) /1e9
    out[:proj] = gl.dem.proj
    out[:fit_target] = string(sol.misc[:fit_target])

    # collect the ranges for future-proofing:
    out[:x] = collect(gl.dem.x)
    out[:y] = collect(gl.dem.y)
    out[:bands] = collect(bands_)

    if !(T<:Void)
        # 0D
        out[:vol_km3] = type2dict(StatsBase.summarystats(sol.vols./1e9))
        out[:vol_above_km3] = type2dict(StatsBase.summarystats(sol.vols_above./1e9))

        # reduce number of samples of vols
        nsamples = length(sol.vols)
        thin = if nsamples==sol.solverstats[:nsamples]
            max(sol.solverstats[:τ],1)
        else
            1
        end
        inds = thin==-1 ? (1:nsamples) : (1:thin:nsamples)
        # we want at most between 250 and 500 samples
        if length(inds)>250
            inds = inds[1:(length(inds)÷150):end]
        end
        out[:mc_vols] = sol.vols[inds]
        out[:mc_vols_above] = sol.vols_above[inds]

        # 1D vars
        out[:hs1d] = mean(sol.mc_hs1d,2)
        out[:hs1d_std] = std(sol.mc_hs1d,2)
        out[:hs1d_min] = minimum(sol.mc_hs1d,2)
        out[:hs1d_max] = maximum(sol.mc_hs1d,2)

        out[:ivs1d] = mean(sol.mc_ivs1d,2)
        out[:ivs1d_std] = std(sol.mc_ivs1d,2)
        out[:ivs1d_min] = minimum(sol.mc_ivs1d,2)
        out[:ivs1d_max] = maximum(sol.mc_ivs1d,2)

        # 2D vars
        if store2d
            out[:hs] = sol.mh2d
            out[:hs_std] = sol.sh2d
            out[:hs_min] = sol.min_h2d
            out[:hs_max] = sol.max_h2d

            out[:ivs] = sol.miv2d
            out[:ivs_std] = sol.siv2d
            out[:ivs_min] = sol.min_iv2d
            out[:ivs_max] = sol.max_iv2d
        end
    end

    # thetas
    if store_thetas
        out[:thetas] = sol.thetas
        out[:reshape_revert] = sol.reshape_revert
    end
    out[:thetas_expect] = sol.theta_expect
    out[:thetas_std] = sol.thetas_std
    out[:thetas_minmax] = sol.thetas_minmax
    out[:thetas_mode] = sol.theta_mode
    out[:thetas_quartiles] = [quantile(sol.thetas[i,:], [0.25, 0.5, 0.75]) for i=1:size(sol.thetas,1)]
    out[:thetas_quant_95] = [quantile(sol.thetas[i,:], [0.05, 0.95]) for i=1:size(sol.thetas,1)] # as in ITMIX paper plots

    # others
    out[:theta0] = Dict(:th0 => sol.theta0.th0,
                        :names => [k=>collect(v) for (k,v) in sol.theta0.names],
                        :th_ele => [k=>collect(v) for (k,v) in sol.theta0.th_ele])

    out[:solverstats] = sol.solverstats
    out[:pmcmc] = Parameters.type2dict(sol.pmcmc)
    out[:pm] = Parameters.type2dict(sol.theta0.pm)
    out[:pn] = Parameters.type2dict(sol.theta0.pn)
    out[:pp] = Parameters.type2dict(sol.theta0.pp)
    pop!(out[:pmcmc], :sample_ppdf)

    # errors statistics
    ae, _, err = compare_to_radar(sol)
    out[:abserr_h] = type2dict(ae[1])
    out[:err_h] = type2dict(err[1])
    # TODO iv errors

    return out
end

function retrace_samples_condensed_MCMCSol(o::Dict)
    (gid, gl, gb, pp, pm, pn, pl, th0d,
     theta0, logposterior, logposterior1d, logprior, logprior_debug,
     loglikelihood, loglikelihood1d, fwdm_fn, fwdm1d_fn,
     pmcmc_defaults, fit_target) = init(o[:rgi])

    _retrace_samples(logposterior, o[:thetas], pmcmc::MCMCNum, demsize,
                          nsamples, verbose, use_progress_meter,
                          logdensity_vals,  # we want the density of the original pdf not the resampled one
                          solverstats)
end

"""
$(SIGNATURES)

Makes
"""
function make_geotiff(sol::MCMCSol, fln)

    # make gridded
    @unpack bands_, gl = sol.theta0.gb
    @unpack x, y, proj = gl.dem
    @unpack glaciermask = gl
    dx = step(x)
    z = Matrix{Float32}(0,0)

    exp = Gridded{Float32}(x, y, sol.mh2d, z, true, proj)
    std = Gridded{Float32}(x, y, sol.sh2d, z, true, proj)
    min = Gridded{Float32}(x, y, sol.min_h2d, z, true, proj)
    max = Gridded{Float32}(x, y, sol.max_h2d, z, true, proj)

    VAWTools.write_geotiff([exp, std, min, max], fln, nodataval=0.0)
end


text:
using Plots;                            #Use the Package Plots
gr()                                    #Set Backend to gr for the package Plots
arr=[1,2,3,4,2,7,9,-5,-3,5,5,4];        #Create an Array
myPlot = plot(arr);                     #Create a Object of the graphic
display(myPlot);                        #Show plot in Window

max_stars_repo_name: RainerNeu/juliaExamplesWithJuliaPro

max_issues_repo_name: RainerNeu/juliaExamplesWithJuliaPro

max_forks_repo_name: RainerNeu/juliaExamplesWithJuliaPro


text:
module EnvNoise

using DSP
# Write your package code here.
include("ptiread.jl")
include("weightingFilter.jl")
include("pwelch.jl")

export filt, welch_pgram, Windows

end


text:
const LOCALZONE = localzone()

immutable Tz
   isvalid::Int8
   hour::Int8
   minute::Int8
end

# parse a timezone agnostic datetime
function parsedate(s)
    useconds = ccall((:parseiso8601, libfdt), Int64, (Ptr{UInt8}, Ptr{Void}), s, C_NULL)
    DateTime(Base.Dates.UTM(Base.Dates.Millisecond(div(useconds, 1000))))
end
parsedate{T<:AbstractString}(a::Vector{T}) = map(parsedate, a)

# parse a timezone aware datetime
function parsedatetz(s)
    tz = Tz(0,0,0)
    useconds = ccall((:parseiso8601, libfdt), Int64, (Ptr{UInt8}, Ptr{Void}), s, pointer_from_objref(tz))
    d = DateTime(Base.Dates.UTM(Base.Dates.Millisecond(div(useconds, 1000))))
    if tz.isvalid == 1
        z = FixedTimeZone("", TimeZones.Offset(tz.hour*60*60 + tz.minute*60, 0))
    else
        z = LOCALZONE
    end
    ZonedDateTime(d, z)
end
parsedatetz{T<:AbstractString}(a::Vector{T}) = map(parsedatetz, a)

max_stars_repo_name: tanmaykm/Chrono

max_issues_repo_name: tanmaykm/Chrono

max_forks_repo_name: tanmaykm/Chrono


text:
# A* shortest-path algorithm

#################################################
#
#  A* shortest-path algorithm
#
#################################################

module AStar

# The enqueue! and dequeue! methods defined in Base.Collections (needed for
# PriorityQueues) conflict with those used for queues. Hence we wrap the A*
# code in its own module.

using Graphs
using DataStructures

export shortest_path

mkindx(t) = typeof(t) == Int ? t : t.index

function a_star_impl!(
    graph::AbstractGraph{V},# the graph
    frontier,               # an initialized heap containing the active vertices
    colormap::Vector{Int},  # an (initialized) color-map to indicate status of vertices
    edge_dists::AbstractEdgePropertyInspector{D},  # cost of each edge
    heuristic::Function,    # heuristic fn (under)estimating distance to target
    t::V) where {V,D} # the end vertex

    tindx = mkindx(t)

    while !isempty(frontier)
        (cost_so_far, path, u) = DataStructures.dequeue!(frontier)
        uindx = mkindx(u)
        if uindx == tindx
            return path
        end

        for edge in out_edges(u, graph)
            v = target(edge)
            vindx = mkindx(v)
            if colormap[vindx] < 2
                colormap[vindx] = 1
                new_path = cat(path, edge, dims=1)
                path_cost = cost_so_far + edge_property(edge_dists, edge, graph)
                DataStructures.enqueue!(frontier,
                        (path_cost, new_path, v),
                        path_cost + heuristic(vindx))
            end
        end
        colormap[uindx] = 2
    end
    nothing
end

function shortest_path(
    graph::AbstractGraph{V,E},  # the graph
    edge_dists::AbstractEdgePropertyInspector{D},      # cost of each edge
    s::V,                       # the start vertex
    t::V,                       # the end vertex
    heuristic::Function = n -> 0) where {V,E,D} # heuristic (under)estimating distance to target
    #
    frontier = DataStructures.PriorityQueue{Tuple{D,Array{E,1},V},D}()
    # frontier = DataStructures.PriorityQueue(Tuple{D,Array{E,1},V},D)
    frontier[(zero(D), E[], s)] = zero(D)
    colormap = zeros(Int, num_vertices(graph))
    sindx = mkindx(s)
    colormap[sindx] = 1
    a_star_impl!(graph, frontier, colormap, edge_dists, heuristic, t)
end

function shortest_path(
    graph::AbstractGraph{V,E},  # the graph
    edge_dists::Vector{D},      # cost of each edge
    s::V,                       # the start vertex
    t::V,                       # the end vertex
    heuristic::Function = n -> 0 )  where {V,E,D}
    #
    edge_len::AbstractEdgePropertyInspector{D} = VectorEdgePropertyInspector(edge_dists)
    shortest_path(graph, edge_len, s, t, heuristic)
end

end

using .AStar


text:
using List
using Base.Test

# write your own tests here
@test 1 == 1 # this better not fail

lst = DoublyLinkedList{Int64}()
push!(lst, 3);
@test length(lst) == 1;
@test lst.head.val == 3;
@test lst.tail.val == 3;
@test lst.head == lst.tail;

push!(lst, rand(1:100, 4));
@test length(lst) == 5;
@test lst.head.val == 3;
@test lst.head.prev == nothing;
@test lst.head.next.prev.val == 3;

push!(lst, 1);
push!(lst, 2);
push!(lst, 3);
println("This list contains...");
for node in lst
  println(node.val);
end
pnode = remove!(lst, 6);
println("The sixth element was...");
println(pnode.val);
@test pnode.val == 1;
@test length(lst) == 7;

println("This list contains...");
for node in lst
  println(node.val);
end

empty!(lst);
@test length(lst) == 0
@test lst.head == nothing
@test lst.tail == nothing

some_array = rand(-50:50, 50);
@test push!(lst, some_array) == 50;
for i=1:50
  @test shift!(lst).val == some_array[i];
end

some_array = rand(-50:50, 50);
@test push!(lst, some_array) == 50;
for i=50:-1:1
  @test pop!(lst).val == some_array[i];
end

println("This list contains...");
for node in lst
  println(node.val);
end
println("and is length ", length(lst));

@test length(lst) == 0;
@test lst.head == nothing;
@test lst.tail == nothing;

@test unshift!(lst, 9) == 1;
@test unshift!(lst, 8) == 2;
@test unshift!(lst, 7) == 3;
@test unshift!(lst, 6) == 4;
@test unshift!(lst, 5) == 5;
@test unshift!(lst, 4) == 6;
@test unshift!(lst, 3) == 7;
@test unshift!(lst, 2) == 8;
@test unshift!(lst, 1) == 9;

@test remove!(lst, 7).val == 7;
@test remove!(lst, 7).val == 8;
@test length(lst) == 7;
@test remove!(lst, 7).val == 9;
@test remove!(lst, 3).val == 3;
@test remove!(lst, 2).val == 2;
@test remove!(lst, 1).val == 1;
@test remove!(lst, 2).val == 5;
@test remove!(lst, 2).val == 6;
@test remove!(lst, lst.head).val == 4;

some_array = rand(-50:50, 50);
@test unshift!(lst, some_array) == 50;
for i=50:-1:1
  @test shift!(lst).val == some_array[i];
end

some_array = rand(-50:50, 50);
@test unshift!(lst, some_array) == 50;
for i=1:50
  @test pop!(lst).val == some_array[i];
end

t = (2, 3, 5, 1, 4);
lst = DoublyLinkedList{Int64}(t...);
for i=1:length(t);
  @test remove!(lst, 1).val == t[i];
end

println("DOUBLY LINKED LIST TESTS PASSED!");

# write your own tests here
@test 1 == 1 # this better not fail

lst = SinglyLinkedList{Int64}()
push!(lst, 3);
@test length(lst) == 1;
@test lst.head.val == 3;
@test lst.tail.val == 3;
@test lst.head == lst.tail;

push!(lst, rand(1:100, 4));
@test length(lst) == 5;
@test lst.head.val == 3;

push!(lst, 1);
push!(lst, 2);
push!(lst, 3);
println("This list contains...");
for node in lst
  println(node.val);
end
pnode = remove!(lst, 6);
println("The sixth element was...");
println(pnode.val);
@test pnode.val == 1;
@test length(lst) == 7;

println("This list contains...");
for node in lst
  println(node.val);
end

empty!(lst);
@test length(lst) == 0
@test lst.head == nothing
@test lst.tail == nothing

some_array = rand(-50:50, 50);
@test push!(lst, some_array) == 50;
for i=1:50
  @test shift!(lst).val == some_array[i];
end

some_array = rand(-50:50, 50);
@test push!(lst, some_array) == 50;
for i=50:-1:1
  @test pop!(lst).val == some_array[i];
end

println("This list contains...");
for node in lst
  println(node.val);
end
println("and is length ", length(lst));

@test length(lst) == 0;
@test lst.head == nothing;
@test lst.tail == nothing;

@test unshift!(lst, 9) == 1;
@test unshift!(lst, 8) == 2;
@test unshift!(lst, 7) == 3;
@test unshift!(lst, 6) == 4;
@test unshift!(lst, 5) == 5;
@test unshift!(lst, 4) == 6;
@test unshift!(lst, 3) == 7;
@test unshift!(lst, 2) == 8;
@test unshift!(lst, 1) == 9;

@test remove!(lst, 7).val == 7;
@test remove!(lst, 7).val == 8;
@test length(lst) == 7;
@test remove!(lst, 7).val == 9;
@test remove!(lst, 3).val == 3;
@test remove!(lst, 2).val == 2;
@test remove!(lst, 1).val == 1;
@test remove!(lst, 2).val == 5;
@test remove!(lst, 2).val == 6;
@test pop!(lst).val == 4;

some_array = rand(-50:50, 50);
@test unshift!(lst, some_array) == 50;
for i=50:-1:1
  @test shift!(lst).val == some_array[i];
end

some_array = rand(-50:50, 50);
@test unshift!(lst, some_array) == 50;
for i=1:50
  @test pop!(lst).val == some_array[i];
end

t = (2, 3, 5, 1, 4);
lst = DoublyLinkedList{Int64}(t...);
for i=1:length(t);
  @test remove!(lst, 1).val == t[i];
end

println("SINGLY LINKED LIST TESTS PASSED!");


text:
mutable struct CIFAR10Model
    # W* - weight; b* - bias; c1 - convolution 1; fc1 - fully connected 1
    Wc1    # (H,W,I,O) == (5,5,3,6)
    Wc2    # (H,W,I,O) == (5,5,6,16)
    Wfc1   # (120, 16*5*5)
    bfc1   # (120,)
    Wfc2   # (84,120)
    bfc2   # (84,)
    Wfc3   # (10,84)
    bfc3   # (10,)
end

CIFAR10Model() = CIFAR10Model(
    randn(5, 5, 3, 6) / (5 * 5 * 3 * 6),
    randn(5, 5, 6, 16) / (5 * 5 * 6 * 16),
    xavier_init(120, 16*5*5),
    randn(120) / 120,
    xavier_init(84, 120),
    randn(84) / 84,
    xavier_init(10, 84),
    randn(10) / 10
)

Base.show(io::IO, m::CIFAR10Model) = print(io, "CIFAR10Model()")

function predict(m::CIFAR10Model, X::AbstractArray{<:AbstractFloat, 4})
    c1 = conv2d(X, m.Wc1)  # 32x32x3xN => 28x28x6xN
    p1 = pool(relu.(c1); stride=2)
    c2 = conv2d(p1, m.Wc2)  # 14x14x6xN => 10x10x16xN
    p2 = pool(relu.(c2); stride=2)
    c2_f = reshape(p2, 400, size(p2, 4))
    fc1 = relu.(m.Wfc1 * c2_f .+ m.bfc1)
    fc2 = relu.(m.Wfc2 * fc1 .+ m.bfc2)
    fc3 = sigmoid.(m.Wfc3 * fc2 .+ m.bfc3)
    return fc3
end

function loss(m::CIFAR10Model, X::AbstractArray{F, 4}, y::AbstractMatrix{F}) where {F <:AbstractFloat}
    ŷ = predict(m, X)
    return cross_entropy_loss(ŷ, y)
end

function partial_fit!(m::CIFAR10Model, X::AbstractArray, y::AbstractMatrix; mem=Dict())
    opt = ModelOptimizer(m, Momentum(η=0.05, γ=0.9))
    # opt = ModelOptimizer(m, Adam(α=0.01))
    cost, dm, dX, dy = xgrad(loss; mem=mem, m=m, X=X, y=y)
    update_params!(opt, m, dm)
    return cost
end

function fit!(m, X::AbstractArray, Y::AbstractMatrix; cuda=false, n_epochs=100)
    mem = Dict()
    if cuda
        m = to_cuda(m)
    end
    @time for epoch=1:n_epochs
        print("Epoch: $epoch: ")
        cost = 0
        for (x, y) in batchview((X, Y); size=100)
            x, y = map(copy, (x, y))
            if cuda
                x, y = map(to_cuda, (x, y))
            end
            cost = partial_fit!(m, x, y; mem=mem)
        end
        println(cost)
    end
    return m
end

# function fit!(m::CIFAR10Model, X::AbstractArray, Y::AbstractMatrix)
#     mem = Dict()
#     for epoch=1:10
#         info("Epoch: $epoch")
#         for (x, y) in batchview((X, Y))
#             cost = partial_fit!(m, copy(x), copy(y); mem=mem)
#             info("cost: $cost")
#         end
#     end
#     return m
# end


text:
# syntax: proto2
using ProtoBuf
import ProtoBuf.meta

struct __enum_Version <: ProtoEnum
    _START_VERSION::Int32
    IR_VERSION_2017_10_10::Int32
    IR_VERSION_2017_10_30::Int32
    IR_VERSION_2017_11_3::Int32
    IR_VERSION_2019_1_22::Int32
    IR_VERSION_2019_3_18::Int32
    IR_VERSION_2019_9_19::Int32
    IR_VERSION::Int32
    __enum_Version() = new(0,1,2,3,4,5,6,7)
end #struct __enum_Version
const Version = __enum_Version()

mutable struct StringStringEntryProto <: ProtoType
    key::AbstractString
    value::AbstractString
    StringStringEntryProto(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct StringStringEntryProto

mutable struct TensorAnnotation <: ProtoType
    tensor_name::AbstractString
    quant_parameter_tensor_names::Base.Vector{StringStringEntryProto}
    TensorAnnotation(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct TensorAnnotation

struct __enum_TensorProto_DataType <: ProtoEnum
    UNDEFINED::Int32
    FLOAT::Int32
    UINT8::Int32
    INT8::Int32
    UINT16::Int32
    INT16::Int32
    INT32::Int32
    INT64::Int32
    STRING::Int32
    BOOL::Int32
    FLOAT16::Int32
    DOUBLE::Int32
    UINT32::Int32
    UINT64::Int32
    COMPLEX64::Int32
    COMPLEX128::Int32
    BFLOAT16::Int32
    __enum_TensorProto_DataType() = new(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16)
end #struct __enum_TensorProto_DataType
const TensorProto_DataType = __enum_TensorProto_DataType()

struct __enum_TensorProto_DataLocation <: ProtoEnum
    DEFAULT::Int32
    EXTERNAL::Int32
    __enum_TensorProto_DataLocation() = new(0,1)
end #struct __enum_TensorProto_DataLocation
const TensorProto_DataLocation = __enum_TensorProto_DataLocation()

mutable struct TensorProto_Segment <: ProtoType
    _begin::Int64
    _end::Int64
    TensorProto_Segment(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct TensorProto_Segment

mutable struct TensorProto <: ProtoType
    dims::Base.Vector{Int64}
    data_type::Int32
    segment::TensorProto_Segment
    float_data::Base.Vector{Float32}
    int32_data::Base.Vector{Int32}
    string_data::Base.Vector{Array{UInt8,1}}
    int64_data::Base.Vector{Int64}
    name::AbstractString
    doc_string::AbstractString
    raw_data::Array{UInt8,1}
    external_data::Base.Vector{StringStringEntryProto}
    data_location::Int32
    double_data::Base.Vector{Float64}
    uint64_data::Base.Vector{UInt64}
    TensorProto(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct TensorProto
const __fnum_TensorProto = Int[1,2,3,4,5,6,7,8,12,9,13,14,10,11]
const __pack_TensorProto = Symbol[:float_data,:int32_data,:int64_data,:double_data,:uint64_data]
meta(t::Type{TensorProto}) = meta(t, ProtoBuf.DEF_REQ, __fnum_TensorProto, ProtoBuf.DEF_VAL, true, __pack_TensorProto, ProtoBuf.DEF_WTYPES, ProtoBuf.DEF_ONEOFS, ProtoBuf.DEF_ONEOF_NAMES, ProtoBuf.DEF_FIELD_TYPES)

mutable struct SparseTensorProto <: ProtoType
    values::TensorProto
    indices::TensorProto
    dims::Base.Vector{Int64}
    SparseTensorProto(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct SparseTensorProto

mutable struct TensorShapeProto_Dimension <: ProtoType
    dim_value::Int64
    dim_param::AbstractString
    denotation::AbstractString
    TensorShapeProto_Dimension(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct TensorShapeProto_Dimension
const __oneofs_TensorShapeProto_Dimension = Int[1,1,0]
const __oneof_names_TensorShapeProto_Dimension = [Symbol("value")]
meta(t::Type{TensorShapeProto_Dimension}) = meta(t, ProtoBuf.DEF_REQ, ProtoBuf.DEF_FNUM, ProtoBuf.DEF_VAL, true, ProtoBuf.DEF_PACK, ProtoBuf.DEF_WTYPES, __oneofs_TensorShapeProto_Dimension, __oneof_names_TensorShapeProto_Dimension, ProtoBuf.DEF_FIELD_TYPES)

mutable struct TensorShapeProto <: ProtoType
    dim::Base.Vector{TensorShapeProto_Dimension}
    TensorShapeProto(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct TensorShapeProto

mutable struct OperatorSetIdProto <: ProtoType
    domain::AbstractString
    version::Int64
    OperatorSetIdProto(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct OperatorSetIdProto

struct __enum_AttributeProto_AttributeType <: ProtoEnum
    UNDEFINED::Int32
    FLOAT::Int32
    INT::Int32
    STRING::Int32
    TENSOR::Int32
    GRAPH::Int32
    SPARSE_TENSOR::Int32
    FLOATS::Int32
    INTS::Int32
    STRINGS::Int32
    TENSORS::Int32
    GRAPHS::Int32
    SPARSE_TENSORS::Int32
    __enum_AttributeProto_AttributeType() = new(0,1,2,3,4,5,11,6,7,8,9,10,12)
end #struct __enum_AttributeProto_AttributeType
const AttributeProto_AttributeType = __enum_AttributeProto_AttributeType()

mutable struct AttributeProto <: ProtoType
    name::AbstractString
    ref_attr_name::AbstractString
    doc_string::AbstractString
    _type::Int32
    f::Float32
    i::Int64
    s::Array{UInt8,1}
    t::TensorProto
    g::Base.Any
    sparse_tensor::SparseTensorProto
    floats::Base.Vector{Float32}
    ints::Base.Vector{Int64}
    strings::Base.Vector{Array{UInt8,1}}
    tensors::Base.Vector{TensorProto}
    graphs::Base.Any
    sparse_tensors::Base.Vector{SparseTensorProto}
    AttributeProto(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct AttributeProto (has cyclic type dependency)
const __fnum_AttributeProto = Int[1,21,13,20,2,3,4,5,6,22,7,8,9,10,11,23]
const __ftype_AttributeProto = Dict(:g => "GraphProto", :graphs => "Base.Vector{GraphProto}")
meta(t::Type{AttributeProto}) = meta(t, ProtoBuf.DEF_REQ, __fnum_AttributeProto, ProtoBuf.DEF_VAL, true, ProtoBuf.DEF_PACK, ProtoBuf.DEF_WTYPES, ProtoBuf.DEF_ONEOFS, ProtoBuf.DEF_ONEOF_NAMES, __ftype_AttributeProto)

mutable struct ValueInfoProto <: ProtoType
    name::AbstractString
    _type::Base.Any
    doc_string::AbstractString
    ValueInfoProto(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct ValueInfoProto (has cyclic type dependency)
const __ftype_ValueInfoProto = Dict(:_type => "TypeProto")
meta(t::Type{ValueInfoProto}) = meta(t, ProtoBuf.DEF_REQ, ProtoBuf.DEF_FNUM, ProtoBuf.DEF_VAL, true, ProtoBuf.DEF_PACK, ProtoBuf.DEF_WTYPES, ProtoBuf.DEF_ONEOFS, ProtoBuf.DEF_ONEOF_NAMES, __ftype_ValueInfoProto)

mutable struct NodeProto <: ProtoType
    input::Base.Vector{AbstractString}
    output::Base.Vector{AbstractString}
    name::AbstractString
    op_type::AbstractString
    domain::AbstractString
    attribute::Base.Vector{AttributeProto}
    doc_string::AbstractString
    NodeProto(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct NodeProto (has cyclic type dependency)
const __fnum_NodeProto = Int[1,2,3,4,7,5,6]
meta(t::Type{NodeProto}) = meta(t, ProtoBuf.DEF_REQ, __fnum_NodeProto, ProtoBuf.DEF_VAL, true, ProtoBuf.DEF_PACK, ProtoBuf.DEF_WTYPES, ProtoBuf.DEF_ONEOFS, ProtoBuf.DEF_ONEOF_NAMES, ProtoBuf.DEF_FIELD_TYPES)

mutable struct TrainingInfoProto <: ProtoType
    initialization::Base.Any
    algorithm::Base.Any
    initialization_binding::Base.Vector{StringStringEntryProto}
    update_binding::Base.Vector{StringStringEntryProto}
    TrainingInfoProto(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct TrainingInfoProto (has cyclic type dependency)
const __ftype_TrainingInfoProto = Dict(:initialization => "GraphProto", :algorithm => "GraphProto")
meta(t::Type{TrainingInfoProto}) = meta(t, ProtoBuf.DEF_REQ, ProtoBuf.DEF_FNUM, ProtoBuf.DEF_VAL, true, ProtoBuf.DEF_PACK, ProtoBuf.DEF_WTYPES, ProtoBuf.DEF_ONEOFS, ProtoBuf.DEF_ONEOF_NAMES, __ftype_TrainingInfoProto)

mutable struct ModelProto <: ProtoType
    ir_version::Int64
    opset_import::Base.Vector{OperatorSetIdProto}
    producer_name::AbstractString
    producer_version::AbstractString
    domain::AbstractString
    model_version::Int64
    doc_string::AbstractString
    graph::Base.Any
    metadata_props::Base.Vector{StringStringEntryProto}
    training_info::Base.Vector{TrainingInfoProto}
    ModelProto(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct ModelProto (has cyclic type dependency)
const __fnum_ModelProto = Int[1,8,2,3,4,5,6,7,14,20]
const __ftype_ModelProto = Dict(:graph => "GraphProto")
meta(t::Type{ModelProto}) = meta(t, ProtoBuf.DEF_REQ, __fnum_ModelProto, ProtoBuf.DEF_VAL, true, ProtoBuf.DEF_PACK, ProtoBuf.DEF_WTYPES, ProtoBuf.DEF_ONEOFS, ProtoBuf.DEF_ONEOF_NAMES, __ftype_ModelProto)

mutable struct GraphProto <: ProtoType
    node::Base.Vector{NodeProto}
    name::AbstractString
    initializer::Base.Vector{TensorProto}
    sparse_initializer::Base.Vector{SparseTensorProto}
    doc_string::AbstractString
    input::Base.Vector{ValueInfoProto}
    output::Base.Vector{ValueInfoProto}
    value_info::Base.Vector{ValueInfoProto}
    quantization_annotation::Base.Vector{TensorAnnotation}
    GraphProto(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct GraphProto (has cyclic type dependency)
const __fnum_GraphProto = Int[1,2,5,15,10,11,12,13,14]
meta(t::Type{GraphProto}) = meta(t, ProtoBuf.DEF_REQ, __fnum_GraphProto, ProtoBuf.DEF_VAL, true, ProtoBuf.DEF_PACK, ProtoBuf.DEF_WTYPES, ProtoBuf.DEF_ONEOFS, ProtoBuf.DEF_ONEOF_NAMES, ProtoBuf.DEF_FIELD_TYPES)

mutable struct TypeProto_Sequence <: ProtoType
    elem_type::Base.Any
    TypeProto_Sequence(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct TypeProto_Sequence (has cyclic type dependency)
const __ftype_TypeProto_Sequence = Dict(:elem_type => "TypeProto")
meta(t::Type{TypeProto_Sequence}) = meta(t, ProtoBuf.DEF_REQ, ProtoBuf.DEF_FNUM, ProtoBuf.DEF_VAL, true, ProtoBuf.DEF_PACK, ProtoBuf.DEF_WTYPES, ProtoBuf.DEF_ONEOFS, ProtoBuf.DEF_ONEOF_NAMES, __ftype_TypeProto_Sequence)

mutable struct TypeProto_Map <: ProtoType
    key_type::Int32
    value_type::Base.Any
    TypeProto_Map(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct TypeProto_Map (has cyclic type dependency)
const __ftype_TypeProto_Map = Dict(:value_type => "TypeProto")
meta(t::Type{TypeProto_Map}) = meta(t, ProtoBuf.DEF_REQ, ProtoBuf.DEF_FNUM, ProtoBuf.DEF_VAL, true, ProtoBuf.DEF_PACK, ProtoBuf.DEF_WTYPES, ProtoBuf.DEF_ONEOFS, ProtoBuf.DEF_ONEOF_NAMES, __ftype_TypeProto_Map)

mutable struct TypeProto_Tensor <: ProtoType
    elem_type::Int32
    shape::TensorShapeProto
    TypeProto_Tensor(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct TypeProto_Tensor

mutable struct TypeProto <: ProtoType
    tensor_type::TypeProto_Tensor
    sequence_type::TypeProto_Sequence
    map_type::TypeProto_Map
    denotation::AbstractString
    TypeProto(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct TypeProto (has cyclic type dependency)
const __fnum_TypeProto = Int[1,4,5,6]
const __oneofs_TypeProto = Int[1,1,1,0]
const __oneof_names_TypeProto = [Symbol("value")]
meta(t::Type{TypeProto}) = meta(t, ProtoBuf.DEF_REQ, __fnum_TypeProto, ProtoBuf.DEF_VAL, true, ProtoBuf.DEF_PACK, ProtoBuf.DEF_WTYPES, __oneofs_TypeProto, __oneof_names_TypeProto, ProtoBuf.DEF_FIELD_TYPES)

export Version, AttributeProto_AttributeType, AttributeProto, ValueInfoProto, NodeProto, TrainingInfoProto, ModelProto, StringStringEntryProto, TensorAnnotation, GraphProto, TensorProto_DataType, TensorProto_DataLocation, TensorProto_Segment, TensorProto, SparseTensorProto, TensorShapeProto_Dimension, TensorShapeProto, TypeProto_Tensor, TypeProto_Sequence, TypeProto_Map, TypeProto, OperatorSetIdProto, AttributeProto_AttributeType, AttributeProto, ValueInfoProto, NodeProto, TrainingInfoProto, ModelProto, GraphProto, TypeProto_Sequence, TypeProto_Map, TypeProto


text:
export StandardEnergy

mutable struct StandardEnergy <: EnergyComponent{Vector{Float}}
    specific_energies::Vector{Float}

    """
        StandardEnergy(
            positions::AbstractVector{SVectorF{N}},
            mass_densities::AbstractVector{Float},
            energy_distribution::InitialEnergyDistribution{N},
            eos::EquationOfState,
        )
    """
    function StandardEnergy(
        positions::AbstractVector{SVectorF{N}},
        mass_densities::AbstractVector{Float},
        energy_distribution::InitialEnergyDistribution{N},
        eos::EquationOfState,
    ) where {N}
        specific_energies = energy_distribution(positions, mass_densities, eos)
        new(specific_energies)
    end
end

get_specific_energies(standard_energy::StandardEnergy) =
    standard_energy.specific_energies

initderivatives(standard_energy::StandardEnergy) =
    zeros(length(standard_energy.specific_energies))

initderivatives!(dudt::AbstractVector{Float}, ::StandardEnergy) =
    fill!(dudt, 0.0)

function updatederivatives!(
    dudt::AbstractVector{Float},
    (i, j)::Tuple{Unsigned,Unsigned},
    vᵣ::Number,
    (Δaᵢ_pressure, Δaⱼ_pressure, Δa_diffusion)::Tuple{Number,Number,Number},
    ::StandardEnergy,
)
    Δdudtᵢ = compute_Δdudt(Δaᵢ_pressure, Δa_diffusion, vᵣ)
    Δdudtⱼ = compute_Δdudt(Δaⱼ_pressure, Δa_diffusion, vᵣ)
    dudt[i] += Δdudtᵢ
    dudt[j] += Δdudtⱼ
end

function updatederivative!(
    dudt::AbstractVector{Float},
    i::Unsigned,
    vᵣ::Number,
    (Δaᵢ_pressure, Δaⱼ_pressure, Δa_diffusion)::Tuple{Number,Number,Number},
    ::StandardEnergy,
)
    dudt[i] += compute_Δdudt(Δaᵢ_pressure, Δa_diffusion, vᵣ)
end

compute_Δdudt(Δa_pressure::Number, Δa_diffusion::Number, vᵣ::Number) =
    (Δa_pressure + Δa_diffusion) * vᵣ

evolvevariables!(
    standard_energy::StandardEnergy,
    dudt::AbstractVector{Float},
    Δt::Number,
) = standard_energy.specific_energies .+= Δt * dudt

max_stars_repo_name: lars-frogner/Whirl

max_issues_repo_name: lars-frogner/Whirl

max_forks_repo_name: lars-frogner/Whirl


text:
using FactCheck
using MathProgBase
importall NEOS

# Null out this method for testing
NEOS.getobjbound(m::NEOS.NEOSMathProgModel) = 0

#
# As part of the NEOS terms of use, some solvers
# 	require a valid email to be supplied.
#
# TESTING_EMAIL = readchomp(`git config --get user.email`)
TESTING_EMAIL = "odow@users.noreply.github.com"

facts("Test NEOS Server") do
	s = NEOSServer()
	addemail!(s, TESTING_EMAIL)
	@fact s.email --> TESTING_EMAIL
	addemail!(s, "")
	s = NEOSServer(email=TESTING_EMAIL)
	@fact s.email --> TESTING_EMAIL
	v = version(s)
	@fact match(r"neos version ([0-9]+) \(.+\)", v) == nothing --> false

	@fact contains(neosHelp(s), "class NeosServer") --> true

	_solvers = listAllSolvers(s)
	@fact "milp:CPLEX:MPS" in _solvers --> true
	@fact "milp:MOSEK:MPS" in _solvers --> true
	@fact "lp:MOSEK:MPS" in _solvers --> true
	@fact "milp:SYMPHONY:MPS" in _solvers --> true
	@fact "milp:XpressMP:MPS" in _solvers --> true

	@fact "Mixed Integer Linear Programming" in listCategories(s) --> true

	_solvers = listSolversInCategory(s, :MILP)
	@fact "CPLEX:MPS" in _solvers --> true
	@fact "MOSEK:MPS" in _solvers --> true
	@fact "SYMPHONY:MPS" in _solvers --> true
	@fact "XpressMP:MPS" in _solvers --> true

	j = NEOS.NEOSJob(3804943, "OfRcoMbp")
	_info = getJobInfo(s, j)
	@fact _info[1] --> "milp"
	@fact _info[2] --> "XpressMP"
	@fact _info[3] --> "MPS"
	@fact _info[4] --> "Done"

	@fact getJobStatus(s, j) --> "Done"
	@fact killJob(s, j) --> "Job #3804943 is finished"

	@fact getIntermediateResults(s, j) == getIntermediateResultsNonBlocking(s, j) == "Results for Job #3804943 are no longer available" --> true
end

facts("Test NEOSMathProgModel") do
	m = MathProgBase.LinearQuadraticModel(NEOSSYMPHONYSolver())
	@fact MathProgBase.getsolution(m) --> []
	@fact MathProgBase.getobjval(m) --> 0.
	@fact MathProgBase.getsense(m) --> :Min
	MathProgBase.setsense!(m, :Max)
	@fact MathProgBase.getsense(m) --> :Max
	@fact MathProgBase.status(m) --> NEOS.NOTSOLVED
	MathProgBase.loadproblem!(m, [1. 2. 3.; 1. 1. 1.], [-1., 0., 0.], [1., 1., Inf], [0., 0., 1.], [1.25, 1.], [1.25, 1.], :Max)
	MathProgBase.setvartype!(m, [:SemiCont, :Cont, :Bin])
	@fact_throws NEOS.addCOLS(m, "")
	MathProgBase.setvartype!(m, [:SemiInt, :Cont, :Bin])
	@fact_throws NEOS.addCOLS(m, "")
end

SOLVERS = [(NEOSCPLEXSolver, :timelimit), (NEOSMOSEKSolver, :MSK_DPAR_OPTIMIZER_MAX_TIME), (NEOSSYMPHONYSolver, :time_limit), (NEOSXpressMPSolver, :MAXTIME)]

for (s, timelimit) in SOLVERS
	solver = s()

	facts("Test basic solver stuff for $(typeof(solver))") do
		@fact isa(solver, NEOS.NEOSSolver) --> true

		fields = fieldnames(solver)
		for sym in [:server, :requires_email, :solves_sos, :provides_duals,
			:template, :params, :gzipmodel, :print_results, :result_file]
			@fact sym in fields --> true
		end

		@fact method_exists(NEOS.parse_status!, (typeof(solver), NEOS.NEOSMathProgModel)) --> true
		@fact method_exists(NEOS.parse_objective!, (typeof(solver), NEOS.NEOSMathProgModel)) --> true
		@fact method_exists(NEOS.parse_solution!, (typeof(solver), NEOS.NEOSMathProgModel)) --> true

		m = MathProgBase.LinearQuadraticModel(solver)

		m.nrow, m.ncol = 1, 2
		if solver.provides_duals
			@fact method_exists(NEOS.parse_duals!, (typeof(solver), NEOS.NEOSMathProgModel)) --> true
			@fact MathProgBase.getreducedcosts(m) --> []
			@fact MathProgBase.getconstrduals(m) --> []
		else
			@fact isnan(MathProgBase.getreducedcosts(m)) --> [true, true;]
			@fact isnan(MathProgBase.getconstrduals(m)) --> [true;]
		end

		if !solver.solves_sos
			@fact_throws MathProgBase.addsos1!(m, [], [])
			@fact_throws MathProgBase.addsos2!(m, [], [])
		end

		addemail!(m, "Test")
		@fact m.solver.server.email --> "Test"
		addemail!(solver, TESTING_EMAIL)
		@fact solver.server.email --> TESTING_EMAIL

		addparameter!(solver, "key", 0)
		@fact solver.params["key"] --> 0
		solver.params = Dict{ASCIIString, Any}()

		_solver = @eval $(s)($(timelimit)=60, email=TESTING_EMAIL)
		@fact _solver.params[string(timelimit)] --> 60
		@fact _solver.server.email --> TESTING_EMAIL

		if solver.requires_email
			addemail!(solver, "")
			@fact_throws linprog([-1.,0.;],sparse([2. -1.;]),'<',1.5, [-1, -Inf], [1, 0.], solver)
			addemail!(solver, TESTING_EMAIL)
		end
	end

    facts("Testing feasible problem $(typeof(solver))") do
	    sol = linprog([-1.,0.;],sparse([2. -1.;]),'<',1.5, [-1, -Inf], [1, 0.], solver)
	    @fact sol.status --> :Optimal
	    @fact sol.objval --> roughly(-0.75, 1e-5)
	    @fact sol.sol --> roughly([0.75, 0.;], 1e-5)
		if solver.provides_duals
	    	@fact sol.attrs[:lambda] --> roughly([-0.5;], 1e-5)
	    	@fact sol.attrs[:redcost] --> roughly([0., -0.5;], 1e-5)
		else
			@fact isnan(sol.attrs[:lambda]) --> [true]
	    	@fact isnan(sol.attrs[:redcost]) --> [true, true;]
		end

		addparameter!(solver, string(timelimit), 60)
        sol = mixintprog(-[5.,3.,2.,7.,4.;],Float64[2. 8. 4. 2. 5.;],'<',10.,:Int,-0.5,1.,solver)
		@fact sol.status --> :Optimal
 		@fact sol.objval --> roughly(-16.0, 1e-6)
		@fact sol.sol --> roughly([1.0, 0.0, 0.0, 1.0, 1.0;], 1e-4)
	end

	facts("Testing infeasible problem $(typeof(solver))") do
		solver.gzipmodel=false
	    sol = linprog([1.,0.;],[-2. -1.;],'>',1., solver)
		@fact (sol.status == NEOS.INFEASIBLE || sol.status == NEOS.UNBNDORINF) --> true
	end

	facts("Testing unbounded problem $(typeof(solver))") do
	    solver.result_file = randstring(5)
		sol = linprog([-1.,-1.;],[-1. 2.;],'<',[0.;], solver)
	    @fact (sol.status == NEOS.UNBOUNDED || sol.status == NEOS.UNBNDORINF) --> true
		@fact length(readall(solver.result_file)) > 0 --> true
		rm(solver.result_file)
		solver.result_file = ""
    end

	facts("Testing null problem $(typeof(solver))") do
		solver.result_file = randstring(5)
		m = MathProgBase.LinearQuadraticModel(solver)
		MathProgBase.loadproblem!(m, Array(Int, (0,0)), [0.], [Inf], [1.], [], [], :Min)
		MathProgBase.optimize!(m)
		rm(solver.result_file)
		solver.result_file = ""
	end

	!solver.solves_sos && continue
	facts("Testing SOS problem $(typeof(solver))") do
		m = MathProgBase.LinearQuadraticModel(solver)
		MathProgBase.loadproblem!(m, [1. 2. 3.; 1. 1. 1.], [-1., 0., 0.], [1., 1., Inf], [0., 0., 1.], [1.25, 1.], [1.25, 1.], :Max)
		MathProgBase.addsos2!(m, [1, 2, 3], [1., 2., 3.])
		@fact MathProgBase.optimize!(m) --> NEOS.OPTIMAL
		@fact MathProgBase.getobjval(m) --> roughly(0., 1e-6)
		@fact MathProgBase.getsolution(m) --> roughly([0.75, 0.25, 0.], 1e-6)

		m = MathProgBase.LinearQuadraticModel(solver)
		MathProgBase.loadproblem!(m, [1. 1. 1.], [0., 0., 0.], [1., 1., 1.], [1., 3., 2.], [0.], [1.5], :Max)
		MathProgBase.addsos1!(m, [1, 2, 3], [1., 2., 3.])
		@fact MathProgBase.optimize!(m) --> NEOS.OPTIMAL
		@fact MathProgBase.getobjval(m) --> roughly(3., 1e-6)
		@fact MathProgBase.getsolution(m) --> roughly([0., 1., 0.], 1e-6)
	end
end

FactCheck.exitstatus()


text:
module Icon

using Genie, Stipple, StippleUI, StippleUI.API
import Genie.Renderer.Html: HTMLString, normal_element

export icon

Genie.Renderer.Html.register_normal_element("q__icon", context = @__MODULE__)

function icon(name::Union{String,Symbol},
              args...;
              wrap::Function = StippleUI.DEFAULT_WRAPPER,
              kwargs...)

  wrap() do
    q__icon(args...; attributes([:name => name, kwargs...])...)
  end
end

end


text:
using HTTP, Joseki, JSON, Sockets, Test

@testset "Integration tests" begin

    # Simple server
    function pow(req::HTTP.Request)
        j = HTTP.queryparams(HTTP.URI(req.target))
        if !(haskey(j, "x")&haskey(j, "y"))
            return error_responder(req, "You need to specify values for x and y!")
        end
        x = parse(Float32, j["x"])
        y = parse(Float32, j["y"])
        json_responder(req, x^y)
    end

    function test_error_responder(req::HTTP.Request, e::Exception)
        error_responder(req, "Unhandled error!")
    end

    endpoints = [
        (pow, "GET", "/pow")
    ]
    # Default middleware but a custom error responder
    router = Joseki.router(endpoints; error_fn=test_error_responder)

    @info "Starting test server"
    server = Sockets.listen(Sockets.InetAddr(ip"127.0.0.1", 8000))
    server_task = @async HTTP.serve(router, ip"127.0.0.1", 8000; verbose=false,
                                    server = server)
    sleep(1.0)

    # A valid request
    res = HTTP.get("http://localhost:8000/pow/?x=2&y=3")
    @test res.status == 200
    @test HTTP.hasheader(res, "Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,PATCH,OPTIONS")

    # An invalid request
    res = HTTP.get("http://localhost:8000/pow/?x=2&y=nothing")
    @test res.status == 200 # Our handeled errors return 200 responses
    @test occursin("Unhandled error!", String(copy(res.body)))

    @info "Shutting down test server"

    close(server)
    sleep(2)
    @test istaskdone(server_task)
end


text:
module MathFuns

export Eb, deltafun, deltadxfun, dabs

"""
    Eb(x,m)

compute ``\\sqrt{(x^2+m)}``
"""
function Eb(x, m2)
    sqrt(x^2 + m2)
end

"""
    deltafun(x,dϵ=0.02)
compute ``\\delta`` function with the approximation ``\\frac{\\epsilon}{\\pi(\\epsilon^2+x^2)}``
and ``\\epsilon`` is set to be ``0.02`` by default
"""
deltafun(x, dϵ = 1.0) = dϵ / (pi * (dϵ^2 + x^2))

function deltadxfun(x, ϵ = 1.0)
    (-2 * x * ϵ) / (pi * (x^2 + ϵ^2)^2)
end

function dabs(x)
    if x > 0.0
        return 1.0
    elseif x < 0.0
        return -1.0
    elseif x == 0.0
        return 0.0
    end
end

end


text:
using Pkg

for x in readdir()
    if isdir(x) && isfile(joinpath(x, "Project.toml"))
        Pkg.activate(x)
        Pkg.update()
    end
end