text:
function gausschebyshev(n::Int, kind::Int=1)
    # GAUSS-CHEBYSHEV NODES AND WEIGHTS.

    # Use known explicit formulas. Complexity O(n).
    if kind == 1
        # Gauss-ChebyshevT quadrature, i.e., w(x) = 1/sqrt(1-x^2)
        [cos((2 * k - 1) * π / (2 * n)) for k = n:-1:1], fill(π / n, n)
    elseif kind == 2
        # Gauss-ChebyshevU quadrature, i.e., w(x) = sqrt(1-x^2)
        ([cos(k * π / (n + 1)) for k = n:-1:1],
         [π/(n + 1) * sin(k / (n + 1) * π)^2 for k = n:-1:1])
    elseif kind == 3
        # Gauss-ChebyshevV quadrature, i.e., w(x) = sqrt((1+x)/(1-x))
        ([cos((k - .5) * π / (n + .5)) for k = n:-1:1],
         [2π / (n + .5) * cos((k - .5) * π / (2 * (n + .5)))^2 for k = n:-1:1])
    elseif kind == 4
        # Gauss-ChebyshevW quadrature, i.e., w(x) = sqrt((1-x)/(1+x))
        ([cos(k * π / (n + .5)) for k = n:-1:1],
         [2π / (n + .5) * sin(k * π / (2 * (n + .5)))^2 for k = n:-1:1])
    else
        throw(ArgumentError("Chebyshev kind should be 1, 2, 3, or 4"))
    end
end


text:
@inline bson_representation_type(::Type{T}) where T = T
@inline bson_representation_type(::Type{Symbol}) = String
@inline bson_representation_type(::Type{<:Enum}) = String

@inline bson_representation_convert(::Type{T}, x) where T = StructTypes.construct(T, x)
@inline bson_representation_convert(::Type{String}, x) = string(x)

@inline bson_representation_type(::Type{Vector{UInt8}}) = BSONBinary
@inline bson_representation_convert(::Type{Vector{UInt8}}, x::BSONBinary) = x.data
@inline bson_representation_convert(::Type{BSONBinary}, x::Vector{UInt8}) = BSONBinary(x)

@inline bson_representation_type(::Type{<:IPAddr}) = String
@inline bson_representation_type(::Type{<:Sockets.InetAddr}) = String

bson_representation_convert(::Type{String}, x::Sockets.InetAddr{IPv4}) = "$(x.host):$(x.port)"

function bson_representation_convert(::Type{Sockets.InetAddr{IPv4}}, x::String)
    m = match(r"^(.*):(\d+)$", x)
    m === nothing && throw(ArgumentError("Invalid IPv4 inet address: $x"))
    Sockets.InetAddr(IPv4(m.captures[1]), parse(Int, m.captures[2]))
end

bson_representation_convert(::Type{String}, x::Sockets.InetAddr{IPv6}) = "[$(x.host)]:$(x.port)"

function bson_representation_convert(::Type{Sockets.InetAddr{IPv6}}, x::String)
    m = match(r"^\[(.*)\]:(\d+)$", x)
    m === nothing && throw(ArgumentError("Invalid IPv6 inet address: $x"))
    Sockets.InetAddr(IPv6(m.captures[1]), parse(Int, m.captures[2]))
end

ext: jl


text:
# A one-dimensional light-dark problem, originally used to test MCVI
# A very simple POMDP with continuous state and observation spaces.
# maintained by @zsunberg

import Base: ==, +, *, -

"""
    LightDark1DState

## Fields
- `y`: position
- `status`: 0 = normal, negative = terminal
"""
struct LightDark1DState
    status::Int64
    y::Float64
end

*(n::Number, s::LightDark1DState) = LightDark1DState(s.status, n*s.y)

"""
    LightDark1D

A one-dimensional light dark problem. The goal is to be near 0. Observations are noisy measurements of the position.

Model
-----

   -3-2-1 0 1 2 3
...| | | | | | | | ...
          G   S

Here G is the goal. S is the starting location
"""
mutable struct LightDark1D{F<:Function} <: POMDPs.POMDP{LightDark1DState,Int,Float64}
    discount_factor::Float64
    correct_r::Float64
    incorrect_r::Float64
    step_size::Float64
    movement_cost::Float64
    sigma::F
end

default_sigma(x::Float64) = abs(x - 5)/sqrt(2) + 1e-2

LightDark1D() = LightDark1D(0.9, 10.0, -10.0, 1.0, 0.0, default_sigma)

discount(p::LightDark1D) = p.discount_factor

isterminal(::LightDark1D, act::Int64) = act == 0

isterminal(::LightDark1D, s::LightDark1DState) = s.status < 0

actions(::LightDark1D) = -1:1

struct LDNormalStateDist
    mean::Float64
    std::Float64
end

sampletype(::Type{LDNormalStateDist}) = LightDark1DState
rand(rng::AbstractRNG, d::LDNormalStateDist) = LightDark1DState(0, d.mean + randn(rng)*d.std)
initialstate(pomdp::LightDark1D) = LDNormalStateDist(2, 3)
initialobs(m::LightDark1D, s) = observation(m, s)

observation(p::LightDark1D, sp::LightDark1DState) = Normal(sp.y, p.sigma(sp.y))

function transition(p::LightDark1D, s::LightDark1DState, a::Int)
    if a == 0
        return Deterministic(LightDark1DState(-1, s.y+a*p.step_size))
    else
        return Deterministic(LightDark1DState(s.status, s.y+a*p.step_size))
    end
end

function reward(p::LightDark1D, s::LightDark1DState, a::Int)
    if s.status < 0
        return 0.0
    elseif a == 0
        if abs(s.y) < 1
            return p.correct_r
        else
            return p.incorrect_r
        end
    else
        return -p.movement_cost*a
    end
end

convert_s(::Type{A}, s::LightDark1DState, p::LightDark1D) where A<:AbstractArray = eltype(A)[s.status, s.y]
convert_s(::Type{LightDark1DState}, s::A, p::LightDark1D) where A<:AbstractArray = LightDark1DState(Int64(s[1]), s[2])

# Define some simple policies based on particle belief
mutable struct DummyHeuristic1DPolicy <: POMDPs.Policy
    thres::Float64
end
DummyHeuristic1DPolicy() = DummyHeuristic1DPolicy(0.1)

mutable struct SmartHeuristic1DPolicy <: POMDPs.Policy
    thres::Float64
end
SmartHeuristic1DPolicy() = SmartHeuristic1DPolicy(0.1)

function action(p::DummyHeuristic1DPolicy, b::B) where {B}
    target = 0.0
    μ = mean(b)
    σ = std(b, μ)

    if σ.y < p.thres && -0.5 < μ.y < 0.5
        a = 0
    elseif μ.y < target
        a = 1                   # Right
    elseif μ.y > target
        a = -1                  # Left
    end
    return a
end

function action(p::SmartHeuristic1DPolicy, b::B) where {B}
    μ = mean(b)
    σ = std(b, μ)
    target = 0.0
    if σ.y > p.thres
        target = 5.0
    end
    if σ.y < p.thres && -0.5 < μ.y < 0.5
        a = 0
    elseif μ.y < target
        a = 1                   # Right
    elseif μ.y > target
        a = -1                  # Left
    end
    return a
end

# deprecated in POMDPs v0.9
POMDPs.initialstate_distribution(pomdp::LightDark1D) = LDNormalStateDist(2, 3)


text:
importall Bukdu

type ViewController <: ApplicationController
end

layout(::Layout, body) = "$body"

show(::ViewController) = render(View; path="renderers/page.tpl", contents="hello")
index(::ViewController) = render(View/Layout; path="renderers/page.tpl", contents="hello")
mark(::ViewController) = render(Markdown/Layout, "# hello")

Router() do
    get("/hey", ViewController, show)
    get("/", ViewController, index)
    get("/mark", ViewController, mark)
end

Endpoint() do
    plug(Router)
end

plugins(render, View/Layout) do
    plug(Logger.log_message, View/Layout)
end

plugins(render, View) do
    plug(Logger.log_message, View)
end

plugins(render, Markdown/Layout) do md
    plug(Logger.log_message, Markdown/Layout)
end

plugins(render, Markdown) do md
    plug(Logger.log_message, Markdown)
end

using Base.Test
conn = (Router)(get, "/hey")
@test 200 == conn.status
@test "
hello
" == conn.resp_body

conn = (Router)(get, "/")
@test 200 == conn.status
@test "
hello
" == conn.resp_body

conn = (Router)(get, "/mark")
@test 200 == conn.status
@test "
hello
" == conn.resp_body

logs = []

before(render, View/Layout) do
    push!(logs, :bvl)
end

before(render, View) do
    push!(logs, :bv)
end

after(render, View/Layout) do
    push!(logs, :avl)
end

after(render, View) do
    push!(logs, :av)
end

conn = (Router)(get, "/")
@test [:bvl,:bv,:av,:avl] == logs

conn = (Router)(get, "/")
@test [:bvl,:bv,:av,:avl, :bvl,:bv,:av,:avl] == logs

@test "
hello
" == render(View; path="renderers/page.tpl", contents="hello").resp_body
@test "
hello
" == render(View/Layout; path="renderers/page.tpl", contents="hello").resp_body

Logger.have_color(false)

before(render, Markdown/Layout) do md
    Logger.info("mark layout")
end

before(render, Markdown) do md
    Logger.info("mark")
end

let oldout = STDERR
   rdout, wrout = redirect_stdout()

   conn = (Router)(get, "/mark")

   reader = @async readstring(rdout)
   redirect_stdout(oldout)
   close(wrout)

   @test "INFO Markdown/Layout mark layout\nINFO Markdown mark\n" == wait(reader)
end

before(render, View/Layout) do
    Logger.info("view layout")
end

before(render, View) do
    Logger.info("view")
end

let oldout = STDERR
    rdout, wrout = redirect_stdout()

    conn = (Router)(get, "/")

    reader = @async readstring(rdout)
    redirect_stdout(oldout)
    close(wrout)

    @test "INFO View/Layout view layout\nINFO View view\n" == wait(reader)
end


text:
"""
$(TYPEDEF)

XY Euclidean manifold variable node softtype.
"""
struct Point2 <: IncrementalInference.InferenceVariable
  dims::Int
  labels::Vector{String}
  manifolds::Tuple{Symbol,Symbol}
  Point2(;labels::Vector{<:AbstractString}=String[]) = new(2, labels, (:Euclid, :Euclid))
end


text:
"""
    ThermistorHW

Cálculo de propriedades de termistores e sua aplicação em
termo-anemometria.

"""
module ThermistorHW

# package code goes here

export Thermistor, Resistor, resistance, temperature
export myhorner, IdealGas, AirType, Air, heatcond, viscosity, density, kinviscosity, specheat
export thermaldiff, prandtl, volthermalexpansion
export reynolds, nusphere, nucylinder, grashof, rayleigh, nuspherefree, hconvect, hconvectcyl
export Solid, Fe2O3, Fe₂O₃, const_current, const_temperature, thermalcond
export HWSensor

abstract type AbstractSubstance end
abstract type AbstractFluid <: AbstractSubstance end
abstract type AbstractGas <: AbstractFluid end
abstract type AbstractIdealGas <: AbstractGas end

include("thermistor.jl")
include("air.jl")
include("solid.jl")
include("heattrans.jl")
include("anemometer.jl")

end # module


text:
### Broadcasting

Base.getindex(df::AbstractDataFrame, idx::CartesianIndex{2}) = df[idx[1], idx[2]]
Base.view(df::AbstractDataFrame, idx::CartesianIndex{2}) = view(df, idx[1], idx[2])
Base.setindex!(df::AbstractDataFrame, val, idx::CartesianIndex{2}) =
    (df[idx[1], idx[2]] = val)

Base.broadcastable(df::AbstractDataFrame) = df

struct DataFrameStyle <: Base.Broadcast.BroadcastStyle end

Base.Broadcast.BroadcastStyle(::Type{<:AbstractDataFrame}) =
    DataFrameStyle()

Base.Broadcast.BroadcastStyle(::DataFrameStyle, ::Base.Broadcast.BroadcastStyle) =
    DataFrameStyle()
Base.Broadcast.BroadcastStyle(::Base.Broadcast.BroadcastStyle, ::DataFrameStyle) =
    DataFrameStyle()
Base.Broadcast.BroadcastStyle(::DataFrameStyle, ::DataFrameStyle) = DataFrameStyle()

function copyto_widen!(res::AbstractVector{T}, bc::Base.Broadcast.Broadcasted,
                       pos, col) where T
    for i in pos:length(axes(bc)[1])
        val = bc[CartesianIndex(i, col)]
        S = typeof(val)
        if S <: T || promote_type(S, T) <: T
            res[i] = val
        else
            newres = similar(Vector{promote_type(S, T)}, length(res))
            copyto!(newres, 1, res, 1, i-1)
            newres[i] = val
            return copyto_widen!(newres, bc, i + 1, col)
        end
    end
    return res
end

function getcolbc(bcf::Base.Broadcast.Broadcasted{Style}, colind) where {Style}
    # we assume that bcf is already flattened and unaliased
    newargs = map(bcf.args) do x
        Base.Broadcast.extrude(x isa AbstractDataFrame ? x[!, colind] : x)
    end
    return Base.Broadcast.Broadcasted{Style}(bcf.f, newargs, bcf.axes)
end

function Base.copy(bc::Base.Broadcast.Broadcasted{DataFrameStyle})
    ndim = length(axes(bc))
    if ndim != 2
        throw(DimensionMismatch("cannot broadcast a data frame into $ndim dimensions"))
    end
    bcf = Base.Broadcast.flatten(bc)
    colnames = unique!(Any[_names(df) for df in bcf.args if df isa AbstractDataFrame])
    if length(colnames) != 1
        wrongnames = setdiff(union(colnames...), intersect(colnames...))
        if isempty(wrongnames)
            throw(ArgumentError("Column names in broadcasted data frames " *
                                "must have the same order"))
        else
            msg = join(wrongnames, ", ", " and ")
            throw(ArgumentError("Column names in broadcasted data frames must match. " *
                                "Non matching column names are $msg"))
        end
    end
    nrows = length(axes(bcf)[1])
    df = DataFrame()
    for i in axes(bcf)[2]
        if nrows == 0
            col = Any[]
        else
            bcf′ = getcolbc(bcf, i)
            v1 = bcf′[CartesianIndex(1, i)]
            startcol = similar(Vector{typeof(v1)}, nrows)
            startcol[1] = v1
            col = copyto_widen!(startcol, bcf′, 2, i)
        end
        df[!, colnames[1][i]] = col
    end
    return df
end

### Broadcasting assignment

struct LazyNewColDataFrame{T}
    df::DataFrame
    col::T
end

Base.axes(x::LazyNewColDataFrame) = (Base.OneTo(nrow(x.df)),)
Base.ndims(::Type{<:LazyNewColDataFrame}) = 1

struct ColReplaceDataFrame
    df::DataFrame
    cols::Vector{Int}
end

Base.axes(x::ColReplaceDataFrame) = (axes(x.df, 1), Base.OneTo(length(x.cols)))
Base.ndims(::Type{ColReplaceDataFrame}) = 2

Base.maybeview(df::AbstractDataFrame, idx::CartesianIndex{2}) = df[idx]
Base.maybeview(df::AbstractDataFrame, row::Integer, col::ColumnIndex) = df[row, col]
Base.maybeview(df::AbstractDataFrame, rows, cols) = view(df, rows, cols)

function Base.dotview(df::DataFrame, ::Colon, cols::ColumnIndex)
    haskey(index(df), cols) && return view(df, :, cols)
    if !(cols isa SymbolOrString)
        throw(ArgumentError("creating new columns using an integer index is disallowed"))
    end
    return LazyNewColDataFrame(df, Symbol(cols))
end

function Base.dotview(df::DataFrame, ::typeof(!), cols)
    if !(cols isa ColumnIndex)
        return ColReplaceDataFrame(df, index(df)[cols])
    end
    if !(cols isa SymbolOrString) && cols > ncol(df)
        throw(ArgumentError("creating new columns using an integer index is disallowed"))
    end
    return LazyNewColDataFrame(df, cols isa AbstractString ? Symbol(cols) : cols)
end

Base.dotview(df::SubDataFrame, ::typeof(!), idxs) =
    throw(ArgumentError("broadcasting with ! row selector is not allowed for SubDataFrame"))

# TODO: remove the deprecations when Julia 1.7 functionality is commonly used
#       by the community
if isdefined(Base, :dotgetproperty)
    function Base.dotgetproperty(df::DataFrame, col::SymbolOrString)
        if columnindex(df, col) == 0
            return LazyNewColDataFrame(df, Symbol(col))
        else
            Base.depwarn("In the future this operation will allocate a new column" *
                    "instead of performing an in-place assignment.", :dotgetproperty)
            return getproperty(df, col)
        end
    end

    function Base.dotgetproperty(df::SubDataFrame, col::SymbolOrString)
        Base.depwarn("broadcasting getproperty is deprecated for SubDataFrame and " *
                     "will be disallowed in  the future. Use `df[:, $(repr(col))] .= ... instead",
                     :dotgetproperty)
        return getproperty(df, col)
    end
end

function Base.copyto!(lazydf::LazyNewColDataFrame, bc::Base.Broadcast.Broadcasted{T}) where T
    if bc isa Base.Broadcast.Broadcasted{<:Base.Broadcast.AbstractArrayStyle{0}}
        bc_tmp = Base.Broadcast.Broadcasted{T}(bc.f, bc.args, ())
        v = Base.Broadcast.materialize(bc_tmp)
        col = similar(Vector{typeof(v)}, nrow(lazydf.df))
        copyto!(col, bc)
    else
        col = Base.Broadcast.materialize(bc)
    end
    lazydf.df[!, lazydf.col] = col
end

function _copyto_helper!(dfcol::AbstractVector, bc::Base.Broadcast.Broadcasted, col::Int)
    if axes(dfcol, 1) != axes(bc)[1]
        # this should never happen unless data frame is corrupted (has unequal column lengths)
        throw(DimensionMismatch("Dimension mismatch in broadcasting. The updated" *
                                " data frame is invalid and should not be used"))
    end
    @inbounds for row in eachindex(dfcol)
        dfcol[row] = bc[CartesianIndex(row, col)]
    end
end

function Base.Broadcast.broadcast_unalias(dest::AbstractDataFrame, src)
    for col in eachcol(dest)
        src = Base.Broadcast.unalias(col, src)
    end
    return src
end

function Base.Broadcast.broadcast_unalias(dest, src::AbstractDataFrame)
    wascopied = false
    for (i, col) in enumerate(eachcol(src))
        if Base.mightalias(dest, col)
            if src isa SubDataFrame
                if !wascopied
                    src = SubDataFrame(copy(parent(src), copycols=false),
                                       index(src), rows(src))
                end
                parentidx = parentcols(index(src), i)
                parent(src)[!, parentidx] = Base.unaliascopy(parent(src)[!, parentidx])
            else
                if !wascopied
                    src = copy(src, copycols=false)
                end
                src[!, i] = Base.unaliascopy(col)
            end
            wascopied = true
        end
    end
    return src
end

function _broadcast_unalias_helper(dest::AbstractDataFrame, scol::AbstractVector,
                                   src::AbstractDataFrame, col2::Int, wascopied::Bool)
    # col1 can be checked till col2 point as we are writing broadcasting
    # results from 1 to ncol
    # we go downwards because aliasing when col1 == col2 is most probable
    for col1 in col2:-1:1
        dcol = dest[!, col1]
        if Base.mightalias(dcol, scol)
            if src isa SubDataFrame
                if !wascopied
                    src =SubDataFrame(copy(parent(src), copycols=false),
                                      index(src), rows(src))
                end
                parentidx = parentcols(index(src), col2)
                parent(src)[!, parentidx] = Base.unaliascopy(parent(src)[!, parentidx])
            else
                if !wascopied
                    src = copy(src, copycols=false)
                end
                src[!, col2] = Base.unaliascopy(scol)
            end
            return src, true
        end
    end
    return src, wascopied
end

function Base.Broadcast.broadcast_unalias(dest::AbstractDataFrame, src::AbstractDataFrame)
    if size(dest, 2) != size(src, 2)
        throw(DimensionMismatch("Dimension mismatch in broadcasting."))
    end
    wascopied = false
    for col2 in axes(dest, 2)
        scol = src[!, col2]
        src, wascopied = _broadcast_unalias_helper(dest, scol, src, col2, wascopied)
    end
    return src
end

function Base.copyto!(df::AbstractDataFrame, bc::Base.Broadcast.Broadcasted)
    bcf = Base.Broadcast.flatten(bc)
    colnames = unique!(Any[_names(x) for x in bcf.args if x isa AbstractDataFrame])
    if length(colnames) > 1 || (length(colnames) == 1 && _names(df) != colnames[1])
        push!(colnames, _names(df))
        wrongnames = setdiff(union(colnames...), intersect(colnames...))
        if isempty(wrongnames)
            throw(ArgumentError("Column names in broadcasted data frames " *
                                "must have the same order"))
        else
            msg = join(wrongnames, ", ", " and ")
            throw(ArgumentError("Column names in broadcasted data frames must match. " *
                                "Non matching column names are $msg"))
        end
    end

    bcf′ = Base.Broadcast.preprocess(df, bcf)
    for i in axes(df, 2)
        _copyto_helper!(df[!, i], getcolbc(bcf′, i), i)
    end
    return df
end

function Base.copyto!(df::AbstractDataFrame,
                      bc::Base.Broadcast.Broadcasted{<:Base.Broadcast.AbstractArrayStyle{0}})
    # special case of fast approach when bc is providing an untransformed scalar
    if bc.f === identity && bc.args isa Tuple{Any} && Base.Broadcast.isflat(bc)
        for col in axes(df, 2)
            fill!(df[!, col], bc.args[1][])
        end
        return df
    else
        return copyto!(df, convert(Base.Broadcast.Broadcasted{Nothing}, bc))
    end
end

create_bc_tmp(bcf′_col::Base.Broadcast.Broadcasted{T}) where {T} =
    Base.Broadcast.Broadcasted{T}(bcf′_col.f, bcf′_col.args, ())

function Base.copyto!(crdf::ColReplaceDataFrame, bc::Base.Broadcast.Broadcasted)
    bcf = Base.Broadcast.flatten(bc)
    colnames = unique!(Any[_names(x) for x in bcf.args if x isa AbstractDataFrame])
    if length(colnames) > 1 ||
        (length(colnames) == 1 && view(_names(crdf.df), crdf.cols) != colnames[1])
        push!(colnames, view(_names(crdf.df), crdf.cols))
        wrongnames = setdiff(union(colnames...), intersect(colnames...))
        if isempty(wrongnames)
            throw(ArgumentError("Column names in broadcasted data frames " *
                                "must have the same order"))
        else
            msg = join(wrongnames, ", ", " and ")
            throw(ArgumentError("Column names in broadcasted data frames must match. " *
                                "Non matching column names are $msg"))
        end
    end

    bcf′ = Base.Broadcast.preprocess(crdf, bcf)
    nrows = length(axes(bcf′)[1])
    for (i, col_idx) in enumerate(crdf.cols)
        bcf′_col = getcolbc(bcf′, i)
        if bcf′_col isa Base.Broadcast.Broadcasted{<:Base.Broadcast.AbstractArrayStyle{0}}
            bc_tmp = create_bc_tmp(bcf′_col)
            v = Base.Broadcast.materialize(bc_tmp)
            newcol = similar(Vector{typeof(v)}, nrow(crdf.df))
            copyto!(newcol, bc)
        else
            if nrows == 0
                newcol = Any[]
            else
                v1 = bcf′_col[CartesianIndex(1, i)]
                startcol = similar(Vector{typeof(v1)}, nrows)
                startcol[1] = v1
                newcol = copyto_widen!(startcol, bcf′_col, 2, i)
            end
        end
        crdf.df[!, col_idx] = newcol
    end
    return crdf.df
end

Base.Broadcast.broadcast_unalias(dest::DataFrameRow, src) =
    Base.Broadcast.broadcast_unalias(parent(dest), src)

function Base.copyto!(dfr::DataFrameRow, bc::Base.Broadcast.Broadcasted)
    bc′ = Base.Broadcast.preprocess(dfr, bc)
    for I in eachindex(bc′)
        dfr[I] = bc′[I]
    end
    return dfr
end


text:
using PyCall

cd(joinpath(Pkg.dir("LCMCore"), "deps", "builds", "lcm")) do
    if !isfile("CMakeCache.txt")
        error("LCMCore build not found. Try running 'Pkg.build(\"LCMCore\")'")
    end

    cachelines = open("CMakeCache.txt") do f
        readlines(f)
    end
    cmake_python_executable = nothing
    for line in cachelines
        m = match(r"PYTHON_EXECUTABLE(:[A-Z]*)?=(.*)", line)
        if m !== nothing
            cmake_python_executable = normpath(strip(m.captures[end]))
            break
        end
    end
    if cmake_python_executable != normpath(PyCall.pyprogramname)
        run(`cmake "-UPYTHON*" -DPYTHON_EXECUTABLE=$(normpath(PyCall.pyprogramname)) .`)
        run(`cmake --build . --target install`)
    end
end


text:
include("../src/includes.jl")
include("../demo/qapBM.jl")

hnqap1 = HopfieldQAP(D[1], F[1])

hnqap1.s = [0 0 1;
            0 1 0;
            1 0 0]
energy(hnqap1)
hnqap1.s = [1 0 0; 0 1 0; 0 0 1]
energy(hnqap1)
energy(hnqap1)/91.4

# println(hnqap1.s[1,1])
# update!(hnqap1, (1,1))
# println(hnqap1.s[1,1])

# hnqap1.s = [1 -1 -1; -1 1 -1; -1 -1 1]
# θ = energy(hnqap1) / 3
hnqap1.s = [1 0 0; 0 1 0; 0 0 1]
hnqap1.λ = 0.5
hnqap1.ϵ = 0.05
θ = 60
for i in 1:5
    e = energy(hnqap1)
    # println("Before update cycle")
    # println(hnqap1.s)
    cycle!(hnqap1, θ)
    f = isFeasible(hnqap1)
    println("The solution is $(map(x-> x ? " " : "not ", f))feasible")
    println("After update cycle")
    println(hnqap1.s)
    println("Energy now ", e)
end
energy(hnqap1)


text:
module ModuleTriangulation
using MultipleViewGeometry.ModuleMathAliases, MultipleViewGeometry.ModuleDataNormalization
using MultipleViewGeometry.ModuleTypes, MultipleViewGeometry.ModuleProjection
using MultipleViewGeometry.ModuleConstraints, MultipleViewGeometry.ModuleConstruct
using MultipleViewGeometry.ModuleOperators
using StaticArrays, LinearAlgebra
export triangulate
include("triangulate.jl")
end


text:
# ClimateDataIO.jl
#
#   Module for loading typical data file formats found in soil and atmospheric
#	sciences
#
# Jeremy Rüffer
# Thünen Institut
# Institut für Agrarklimaschutz
# Julia 1.4.0
# 02.04.2020
# Last Edit: 09.04.2020

__precompile__(true)

"""# StofffluesseAG

Miscellaneous functions for the Stoffflüße AG

For more specific information see each functions' help.

---

`dirlist`: List the files and folders in a given folder

`findnewton`: Find a value in an ordered vector

`nanmax`: Find the maximum value in an array, ignoring NaN and missing values

`nanmin`: Find the minimum value in an array, ignoring NaN and missing values

`nanmean`: Find the mean value of an array, ignoring NaN and missing values

`nCLD_ErrorsWarnings`: Parse the error and warning values from the Eco Physics nCLD

`nCLD_Status`: Parse the status values from the Eco Physics nCLD

`timestamp_aerodyne`: Parse timestamps from Aerodyne data files

`timestamp_lgr`: Parse timestamps from Los Gatos Research (LGR) data files

`timestamp_licor` : Parse timestamps from Licor data files

`work_hours` : Calculate worked hours or time remaining

### SBF Functions
`sbf_load`: Load Stoffflüße Binary Files (.sbf)

`sbf_read`: Read an individual Stoffflüße Binary File (.sbf)

---

#### Requirements
* DataFrames
* Dates
* Statistics
* Test"""
module StofffluesseAG

using Dates
using DataFrames # sbf_load
using Statistics # nanmean

export work_hours,
		dirlist,
		findnewton,
		nanmin,
		nanmax,
		nanmean,
		nanstd,
		nCLD_ErrorsWarnings,
		nCLD_Status,
		sbf_read,
		sbf_load,
		timestamp,
		timestamp_aerodyne,
		timestamp_licor,
		timestamp_lgr

dir = splitdir(@__FILE__)[1]
include(joinpath(dir,"dirlist.jl"))
include(joinpath(dir,"work_hours.jl"))
include(joinpath(dir,"nanmean.jl"))
include(joinpath(dir,"nanstd.jl"))
include(joinpath(dir,"nanmin.jl"))
include(joinpath(dir,"nanmax.jl"))
include(joinpath(dir,"timestamp.jl"))
include(joinpath(dir,"sbf_read.jl"))
include(joinpath(dir,"sbf_load.jl"))
include(joinpath(dir,"sbf_header.jl"))
include(joinpath(dir,"nCLD.jl"))
include(joinpath(dir,"findnewton.jl"))

end # module


text:
export Splat,
    add_command!,
    delete_command!,
    add_help!,
    set_prefix!,
    @command

# A bot command handler.
struct Command <: AbstractHandler{MessageCreate}
    h::Handler{MessageCreate}
    name::Symbol
    help::String
    cooldowns::Nullable{TTL{Snowflake, Nothing}}
    fb_parsers::Function
    fb_allowed::Function
    fb_permissions::Function
    fb_cooldown::Function

    function Command(
        h::Handler{MessageCreate},
        name::Symbol,
        help::AbstractString,
        cooldown::Nullable{Period},
        fb_parsers::Function,
        fb_allowed::Function,
        fb_permissions::Function,
        fb_cooldown::Function,
    )
        cds = cooldown === nothing ? nothing : TTL{Snowflake, Nothing}(cooldown)
        return new(h, name, help, cds, fb_parsers, fb_allowed, fb_permissions, fb_cooldown)
    end
end

function Command(;
    name::Symbol,
    handler::Function,
    help::AbstractString="",
    parsers::Vector=[],
    separator::StringOrChar=' ',
    pattern::Regex=defaultpattern(name, length(parsers), separator),
    allowed::Vector{<:Integer}=Snowflake[],
    permissions::Integer=PERM_NONE,
    cooldown::Nullable{Period}=nothing,
    fallback_parsers::Function=donothing,
    fallback_allowed::Function=donothing,
    fallback_permissions::Function=donothing,
    fallback_cooldown::Function=donothing,
    priority::Int=DEFAULT_PRIORITY,
    remaining::Nullable{Int}=nothing,
    timeout::Nullable{Period}=nothing,
)
    fbs = [fallback_parsers, fallback_allowed, fallback_permissions, fallback_cooldown]
    if any(f -> !hasmethod(f, (Client, Message)), fbs)
        throw(ArgumentError("Fallback handlers must accept (::Client, Message)"))
    elseif !any(methods(handler)) do m
        length(m.sig.types) < 3 && return false
        return Client <: m.sig.types[2] && Message <: m.sig.types[3]
    end
        throw(ArgumentError("Handler function must accept (::Client, ::Message, ...)"))
    elseif !all(p -> p isa Base.Callable, parsers)
        throw(ArgumentError("All parsers must be callable"))
    elseif count(p -> p isa Splat, parsers) > 1
        throw(ArgumentError("Only one Splat parser can be used at a time"))
    end

    function predicate(c::Client, e::MessageCreate)
        # Exclude webhooks and empty messages.
        ismissing(e.message.webhook_id) || return false
        isempty(e.message.content) && return false

        # Exclude self messages.
        id = me(c) === nothing ? nothing : me(c).id
        author = e.message.author
        !ismissing(author) && author.id == id && return false

        # Check the prefix.
        pfx = prefix(c, e.message.guild_id)
        startswith(e.message.content, pfx) || return false

        # Check the pattern.
        m = match(pattern, noprefix(e.message.content, pfx))
        m === nothing && return false

        # Check the arguments.
        try
            parsecaps(parsers, Any[m.captures...])
        catch
            return FB_PARSERS
        end

        # Check authorization.
        if !isempty(allowed)
            ids = ismissing(author) ? Snowflake[] : [author.id]
            if ismissing(e.message.member)
                # TODO: Should we be making potential REST calls here (also in perm check)?
                # It's very likely that everything is cached but that's not a given.
                if !ismissing(e.message.guild_id)
                    guild = fetch(retrieve(c, Guild, e.message.guild_id))
                    if guild.ok
                        member = fetch(retrieve(c, Member, guild.val, author))
                        member.ok && append!(ids, member.val.roles)
                    end
                end
            else
                append!(ids, e.message.member.roles)
            end

            # We do run the fallback for lack of permissions.
            any(id -> id in allowed, ids) || return FB_ALLOWED
        end

        # Check permissions.
        if !ismissing(author) && !ismissing(e.message.guild_id) && permissions != PERM_NONE
            @deferred_fetch begin
                guild = retrieve(c, Guild, e.message.guild_id)
                channel = retrieve(c, DiscordChannel, e.message.channel_id)
            end
            if guild.ok && channel.ok
                member = fetch(retrieve(c, Member, guild.val, author))
                if member.ok
                    user_perms = permissions_in(member.val, guild.val, channel.val)
                    user_perms & permissions == permissions || return FB_PERMISSIONS
                end
            end
        end

        # Check cooldowns.
        if !ismissing(author) && cooldown !== nothing
            cmd = get(get(c.handlers, MessageCreate, Dict()), name, nothing)
            cmd !== nothing && haskey(cmd.cooldowns, author.id) && return FB_COOLDOWN
            cmd.cooldowns[author.id] = nothing  # Update the rate limiter.
        end

        return true
    end

    function wrapped_handler(c::Client, e::MessageCreate)
        m = match(pattern, noprefix(e.message.content, prefix(c, e.message.guild_id)))
        handler(c, e.message, parsecaps(parsers, Any[m.captures...])...)
    end

    # Run the fallbacks on the message itself.
    wrapped_fb_parsers(c::Client, e::MessageCreate) = fallback_parsers(c, e.message)
    wrapped_fb_allowed(c::Client, e::MessageCreate) = fallback_allowed(c, e.message)
    wrapped_fb_permissions(c::Client, e::MessageCreate) = fallback_permissions(c, e.message)
    wrapped_fb_cooldown(c::Client, e::MessageCreate) = fallback_cooldown(c, e.message)

    return Command(
        Handler{MessageCreate}(
            predicate, wrapped_handler, donothing,
            priority, remaining, timeout, nothing, false,
        ),
        name, help, cooldown, wrapped_fb_parsers, wrapped_fb_allowed,
        wrapped_fb_permissions, wrapped_fb_cooldown,
    )
end

"""
    @command name=name handler=handler kwargs...

Mark a function as a bot command to be collected by [`add_command!`](@ref) (from a module).
Supported keywords are identical to `add_command!`.

## Example
```julia
module Commands
using Discord
echo(c::Client, m::Message, noprefix::AbstractString) = reply(c, m, noprefix)
@command name=:echo handler=echo help="Echo a message" pattern=r"^echo (.+)"
end
c = Client("token")
add_command!(c, Commands)
```
"""
macro command(exs...)
    kws = map(ex -> Expr(:kw, ex.args[1], esc(ex.args[2])), exs)
    quote
        $(gensym(:djl_cmd)) = Discord.Command(; $(kws...))
    end
end

"""
    Splat(func::Base.Callable=identity, split::StringOrChar=' ') -> Splat

Collect a variable number of arguments from one capture group with a single parser.
"""
struct Splat <: Function
    func::Base.Callable
    split::StringOrChar
end
Splat() = Splat(identity, ' ')
Splat(func::Base.Callable) = Splat(func, ' ')
Splat(split::StringOrChar) = Splat(identity, split)

predicate(c::Command) = predicate(c.h)
handler(c::Command) = handler(c.h)
priority(c::Command) = priority(c.h)
expiry(c::Command) = expiry(c.h)
dec!(c::Command) = dec!(c.h)
isexpired(c::Command) = isexpired(c.h)
function fallback(c::Command, r::FallbackReason)
    return if r === FB_PARSERS
        c.fb_parsers
    elseif r === FB_ALLOWED
        c.fb_allowed
    elseif r === FB_PERMISSIONS
        c.fb_permissions
    elseif r === FB_COOLDOWN
        c.fb_cooldown
    else
        donothing
    end
end

"""
    add_command!(
        c::Client,
        name::Symbol,
        handler::Function;
        help::AbstractString="",
        parsers::Vector=[],
        separator::StringOrChar=' ',
        pattern::Regex=defaultpattern(name, length(parsers), separator),
        allowed::Vector{<:Integer}=Snowflake[],
        permissions::Integer=PERM_NONE,
        cooldown::Nullable{Period}=nothing,
        fallback_parsers::Function=donothing,
        fallback_allowed::Function=donothing,
        fallback_permissions::Function=donothing,
        fallback_cooldown::Function=donothing,
        priority::Int=$DEFAULT_PRIORITY,
        count::Nullable{Int}=nothing,
        timeout::Nullable{Period}=nothing,
        compile::Bool=false,
        kwargs...,
    )

Add a text command handler. `do` syntax is also accepted.

### Handler Function
The handler function must accept a [`Client`](@ref) and a [`Message`](@ref). Additionally,
it can accept any number of additional arguments, which are captured from `pattern`
and parsed with `parsers` (see below).

### Command Pattern
The `pattern` keyword specifies how to invoke the command. The given `Regex` must match the
message contents after having removed the command prefix. By default, it's the command name
with as many wildcard capture groups as there are parsers, separated by the `separator`
keyword (a space character by default).

### Command Help
The `help` keyword specifies a help string which can be used by [`add_help!`](@ref).

### Argument Parsing
The `parsers` keyword sets the parsers of the command arguments, and can contain both
types and functions. If `pattern` contains captures, then they are run through the parsers
before being passed into the handler. For repeating arguments, see [`Splat`](@ref).

### Authorization + Required Permissions
The `allowed` keyword specifies [`User`](@ref)s or [`Role`](@ref)s (by ID) that are allowed
to use the command. The `permissions` keyword sets the minimum permissions that command
callers must have.

### Rate Limiting
The `cooldown` keyword sets the rate at which a user can invoke the command. The default
of `nothing` indicates no limit.

### Fallback Functions
The `fallback_*` keywords specify functions to be run whenever a command is called but
cannot be run, such as failed argument parsing, missing permissions, or rate limiting.
They should accept a [`Client`](@ref) and a [`Message`](@ref).

Additional keyword arguments are a subset of those to [`add_handler!`](@ref).

## Examples
Basic echo command with a help string:
```julia
add_command!(c, :echo, (c, m) -> reply(c, m, m.content); help="repeat a message")
```
The same, but excluding the command part:
```julia
add_command!(c, :echo, (c, m, msg) -> reply(c, m, msg); pattern=r"^echo (.+)")
```
Parsing a subtraction expression with custom parsers and separator:
```julia
add_command!(
    c, :sub, (c, m, a, b) -> reply(c, m, string(a - b));
    parsers=[Float64, Float64], separator='-',
)
```
Splatting some comma-separated numbers with a parsing fallback function:
```julia
add_command!(
    c, :sum, (c, m, xs...) -> reply(c, m, string(sum(collect(xs))));
    parsers=[Splat(Float64, ',')],
    fallback_parsers=(c, m) -> reply(c, m, "Args must be numbers."),
)
```
"""
function add_command!(
    c::Client,
    name::Symbol,
    handler::Function;
    help::AbstractString="",
    parsers::Vector=[],
    separator::StringOrChar=' ',
    pattern::Regex=defaultpattern(name, length(parsers), separator),
    allowed::Vector{<:Integer}=Snowflake[],
    permissions::Integer=PERM_NONE,
    cooldown::Nullable{Period}=nothing,
    fallback_parsers::Function=donothing,
    fallback_allowed::Function=donothing,
    fallback_permissions::Function=donothing,
    fallback_cooldown::Function=donothing,
    priority::Int=DEFAULT_PRIORITY,
    count::Nullable{Int}=nothing,
    timeout::Nullable{Period}=nothing,
    compile::Bool=false,
    kwargs...,
)
    cmd = Command(;
        name=name, handler=handler, help=help, parsers=parsers, separator=separator,
        pattern=pattern, allowed=allowed, permissions=permissions,
        fallback_parsers=fallback_parsers, cooldown=cooldown, priority=priority,
        remaining=count, timeout=timeout,
    )
    puthandler!(c, cmd, name, compile; message=mock(Message; kwargs...))
end
function add_command!(handler::Function, c::Client, name::Symbol; kwargs...)
    add_command!(c, name, handler; kwargs...)
end

"""
    add_command!(c::Client, m::Module; compile::Bool=false; kwargs...)

Add all of the bot commands defined in a module. To set up commands to be included, see
[`@command`](@ref).
"""
function add_command!(c::Client, m::Module; compile::Bool=false, kwargs...)
    for cmd in filter(cmd -> cmd isa Command, map(n -> getfield(m, n), names(m; all=true)))
        puthandler!(c, cmd, cmd.name, compile; kwargs...)
    end
end

"""
    delete_command!(c::Client, name::Symbol)

Delete a command.
"""
delete_command!(c::Client, name::Symbol) = delete_handler!(c, MessageCreate, name)

"""
    add_help!(
        c::Client;
        pattern::Regex=r"^help(?: (.+))?",
        help::AbstractString="Show this help message",
        nohelp::AbstractString="No help provided",
        nocmd::AbstractString="Command not found",
    )

Add a help command. This can be called at any time, new commands will be included
automatically.

## Keywords
- `separator::StringOrChar`: Separator between commands.
- `pattern::Regex`: The command pattern (see [`add_command!`](@ref)).
- `help::AbstractString`: Help for the help command.
- `nohelp::AbstractString`: Help for commands without their own help string.
- `nocmd::AbstractString`: Help for commands that aren't found.
"""
function add_help!(
    c::Client;
    separator::StringOrChar=' ',
    pattern::Regex=r"^help(?: (.+))?",
    help::AbstractString="Show this help message",
    nohelp::AbstractString="No help provided",
    nocmd::AbstractString="Command not found",
)
    function handler(c::Client, m::Message, names::String...)
        names = strip.(names)
        sort!(collect(names))
        len = maximum(length, names)
        handlers = get(c.handlers, MessageCreate, Dict())
        io = IOBuffer()

        for name in names
            padded = lpad(name, len)
            h = get(handlers, Symbol(name), nothing)
            if h isa Command
                println(io, padded, ": ", isempty(h.help) ? nohelp : h.help)
            else
                println(io, padded, ": ", nocmd)
            end
        end

        reply(c, m, "```\n" * String(take!(io)) * "```")
    end

    function handler(c::Client, m::Message, ::Nothing=nothing)
        cmds = collect(get(c.handlers, MessageCreate, Dict()))
        filter!(p -> p.second isa Command, cmds)
        handler(c, m, map(p -> string(p.second.name), cmds)...)
    end

    add_command!(
        c, :help, handler;
        parsers=[Splat(separator)], pattern=pattern, help=help, priority=typemax(Int),
        compile=true, content=prefix(c) * "help",
    )
end

"""
    set_prefix!(c::Client, prefix::StringOrChar)
    set_prefix!(c::Client, prefix::StringOrChar, guild::Union{Guild, Integer})

Set [`Client`](@ref)'s command prefix. If a [`Guild`](@ref) or its ID is supplied, then the
prefix only applies to that guild.
"""
set_prefix!(c::Client, prefix::AbstractString) = c.p_global = prefix
set_prefix!(c::Client, prefix::AbstractString, guild::Integer) = c.p_guilds[guild] = prefix
set_prefix!(c::Client, prefix::AbstractString, g::Guild) = set_prefix!(c, prefix, g.id)
set_prefix!(c::Client, prefix::AbstractChar) = set_prefix!(c, string(prefix))
function set_prefix!(c::Client, prefix::AbstractChar, guild::Union{Guild, Integer})
    set_prefix!(c, string(prefix, guild))
end

# Get the command prefix.
prefix(c::Client, ::Missing=missing) = c.p_global
prefix(c::Client, guild::Integer) = get(c.p_guilds, guild, c.p_global)

# Get a string without a prefix.
function noprefix(s::AbstractString, p::AbstractString)
    return startswith(s, p) ? s[nextind(s, 1, length(p)):end] : s
end

# Parse command arguments.
function parsecaps(parsers::Vector, caps::Vector)
    map!(c -> c isa AbstractString ? string(c) : c, caps, caps)
    len = min(length(parsers), length(caps))
    parsers = parsers[1:len]
    unparsed = splice!(caps, len+1:lastindex(caps))
    args = Any[vcat(map(t -> parsecap(t...), zip(parsers, caps))...)...]
    return append!(vcat(args...), unparsed)
end

# Parse a single capture.
parsecap(::Base.Callable, ::Nothing) = []  # Optional captures don't return anything.
parsecap(p::Function, s::AbstractString) = Any[p(s)]
parsecap(p::Splat, s::AbstractString) = Any[parsecap.(p.func, string.(split(s, p.split)))...]
function parsecap(p::Type, s::AbstractString)
    return Any[hasmethod(parse, (Type{p}, AbstractString)) ? parse(p, s) : p(s)]
end

# Generate a bot command's default pattern.
function defaultpattern(name::Symbol, n::Int, separator::StringOrChar)
    return n == 0 ? Regex("^$name") : Regex("^$name " * join(repeat(["(.*)"], n), separator))
end


text:
# Use baremodule to shave off a few KB from the serialized `.ji` file
baremodule S2Geometry_jll
using Base
using Base: UUID
import JLLWrappers

JLLWrappers.@generate_main_file_header("S2Geometry")
JLLWrappers.@generate_main_file("S2Geometry", UUID("846536d6-5c10-5069-b47f-45525c463cf9"))
end  # module S2Geometry_jll


text:
function extrap_prep{N,d}(::Type{Flat}, ::Val{N}, ::Val{d})
    xs_d = Symbol("xs_", d)
    :($xs_d = clamp($xs_d, lbound(etp, $d), ubound(etp, $d)))
end

function extrap_prep{N,d}(::Type{Flat}, ::Val{N}, ::Val{d}, ::Val{:lo})
    xs_d = Symbol("xs_", d)
    :($xs_d = max($xs_d, lbound(etp, $d)))
end

function extrap_prep{N,d}(::Type{Flat}, ::Val{N}, ::Val{d}, ::Val{:hi})
    xs_d = Symbol("xs_", d)
    :($xs_d = min($xs_d, ubound(etp, $d)))
end

function extrap_prep{N,d}(::Val{:gradient}, ::Type{Flat}, ::Val{N}, ::Val{d}, ::Val{:lo})
    coords = [Symbol("xs_", k) for k in 1:N]
    xs_d = coords[d]

    quote
        if $xs_d < lbound(etp, $d)
            $xs_d = lbound(etp, $d)
            gradient!(g, etp.itp, $(coords...))
            g[$d] = 0
            return g
        end
    end
end

function extrap_prep{N,d}(::Val{:gradient}, ::Type{Flat}, ::Val{N}, ::Val{d}, ::Val{:hi})
    coords = [Symbol("xs_", k) for k in 1:N]
    xs_d = coords[d]

    quote
        if $xs_d > ubound(etp, $d)
            $xs_d = ubound(etp, $d)
            gradient!(g, etp.itp, $(coords...))
            g[$d] = 0
            return g
        end
    end
end


text:
module SimpleWorld

export status_report, load_all

include("Rebuild-All-Packages.jl")

end


text:
#WIP currently runs simulated SimulatedAnnealing in compressed img
function (algorithm::MultiResolutionHybrid)(img::AbstractArray)
    @warn "This function is WIP and will only return zeros."
    # T₀ = algorithm.T₀
    # α = algorithm.α
    # integration_factor = algorithm.integration_factor
    # smoothness = algorithm.smoothness
    # integration_factor2 = algorithm.integration_factor2
    # smoothness2 = algorithm.smoothness2
    # img_size = first(size(img))
    # E = Float64.(img)
    # Eₘ = maximum(E)
    # ρ = sqrt.((Eₘ^2)./(E.^2) .- 1)
    # ρ = imfilter(ρ, Kernel.gaussian(3))
    # E₁ = Eₘ ./ (1 .+ (ρ[1:2:end, 1:2:end,].^2))
    # ρ = sqrt.((Eₘ^2)./(E₁.^2) .- 1)
    # ρ = imfilter(ρ, Kernel.gaussian(3))
    # E₂ = Eₘ ./ (1 .+ (ρ[1:2:end, 1:2:end,].^2))
    # ρ = sqrt.((Eₘ^2)./(E₂.^2) .- 1)
    # ρ = imfilter(ρ, Kernel.gaussian(3))
    # E₃ = Eₘ ./ (1 .+ (ρ[1:2:end, 1:2:end,].^2))
    # p = rand(Float64, size(E₃))
    # q = rand(Float64, size(E₃))
    # pn, qn = SimulatedAnnealing(pin = p, qin = q, T₀ = T₀, α = α, integration_factor = integration_factor, smoothness = smoothness, max_iter = 1)(E₃)
    p = zeros(Float64, size(img))
    q = zeros(Float64, size(img))
    return p, q
end


text:
###
#   Script for launching many Himmelblaus
###

numProcs = [1, 5, 10, 20, 50, 80, 100, 120, 150, 180]

script = ""
for num in numProcs

    script =
"#!/bin/bash -l
#SBATCH -p phi
#SBATCH -e errors_$num
#SBATCH -o output_$num
#SBATCH -D ./
#SBATCH --export=ALL
#SBATCH -n $num
#SBATCH -t 24:00:00

module purge
#module load neutronics
#module load libs/qt/5.9.1/gcc-5.5.0
module load python/3.6
module load julia

#
# Should not need to edit below this line
#
echo ========================================================= echo SLURM job: submitted date = `date`
date_start=`date +%s`
echo ========================================================= echo Job output begins
echo -----------------
echo
hostname

julia tmcmcHimmelblau_par_Slurm.jl $num
echo
echo ---------------
echo Job output ends
echo =========================================================
echo SLURM job: finished date = `date`
    "

    #println(script)
    open("runSim_$num.sh","w") do io
        print(io, script)
    end
    run(`sbatch runSim_$num.sh`);
end


text:
using Test
@time begin
    @time include("test_2d_generators.jl")
    @time include("test_mesh2.jl")
    @time include("test_boundaryhandler.jl")
    @time include("test_dofhandler.jl")
    @time include("test_interpolators.jl")
    @time include("test_quads.jl")
    @time include("test_assembler.jl")
    @time include("test_2d_vem_poisson.jl")
    @time include("test_basis.jl")
    @time include("test_fe.jl")
    @time include("test_FunctionSpace.jl")
end

max_stars_repo_name: Paulms/jFEMToools

max_issues_repo_name: Paulms/jFEMToools

max_forks_repo_name: Paulms/jFEMToools


text:
# This file is a part of DataDeps.jl. License is MIT.

function handle_missing(datadep::ManualDataDep, calling_filepath)::String
    localpaths = list_local_paths(datadep, calling_filepath)
    @assert(length(localpaths) > 0)
    @info("This program requested access to the data dependency $(datadep.name)")
    @info("It could not be found on your system. It requires manual installation.")
    @info("Please install it to one of the directories in the DataDeps load path: " *
          join(localpaths,", \n", ",\nor "))
    @info("by following the instructions:")
    @info(datadep.message)
    while true
        reply = input_choice("Once installed please enter 'y' reattempt loading, or 'a' to abort", 'y','a')
        if reply=='a'
            abort("User has aborted attempt to load datadep. Can not proceed without loading.")
        end
        lp = try_determine_load_path(datadep.name, calling_filepath)
        if lp == nothing
            @info("Still failed to find $(datadep.name). User should reattempt to install it.")
        else
            return lp
        end
    end
end


text:
mutable struct Record
    next::Union{Record,Nothing}  # next kan peke på et Record-objekt eller ha verdien nothing.
    value::Int
end

function createlinkedlist(length, valuerange)
    # Lager listen bakfra.
    next = nothing
    record = nothing
    for i in 1:length
        record = Record(next, rand(valuerange))  # valuerange kan f.eks. være 1:1000.
        next = record
    end
    return record
end

function find_max(list::Record)
	cur_pos = list
	cur_max = list.value
	while cur_pos.next != nothing
		if cur_max < cur_pos.value
			cur_max = cur_pos.value
		end
		println(cur_pos.value)
		cur_pos = cur_pos.next
	end
	return cur_max
end


text:
function communities_crime(repls=1, nfolds=6)
	communities_data = @load_communities_crime
	communities_data[1].Column8 = convert(Array{Float64},
										communities_data[1].Column8) .<= 0.18
	#0.18 is the mean value for racepctblack

	communities_crime_task = Task(communities_data[1], communities_data[2],
								grp=:Column8,
								debiasmeasures=[fpr, fnr])
	FairnessProblem(
		communities_crime_task,
		measures=[fnr, fpr],
		repls=repls, nfolds=nfolds, name="communities_crime")
end

function student(repls=1, nfolds=6)
   student_task = Task((@load_student_performance)...,
					   grp=:sex, debiasmeasures=[fnr])
   FairnessProblem(
	   student_task,
	   measures=[fnr, fpr],
	   repls=repls, nfolds=nfolds, name="StudentPerformance")
end

function hmda(repls=1, nfolds=6)
	hmda_df = CSV.read(joinpath(@__DIR__, "..", "data", "HMDA_2018_California.csv"))
	filter!(:derived_sex => x -> x != "Sex Not Available", hmda_df)
	categorical!(hmda_df, [:conforming_loan_limit, :derived_loan_product_type ,
			:derived_dwelling_category, :derived_ethnicity, :derived_race,
			:derived_sex, :action_taken, :purchaser_type, :loan_type,
			:applicant_age, ])
	select!(hmda_df, Not(:county_code))
	rename!(hmda_df, "open-end_line_of_credit" => "open_end_line_of_credit")

	hmda_task = Task(deletecols(hmda_df, :action_taken), hmda_df.action_taken,
				grp=:derived_sex, debiasmeasures=[false_omission_rate])

	FairnessProblem(hmda_task,
		measures=[false_omission_rate, fpr],
		repls=repls, nfolds=nfolds, name="HMDA_Mortgage")
end

function zafar(repls=1, nfolds=6)
   zafar_task = Task((genZafarData())...,
					   grp=:z, debiasmeasures=[])
   FairnessProblem(
	   zafar_task,
	   measures=[],
	   repls=repls, nfolds=nfolds, name="ZafarData")
end

function zafar2(repls=1, nfolds=6)
   zafar2_task = Task((genZafarData2())...,
					   grp=:z, debiasmeasures=[])
   FairnessProblem(
	   zafar2_task,
	   measures=[],
	   repls=repls, nfolds=nfolds, name="StudentPerformance")
end

function subgroup(repls=1, nfolds=6)
   subgroup_task = Task((genSubgroupData(setting="B01"))...,
					   grp=:z, debiasmeasures=[])
   FairnessProblem(
	   subgroup_task,
	   measures=[],
	   repls=repls, nfolds=nfolds, name="SubGroupData")
end

function biased(repls=1, nfolds=6)
   biased_task = Task((genBiasedSampleData())...,
					   grp=:z, debiasmeasures=[])
   biased = FairnessProblem(
	   biased_task,
	   measures=[],
	   repls=repls, nfolds=nfolds, name="BiasedSampleData")
end

function adult(repls=1, nfolds=6)
   adult_task = Task((@load_adult)..., grp=:sex, debiasmeasures=[ppr]) # could keep :sex also as protected attribute
   FairnessProblem(
	   adult_task,
	   refGrp="Male", measures=[ppr, fnr, fpr],
	   repls=repls, nfolds=nfolds, name="Adult")
end

function german(repls=1, nfolds=6)
   german_task = Task((@load_german)..., grp=:gender_status, debiasmeasures=[false_omission_rate])
   FairnessProblem(
	   german_task,
	   refGrp="male_single", measures=[foar, fnr, fpr],
	   repls=repls, nfolds=nfolds, name="German")
end

function portuguese(repls=1, nfolds=6)
   portuguese_task = Task((@load_bank_marketing)...,
					   grp=:marital, debiasmeasures=[false_omission_rate, ppr])
   FairnessProblem(
	   portuguese_task,
	   measures=[false_omission_rate, ppr, fpr],
	   repls=repls, nfolds=nfolds, name="Portuguese")
end

function framingham(repls=1, nfolds=6)
   framingham_df = CSV.read(joinpath(@__DIR__, "..", "data", "framingham.csv"))
   categorical!(framingham_df, [:male, :education, :currentSmoker, :BPMeds,
			   :prevalentStroke, :prevalentHyp, :diabetes, :TenYearCHD])

   framingham_task = Task(deletecols(framingham_df, :TenYearCHD),
			   framingham_df.TenYearCHD, grp=:male,
			   debiasmeasures=[false_omission_rate])

   FairnessProblem(framingham_task,
				   measures=[false_omission_rate],
				   repls=repls, nfolds=nfolds, name="Framingham")
end

function loan(repls=1, nfolds=6)
   loan_df = CSV.read(joinpath(@__DIR__, "..", "data", "loan_default.csv"))
   categorical!(loan_df, [:SEX, :EDUCATION, :MARRIAGE,
		   Symbol("default payment next month")])
   loan_task = Task(deletecols(loan_df, Symbol("default payment next month")),
			   loan_df[!, Symbol("default payment next month")],
			   grp=:SEX, debiasmeasures=[false_omission_rate])
   FairnessProblem(loan_task, measures=[false_omission_rate, fpr],
					   repls=repls, nfolds=nfolds, name="LoanDefault")
end

function medical(repls=1, nfolds=6)
   medical_df = CSV.read(joinpath(@__DIR__, "..", "data", "meps.csv"))

   categorical!(medical_df, ["REGION","SEX","MARRY","FTSTU","ACTDTY","HONRDC",
			   "RTHLTH","MNHLTH","HIBPDX","CHDDX","ANGIDX","MIDX",
			   "OHRTDX","STRKDX","EMPHDX","CHBRON","CHOLDX","CANCERDX","DIABDX",
			   "JTPAIN","ARTHDX","ARTHTYPE","ASTHDX","ADHDADDX","PREGNT","WLKLIM",
			   "ACTLIM","SOCLIM","COGLIM","DFHEAR42","DFSEE42", "ADSMOK42",
			   "PHQ242","EMPST","POVCAT","INSCOV", "UTILIZATION"])

   medical_task = Task(deletecols(medical_df, Symbol("UTILIZATION")),
			   medical_df[!, Symbol("UTILIZATION")],
			   grp=:RACE, debiasmeasures=[false_omission_rate])
   FairnessProblem(medical_task, measures=[false_omission_rate, fnr],
					   repls=repls, nfolds=nfolds, name="MedicalExpenditure")
end

fairness_problems() = [compas(), adult(), german(), portuguese(),
					   student(), framingham(), loan(), medical()]


text:
linear(x::Vector, y::Vector) = (x' * y)[1]
polynomial(x::Vector, y::Vector, d) = (x' * y + 1)[1] ^ d
laplacian(x::Vector, y::Vector, sigma) = exp(-norm(x - y) / sigma ^ 2)
rbf(x::Vector, y::Vector, sigma) = exp(-norm(x - y, 1) / sigma ^ 2)


text:
using vSmartMOM
using vSmartMOM.Architectures
using vSmartMOM.Absorption
using vSmartMOM.Scattering
using vSmartMOM.CoreRT
using vSmartMOM.SolarModel
using Test
using DelimitedFiles
using Statistics
using ProgressMeter
using WignerSymbols
using Distributions
using JLD2

# Test the Absorption module
@testset "vSmartMOM.Absorption" begin include("test_Absorption.jl") end

# Test the Scattering module
@testset "vSmartMOM.Scattering" begin include("test_Scattering.jl") end

# Test the CoreRT module
@testset "vSmartMOM.vSmartMOM" begin include("test_CoreRT.jl") end

# Test the SolarModel module
@testset "vSmartMOM.SolarModel" begin include("test_SolarModel.jl") end


text:
locations(data::PopData)

function locations!(data::PopData, lat::Vector{Union{Missing,T}},
function locations!(data::PopData, lat::Vector{T}, long::Vector{T})
function locations!(data::PopData, lat::Vector{Union{Missing,String}}, long::Vector{Union{Missing,String}})
function locations!(
    data::PopData,
    lat_deg::Vector{Union{Missing,Int}},
    lat_min::Vector{Union{Missing,Float64}},
    long_deg::Vector{Union{Missing,Int}},
    long_min::Vector{Union{Missing,Float64}},
)
function locations!(data::PopData; kwargs...)

function loci(data::PopData)
function loci(data::IndexedTable)
function locus(data::PopData, locus::String)
function meta(data::PopData)
@inline function Base.missing(data::PopData; mode::String = "sample")
@inline function populations(data::PopData; listall::Bool = false)
function populations!(data::PopData, rename::Dict)
function populations!(data::PopData, rename::Vector{String})
function populations!(data::PopData, rename::NamedTuple)
function populations!(data::PopData, rename::Vector{String}, function populations!(data::PopData, oldnames::Vector{String},
function exclude_loci(data::PopData, locus::String)
function exclude_loci(data::PopData, exloci::Vector{String})
function exclude_samples(data::PopData, samp_id::String)
function exclude_samples(data::PopData, samp_ids::Vector{String})
function samples(data::PopData)
function popdata_map_helper(d, x)
function popdata_where_helper(args...)
macro show_only(args...)


text:
using ManualMemory: MemoryBuffer, load, store!, LazyPreserve, preserve, PseudoPtr, Reference
using Test

@testset "ManualMemory.jl" begin

  @test_throws AssertionError MemoryBuffer{4,String}(undef)
  m = MemoryBuffer{4,Float64}(undef);
  store!(pointer(m), 1.23)
  @test load(pointer(m)) == 1.23
  str = "Hello world!"
  GC.@preserve str begin
    store!(Base.unsafe_convert(Ptr{String}, m), str)
    @test load(Base.unsafe_convert(Ptr{String}, m)) === str
  end

  x = [0 0; 0 0];
  preserve(store!, LazyPreserve(x), 1)
  @test x[1] === 1
  p = PseudoPtr(x, 1)
  @test load(p) === 1
  p += 1
  store!(p, 2)
  @test load(p) === 2
  p = 1 + p
  store!(p, 3)
  @test load(p) === 3

  x = Reference{Int}()
  y = Reference(1)
  GC.@preserve x y begin
    store!(pointer(x), 1)
    @test load(pointer(x)) === 1 === load(pointer(y))
  end
end

using ThreadingUtilities
include(joinpath(pkgdir(ThreadingUtilities), "test", "runtests.jl"))


text:
"""
    login(token::AbstractString)

This function will store the token in the `MANGAL_BEARER_TOKEN` environmental
variable. To get the your token, please use `login` with no argument.
"""
function login(token::AbstractString)
    ENV["MANGAL_BEARER_TOKEN"] = token
    @info "Bearer token registered"
end

"""
    login()

Read the bearer token from the `MANGAL_BEARER_TOKEN` environment variable. If
not found, displays a login message with a login URL. Currently, being logged in
is only necessary to access private datasets.
"""
function login()
    if haskey(ENV, "MANGAL_BEARER_TOKEN")
        @info "Your bearer token is already registered"
    else
        Mangal.login_message()
    end
end

"""
    login_message()

Points user to the login URL, and explains how the bearer token can be saved
persistently.
"""
function login_message()
    @info "You need to login"

    msg = """ To login, please go to

    $(Mangal.web_root)auth/

    You will be prompted to login using ORCID - when this is done, you will be
    returned to your profile page, which contains the access_token. Copy and
    paste this value, and use it in the login function:

    julia> my_access_token = "12345654-1234-1234-4321-4343435353"
    julia> Mangal.login(my_access_token)

    If you want to save your bearer token, you can place it in an environmental
    variable named MANGAL_BEARER_TOKEN -- this will let you use

    julia> Mangal.login()
    """

    @info msg
end


text:
# Tests for atoms.jl

@testset "Atoms" begin
    @test inferelement("CA") == "C"
    @test inferelement("NC") == "C"
    @test inferelement("NH") == "N"
    @test inferelement("X") == "-"

    atom_one = Atom("CA", "ALA", 'A', 20, [0.0, 0.0, 0.0], "C")
    atom_two = Atom("CA", "XXX", 'A', 20, [0.0, 0.0, 0.0], "C")
    atom_three = Atom("C", "ALA", 'A', 20, [0.0, 0.0, 0.0], "C")
    @test areatomssame(atom_one, atom_two)
    @test !areatomssame(atom_one, atom_three)

    atoms_one = Atom[
        Atom("CA", "ALA", 'A', 20, [0.0, 0.0, 0.0], "C"),
        Atom("C", "ALA", 'A', 20, [0.0, 0.0, 0.0], "C")
    ]
    atoms_two = Atom[Atom("CA", "SER", 'A', 20, [0.0, 0.0, 0.0], "C")]
    common_one_test, common_two_test = findcommonatoms(atoms_one, atoms_two)
    common_one_real = Atom[Atom("CA", "ALA", 'A', 20, [0.0, 0.0, 0.0], "C")]
    common_two_real = Atom[Atom("CA", "SER", 'A', 20, [0.0, 0.0, 0.0], "C")]
    @test length(common_one_test) == 1
    @test length(common_two_test) == 1
    @test common_one_test[1].atom_name == common_one_real[1].atom_name
    @test common_one_test[1].res_name == common_one_real[1].res_name
    @test common_two_test[1].atom_name == common_two_real[1].atom_name
    @test common_two_test[1].res_name == common_two_real[1].res_name

    atoms_one = [
        Atom("CA", "ALA", 'A', 22, [0.0, 0.0, 0.0], "C"),
        Atom("CA", "ALA", 'A', 19, [0.0, 0.0, 0.0], "C"),
        Atom("CA", "ALA", 'A', 20, [0.0, 0.0, 0.0], "C"),
    ]
    atoms_two = [
        Atom("CA", "ALA", 'A', 20, [0.0, 0.0, 0.0], "C"),
        Atom("CA", "ALA", 'A', 21, [0.0, 0.0, 0.0], "C"),
        Atom("CA", "ALA", 'A', 22, [0.0, 0.0, 0.0], "C"),
    ]
    atom_map = atommap(atoms_one, atoms_two)
    @test atom_map == [3, 0, 1]

    @test atomid(Atom("CA", "ALA", 'A', 20, [0.0, 0.0, 0.0], "C")) == "CA/ALA/20/A"

    atom_one = Atom("C", "ALA", 'A', 20, [0.0, 0.0, 0.0], "C")
    atom_two = Atom("CA", "ALA", 'A', 20, [0.0, 0.0, 0.0], "C")
    atom_thr = Atom("N", "ALA", 'A', 20, [0.0, 0.0, 0.0], "N")
    atoms = [atom_one, atom_two, atom_thr]
    ca_inds = calphaindices(atoms)
    @test ca_inds == [2]

    atom_one = Atom("C", "ALA", 'A', 20, [1.0, 4.0, 5.0], "C")
    atom_two = Atom("CA", "ALA", 'A', 20, [8.0, 4.0, 2.0], "C")
    atom_thr = Atom("N", "ALA", 'A', 20, [4.0, 9.0, 3.0], "N")
    atoms = [atom_one, atom_two, atom_thr]
    coords_test = atomcoords(atoms)
    coords_real = [
        1.0 8.0 4.0;
        4.0 4.0 9.0;
        5.0 2.0 3.0;
    ]
    @test coords_test == coords_real

    atom_one = Atom("CA", "ALA", 'A', 20, [1.0, 4.0, 5.0], "C")
    atom_two = Atom("C", "ALA", 'A', 20, [8.0, 4.0, 2.0], "C")
    atoms = [atom_one, atom_two]
    coords = [
        5.0 3.0;
        6.0 8.0;
        1.0 0.0;
    ]
    atoms_test = atomcoords(atoms, coords)
    @test atoms_test[1].atom_name == "CA"
    @test atoms_test[2].atom_name == "C"
    @test atoms_test[1].coords == coords[:,1]
    @test atoms_test[2].coords == coords[:,2]
    @test atoms[1].coords == [1.0, 4.0, 5.0]
    @test atoms[2].coords == [8.0, 4.0, 2.0]

    atom_one = Atom("CA", "ALA", 'A', 20, [1.0, 4.0, 5.0], "C")
    atom_two = Atom("C", "ALA", 'A', 20, [8.0, 4.0, 2.0], "C")
    atoms = [atom_one, atom_two]
    coords = [
        5.0 3.0;
        6.0 8.0;
        1.0 0.0;
    ]
    atomcoords!(atoms, coords)
    @test atoms[1].coords == coords[:,1]
    @test atoms[2].coords == coords[:,2]

    atom = Atom(mod_atom_info["atom_name"], mod_atom_info["res_name"], mod_atom_info["chain_id"], mod_atom_info["res_n"], [0.0, 0.0, 0.0], mod_atom_info["element"])
    @test ismodulator(atom)
    atom = Atom("CA", "ALA", 'A', 20, [0.0, 0.0, 0.0], "C")
    @test !ismodulator(atom)
end


text:
include("_common.jl")

using GlobalSensitivity

function run_sa(X; node, metric)
    n_params = length(X)

    # drop dummy parameter
    X = X[1:n_params-1]
    update_params!(node, X...)

    Streamfall.run_node!(node, CALIB_CLIMATE)

    score = metric(CALIB_OBS[366:CALIB_LN], node.outflow[366:CALIB_LN])
    Streamfall.reset!(node)

    return score
end

N = 16384

for (app, metric) in zip(APPROACHES, OBJFUNCS)
    # sn, n_id = setup_network(joinpath(DATA_PATH, "cotter_baseline_calibrated_$(app).yml"))
    sn, n_id = setup_network(joinpath(DATA_PATH, "410730_IHACRES.yml"))
    node = sn[n_id]

    p_names, ini_vals, p_bounds = param_info(node; with_level=false)

    @info "Running $app..."

    # Set up dummy parameter
    push!(p_names, :dummy)
    push!(ini_vals, 0.0)
    push!(p_bounds, (0.0, 1000.0))

    sa_runner = (X) -> run_sa(X; node=node, metric=metric)
    sobol_results = gsa(sa_runner, Sobol(), p_bounds, N=N)

    headers = "$app Parameter, ST, S1, Threshold"
    res_lines = zip(p_names, sobol_results.ST, sobol_results.S1, repeat([0.04], length(p_names)))
    outfile = "$(DATA_PATH)sa_results_w_dummy.csv"

    open(outfile, "a+") do f
        println(f, headers)
        for line in res_lines
            println(f, join(line, ","))
        end

        print(f, "\n")
    end
end


text:
include("common.jl")
@testset "Composite solutions" begin
    T = OrdinaryDiffEq.ODECompositeSolution

    integrator = init(prob_dde_1delay,
                      MethodOfSteps(AutoTsit5(Rosenbrock23())))

    @testset "init" begin
        @test typeof(integrator.sol) <: T
        @test typeof(integrator.integrator.sol) <: T
    end

    @testset "solve" begin
        sol1 = solve!(integrator)
        @test typeof(sol1) <: T

        # compare integration grid
        sol2 = solve(prob_dde_1delay, MethodOfSteps(Tsit5()))
        @test sol1.t == sol2.t && sol1.u == sol2.u

        # compare interpolation
        @test sol1(0:0.1:1) == sol2(0:0.1:1)
    end
end


text:
include("dependencies_for_runtests.jl")
include("dependencies_for_poisson_solvers.jl")

#####
##### Run pressure solver tests 1
#####

PB = (Periodic, Bounded)
topos = collect(Iterators.product(PB, PB, PB))[:]

two_dimensional_topologies = [(Flat,     Bounded,  Bounded),
                              (Bounded,  Flat,     Bounded),
                              (Bounded,  Bounded,  Flat),
                              (Flat,     Periodic, Bounded),
                              (Periodic, Flat,     Bounded),
                              (Periodic, Bounded,  Flat)]

@testset "Poisson solvers 1" begin
    @info "Testing Poisson solvers..."

    for arch in archs
        @testset "Poisson solver instantiation [$(typeof(arch))]" begin
            @info "  Testing Poisson solver instantiation [$(typeof(arch))]..."
            for FT in float_types

                grids_3d = [RectilinearGrid(arch, FT, size=(2, 2, 2), extent=(1, 1, 1)),
                            RectilinearGrid(arch, FT, size=(1, 2, 2), extent=(1, 1, 1)),
                            RectilinearGrid(arch, FT, size=(2, 1, 2), extent=(1, 1, 1)),
                            RectilinearGrid(arch, FT, size=(2, 2, 1), extent=(1, 1, 1))]

                grids_2d = [RectilinearGrid(arch, FT, size=(2, 2), extent=(1, 1), topology=topo)
                            for topo in two_dimensional_topologies]

                grids = []
                push!(grids, grids_3d..., grids_2d...)

                for grid in grids
                    @test poisson_solver_instantiates(grid, FFTW.ESTIMATE)
                    @test poisson_solver_instantiates(grid, FFTW.MEASURE)
                end
            end
        end

        @testset "Divergence-free solution [$(typeof(arch))]" begin
            @info "  Testing divergence-free solution [$(typeof(arch))]..."

            for topo in topos
                for N in [7, 16]

                    grids_3d = [RectilinearGrid(arch, topology=topo, size=(N, N, N), extent=(1, 1, 1)),
                                RectilinearGrid(arch, topology=topo, size=(1, N, N), extent=(1, 1, 1)),
                                RectilinearGrid(arch, topology=topo, size=(N, 1, N), extent=(1, 1, 1)),
                                RectilinearGrid(arch, topology=topo, size=(N, N, 1), extent=(1, 1, 1))]

                    grids_2d = [RectilinearGrid(arch, size=(N, N), extent=(1, 1), topology=topo)
                                for topo in two_dimensional_topologies]

                    grids = []
                    push!(grids, grids_3d..., grids_2d...)

                    for grid in grids
                        N == 7 && @info "    Testing $(topology(grid)) topology on square grids [$(typeof(arch))]..."
                        @test divergence_free_poisson_solution(grid)
                    end
                end
            end

            Ns = [11, 16]
            for topo in topos
                @info "    Testing $topo topology on rectangular grids with even and prime sizes [$(typeof(arch))]..."
                for Nx in Ns, Ny in Ns, Nz in Ns
                    grid = RectilinearGrid(arch, topology=topo, size=(Nx, Ny, Nz), extent=(1, 1, 1))
                    @test divergence_free_poisson_solution(grid)
                end
            end

            # Do a couple at Float32 (since its too expensive to repeat all tests...)
            Float32_grids = [RectilinearGrid(arch, Float32, topology=(Periodic, Bounded, Bounded), size=(16, 16, 16), extent=(1, 1, 1)),
                             RectilinearGrid(arch, Float32, topology=(Bounded, Bounded, Periodic), size=(7, 11, 13), extent=(1, 1, 1))]

            for grid in Float32_grids
                @test divergence_free_poisson_solution(grid)
            end
        end

        @testset "Convergence to analytic solution [$(typeof(arch))]" begin
            @info "  Testing convergence to analytic solution [$(typeof(arch))]..."
            for topo in topos
                @test poisson_solver_convergence(arch, topo, 2^6, 2^7)
                @test poisson_solver_convergence(arch, topo, 67, 131, mode=2)
            end
        end
    end
end


text:
import AoC2019
input_data = AoC2019.read_numbers("input17.txt")

out = AoC2019.run_program(input_data)

out_string = map(x -> Char(x), out.output)
arr = AoC2019.text2arr(out_string)
println(AoC2019.arr2text(arr))

function find_intersections(arr)
  intersections = []
  dims = size(arr)
  for x=2:dims[1]-1
    for y=2:dims[2]-1
      if arr[x,y] == '#' && arr[x+1, y] == '#' && arr[x-1,y] == '#' && arr[x,y+1] == '#' && arr[x,y-1] == '#'
        push!(intersections, (x,y))
      end
    end
  end
  alignments = map(x -> (x[1]-1) * (x[2]-1), intersections)
  return sum(alignments)
end
find_intersections(arr)

inst_A = map(x->Int(x), collect("L,6,R,8,L,4,R,8,L,12"))
inst_B = map(x->Int(x), collect("L,12,L,6,L,4,L,4"))
inst_C = map(x->Int(x), collect("L,12,R,10,L,4"))
moves = map(x->Int(x), collect("A,C,C,B,C,B,C,B,A,A"))
robot_input = vcat(moves, 10, inst_A, 10, inst_B, 10, inst_C, 10, Int('n'), 10)

println(robot_input)

input_data[1] = 2
out = AoC2019.run_program(input_data, input=robot_input)

max_stars_repo_name: buotex/aoc

max_issues_repo_name: buotex/aoc

max_forks_repo_name: buotex/aoc


text:
using Dates
using Printf
using Libdl
@static if Base.Sys.islinux()
    RawProcDLLName = joinpath( pwd(),"dll/.so"  )
else
    RawProcDLLName = joinpath( pwd(),"./builddir/31-OnlineApp.dll" )
end
ghDLLRawProc = nothing

function dllLoad()
    global ghDLLRawProc
    ghDLLRawProc = Libdl.dlopen(RawProcDLLName)

    return
    evs ="ghDLLRawProc = Libdl.dlopen(\"$RawProcDLLName\")"
    reps = Base.Meta.parse( evs )
    Core.eval( Main,reps )
end

function MainCall(  )
    startProcessRawData = Libdl.dlsym(Main.ghDLLRawProc,:julia_main )
  println( startProcessRawData ," " ,Main.ghDLLRawProc )
    t = ccall( startProcessRawData ,
    Cint,
    ( ) )
end

dllLoad()
println("----------------")
MainCall()

max_stars_repo_name: wangzhongtian/fiberAlarmAnalyseTool

max_issues_repo_name: wangzhongtian/fiberAlarmAnalyseTool

max_forks_repo_name: wangzhongtian/fiberAlarmAnalyseTool


text:
sourcedir = joinpath(dirname(@__FILE__), "src", "GloVe-c")
cd(sourcedir)
run(`make`)


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, Pkg

name = "SDL2_mixer"
version = v"2.0.4"

# Collection of sources required to complete build
sources = [
    "http://www.libsdl.org/projects/SDL_mixer/release/SDL2_mixer-2.0.4.tar.gz" =>
    "b4cf5a382c061cd75081cf246c2aa2f9df8db04bdda8dcdc6b6cca55bede2419",
]

# Bash recipe for building across all platforms
script = raw"""
cd $WORKSPACE/srcdir/SDL2_mixer-*/
export CPPFLAGS="-I${prefix}/include"
./configure --prefix=${prefix} --build=${MACHTYPE} --host=${target} --with-pic
make -j${nproc}
make install
if [[ "${target}" == *-freebsd* ]]; then
    # We need to manually build the shared library for FreeBSD
    cd "${libdir}"
    ar x libSDL2_mixer.a
    cc -shared -o libSDL2_mixer.${dlext} *.o
fi
"""

# These are the platforms we will build for by default, unless further
# platforms are passed in on the command line
platforms = supported_platforms()

# The products that we will ensure are always built
products = [
    LibraryProduct(["libSDL2_mixer", "SDL2_mixer"], :libsdl2_mixer)
]

# Dependencies that must be installed before this package can be built
dependencies = [
    PackageSpec(name="SDL2_jll", uuid="ab825dc5-c88e-5901-9575-1e5e20358fcf")
    PackageSpec(name="libvorbis_jll", uuid="f27f6e37-5d2b-51aa-960f-b287f2bc3b7a")
    PackageSpec(name="FLAC_jll", uuid="1d38b3a6-207b-531b-80e8-c83f48dafa73")
    PackageSpec(name="mpg123_jll", uuid="3205ef68-7822-558b-ad0d-1b4740f12437")
]

# Build the tarballs.
build_tarballs(ARGS, name, version, sources, script, platforms, products, dependencies)

max_stars_repo_name: sharanry/Yggdrasil

max_issues_repo_name: sharanry/Yggdrasil

max_forks_repo_name: sharanry/Yggdrasil


text:
## FALL-BACK METHODS FOR COMPOSITE MODELS (EXPORTED LEARNING NETWORKS)

# *Note.* Be sure to read Note 4 in src/operations.jl to see see how
# fallbacks are provided for operations acting on Composite models.

caches_data_by_default(::Type{<:Composite}) = true

fitted_params(::Union{Composite,Surrogate},
              fitresult::NamedTuple) =
                  fitted_params(glb(values(fitresult)...))

# legacy code (fitresult a Node):
fitted_params(::Union{Composite,Surrogate},
              fitresult::Node) =
                  fitted_params(fitresult)

function update(model::M,
                verbosity::Integer,
                fitresult::NamedTuple,
                cache,
                args...) where M <: Composite

    # This method falls back to `fit` to force rebuilding the
    # underlying learning network if, since the last fit:
    #
    # (i) Any hyper-parameter associated with a model in the learning network
    #     has been replaced with a new model instance (and not merely
    #     mutated), OR

    # (ii) Any OTHER hyper-parameter has changed it's value (in the sense
    # of `==`).

    # Otherwise, a "smart" fit is carried out by calling `fit!` on a
    # greatest lower bound node for nodes in the signature of the
    # underlying learning network machine. For this it is necessary to
    # temporarily "de-anonymize" the source nodes.

    network_model_names = cache.network_model_names
    old_model = cache.old_model

    glb_node = glb(values(fitresult)...) # greatest lower bound

    if fallback(model, old_model, network_model_names, glb_node)
        return fit(model, verbosity, args...)
    end

    # return data to source nodes for fitting:
    sources, data = cache.sources, cache.data
    for k in eachindex(sources)
        rebind!(sources[k], data[k])
    end

    fit!(glb_node; verbosity=verbosity)

    # anonymize data again:
    for s in sources
        rebind!(s, nothing)
    end

    # record current model state:
    cache = (sources=cache.sources,
             data=cache.data,
             network_model_names=cache.network_model_names,
             old_model = deepcopy(model))

    return fitresult, cache, report(glb_node)

end

# helper for preceding method (where logic is explained):
function fallback(model::M, old_model, network_model_names, glb_node) where M
    # check the hyper-parameters corresponding to models:
    network_models = MLJBase.models(glb_node)
    for j in eachindex(network_models)
        name = network_model_names[j]
        name === nothing ||
            objectid(network_models[j])===objectid(getproperty(model, name)) ||
            return true
    end
    # check any other hyper-parameter:
    for name in propertynames(model)
        if !(name in network_model_names)
            old_value = getproperty(old_model, name)
            value = getproperty(model, name)
            value == old_value || return true
        end
    end
    return false
end

# legacy version of above (fitresult a Node):
function update(model::Composite,
                verbosity::Integer,
                yhat::Node,
                cache,
                args...)

    # If any `model` hyper-parameter has been replaced (and not just
    # mutated) then we actually need to fit rather than update (which
    # will force build of a new learning network). If `model` has been
    # created using a learning network export macro, the test used
    # below is perfect. In any other case it is at least conservative:
    network_model_ids = objectid.(models(yhat))
    fields = [getproperty(model, name) for name in propertynames(model)]
    submodels    = filter(f->f isa Model, fields)
    submodel_ids = objectid.(submodels)
    if !issubset(submodel_ids, network_model_ids)
        return fit(model, verbosity, args...)
    end

    is_anonymized = cache isa NamedTuple{(:sources, :data)}

    if is_anonymized
        sources, data = cache.sources, cache.data
        for k in eachindex(sources)
            rebind!(sources[k], data[k])
        end
    end

    fit!(yhat; verbosity=verbosity)
    if is_anonymized
        for s in sources
            rebind!(s, nothing)
        end
    end

    return yhat, cache, report(yhat)
end

# legacy method (replacements defined in operations.jl):
const _SC = Union{DeterministicComposite,
                  ProbabilisticComposite,
                  JointProbabilisticComposite,
                  IntervalComposite}
predict(::_SC, fitresult::Node, Xnew) = fitresult(Xnew)

# legacy method (replacements defined in operations.jl):
transform(::UnsupervisedComposite, fitresult::Node, Xnew) = fitresult(Xnew)


text:
include("../src/eki.jl")

using .EKI
using Plots
using Plots.PlotMeasures
using LinearAlgebra
using JLD2
using Statistics
#using LaTeXStrings

using .EKI

# utility functions
function get_marginal_sd(param_sample)
    # n_samples, n_params = size(param_sample)
    param_var=var(param_sample,dims=1)
    param_sd=sqrt.(param_var)

    return param_sd

end
function compute_error_new(self::EKIObj,it)
    meang=dropdims(mean(self.g[it],dims=1),dims=1)
    diff = self.g_t - meang
    err = diff' * inv(self.cov)* diff #as the mean of g has a reduced mean due to sample size
    return err
end

"""
Plotting script for the ensemble, It plots the following traced over iterations of EKP:
- The residual of mean difference to the truth data weighted by the covariance (as stored in the EKP)
- The standard deviations of each parameter in the ensemble

I assume 2 parameters for now, but easily extendable to more

requires:
---------
- EKP object
- the min and make of EKP iterations to plot over

"""

######################################################################
function main()

    #object
    @load ekpdir*"ekp.jld2" ekpobj

    #plot from min to max iteration of ekp
    min_ekp_it=1
    max_ekp_it=10

    u=ekpobj.u[min_ekp_it:max_ekp_it]#it x [enssize x param]

    #get sd
    u_sd = get_marginal_sd.(u) #u_sd[i] = [RH_sd,tau_sd]
    u_sd = cat(u_sd...,dims=1) #make into matrix with num_param columns

    #get error
    g_residual = map(x->compute_error_new(ekpobj,x), min_ekp_it:max_ekp_it)

    iterations = 0:size(u_sd)[1]-1 #start at 0 for "ICs"
    #plot - SD of parameters
    gr(size=(500,500))
    Plots.scalefontsizes(1.25)

    plot(iterations,
         u_sd[:,1],
         label="\\theta_{RH}",
         seriestype=:scatter,
         markershape=:circle,
         markercolor=:blue,
         markersize=8,
         msw=0,
         dpi=300,
         legend=:topright,
         framestyle=:box,
         grid=false,
         left_margin=50px,
         bottom_margin=50px)

    plot!(iterations,
          u_sd[:,2],
          seriestype=:scatter,
          markershape=:cross,
          markercolor=:orange,
          markersize=6,
          msw=0,
          label="\\theta_\\tau")

    xlabel!("Iteration")
    ylabel!("Ensemble Standard Deviation")
    savefig(outdir*"sd_ekp.pdf")

    #plot - Residual

    plot(iterations,
         g_residual,
#         yaxis=:log10,
#         ylims=(1,100),
         line = :scatter,
         markershape=:circle,
         markercolor=:grey,
         markersize=8,
         msw=0,
         dpi=300,
         legend=false,
         grid=false,
         framestyle=:box,
         left_margin=75px,
         bottom_margin=50px)
    xlabel!("Iteration")
    ylabel!("Residual")
    savefig(outdir*"residual_ekp.pdf")

end

main()


text:
mutable struct prior_zpr_t <: LCMType
  utime::Int64 # unix time associated with this pose
  id::Int64    # pose id (sequential, 0-based)

  z::Float64
  pitch::Float64
  roll::Float64

  var_z::Float64
  var_pitch::Float64
  var_roll::Float64
end

@lcmtypesetup(prior_zpr_t)


text:
module CentroidalTrajOptTest

using CentroidalTrajOpt
using Test
using Random
using StaticArrays
using LinearAlgebra
using Rotations
using CoordinateTransformations

using CentroidalTrajOpt: align_z_axis, closest_pose

@testset "align_z_axis" begin
    rng = MersenneTwister(2)
    for i = 1 : 100
        unaligned = rand(rng, Quat)
        z_axis = normalize(rand(rng, SVector{3}))
        aligned = align_z_axis(unaligned, z_axis)
        @test aligned * SVector(0, 0, 1) ≈ z_axis atol=1e-14
        θ1 = rotation_angle(unaligned \ aligned)
        θ2 = rotation_angle(rotation_between(unaligned * SVector(0, 0, 1), aligned * SVector(0, 0, 1)))
        @test θ1 ≈ θ2 atol=1e-14
    end
end

@testset "closest_pose" begin
    rng = MersenneTwister(2)
    for i = 1 : 100
        previous = AffineMap(rand(rng, Quat), rand(rng, SVector{3}))
        z_axis = normalize(rand(SVector{3}))
        origin = rand(rng, SVector{3})
        next = closest_pose(previous, origin, z_axis)
        @test next.translation === origin
        @test next.linear * SVector(0, 0, 1) ≈ z_axis atol=1e-14
    end
end

end


text:
# include("../../util/src/util_module.jl")
include("../../../../std/util/src/util_module.jl")

# dependencies:
# - util

module distributions
using LinearAlgebra
using ..util

include("stat_general.jl")
include("histogram.jl")
include("distr_types.jl")
include("pdf.jl")
include("sampling.jl")

end # distr

max_stars_repo_name: HomoModelicus/julia

max_issues_repo_name: HomoModelicus/julia

max_forks_repo_name: HomoModelicus/julia


text:
using SphericalFourierBesselDecompositions
SFB = SphericalFourierBesselDecompositions

using Test

@testset "top-level" begin
    rmin = 500.0
    rmax = 1000.0
    kmax = 0.02
    amodes = SFB.AnlmModes(kmax, rmin, rmax)
    cmodes = SFB.ClnnModes(amodes, Δnmax=0)
    pixwin = SFB.pixwin(cmodes)
end

# vim: set sw=4 et sts=4 :