text:
module SimPN
__precompile__(false)
using DifferentialEquations

function spring_mass(;k=10.0, m=1.0, tspan=(0.0, 5.0), x0=2.0, v0=0.0)
    function mdl!(du, u, p, t)
        x, v = u # position, velocity = dependent variables
        k, m = p # spring constant, mass = parameters
        du[1] = dx = v
        du[2] = dv = -(k/m)*x
    end
    prob = ODEProblem(mdl!, [x0, v0], tspan, [k, m])
    return solve(prob, Tsit5(), reltol=1e-8, abstol=1e-8)
end

function int_fire_neuron_01(;tspan=(0.0, 1.0), τ=0.025)
    function mdl(u, p, t)
        τ, v∞ = p
        (1/τ)*(v∞ - u)
    end
    prob = ODEProblem(mdl, -70.0, tspan, [τ, -40.0])
    return solve(prob, Tsit5(), reltol=1e-8, abstol=1e-8)
end

# reset the membrane potential when it crosses a threshold
function int_fire_neuron_02(;tspan=(0.0, 1.0), τ=0.025, v_rest=-70.0, v_th=-45.0, v∞ = -40.0)
    n_spike = 0
    function mdl(u, p, t)
        (1/τ)*(v∞ - u)
    end
    function cond(u, t, integrator)
        u - v_th # do something when u - v_th = 0
    end
    function affect!(integrator)
        n_spike += 1
        integrator.u = v_rest
    end
    cb = ContinuousCallback(cond, affect!)
    prob = ODEProblem(mdl, v_rest, tspan)
    sol = solve(prob, Tsit5(), reltol=1e-8, abstol=1e-8, callback=cb)
    println(n_spike)
    return sol
end

# add a second condition - reduce the time constant when neuron crosses reset
function int_fire_neuron_03(;tspan=(0.0, 1.0), τ=0.025, v_rest=-70.0, v_th=-45.0, v∞=-40.0, v_reset=-80.0)
    n_spike = 0
    spike_times = Float64[]
    function mdl(u, p, t)
        (1/τ)*(v∞ - u)
    end
    function cond(out, u, t, integrator)
        out[1] = u - v_th # membrane voltage u crossed threshold
        out[2] = u - v_rest #
    end
    function affect!(integrator, idx)
        if idx == 1 # neuron fired!
            n_spike += 1
            push!(spike_times, integrator.t)
            integrator.u = v_reset
        elseif idx == 2 # neuron crossed resting (from reset)
            τ = τ*1.3
        end
    end
    cb = VectorContinuousCallback(cond, affect!, 2)
    prob = ODEProblem(mdl, v_rest, tspan)
    sol = solve(prob, Tsit5(), reltol=1e-8, abstol=1e-8, callback=cb)
    println(n_spike)
    println(spike_times)
    return sol
end

# stepping using the integrator intrerface
function int_fire_neuron_04(;tspan=(0.0, 1.0), τ=0.025, v_rest=-70.0, v_th=-45.0, v∞ = -40.0)
    n_spike = 0
    function mdl(u, p, t)
        (1/τ)*(v∞ - u)
    end
    function cond(u, t, integrator)
        u - v_th # do something when u - v_th = 0
    end
    function affect!(integrator)
        n_spike += 1
        integrator.u = v_rest
    end
    cb = ContinuousCallback(cond, affect!, nothing)
    prob = ODEProblem(mdl, v_rest, tspan)
    integrator = init(prob, Tsit5(), reltol=1e-8, abstol=1e-8, callback=cb)
    return integrator # use step!(integrator) in the calling function to
end

# step through the integrator
function use_integrator(;dt=0.001)
    n1 = int_fire_neuron_04()
    t = Float64[]
    u = Float64[]
    push!(t, n1.t)
    push!(u, n1.u)
    while n1.t <= 1.0
        step!(n1, dt, true)
        push!(t, n1.t)
        push!(u, n1.u)
    end
    return t, u
end

function elastic_mass_01()
    g = 9.81 # m/s2 acceleration due to gravity
    m = 0.6 # kg mass of the ball (talus)
    k = 800 # kg/s2 spring constant (pantar fascia)
    β1 = 0.1 # m length from talus to calcaneus contacting the ground
    β = 0.03 # m length from talus to the pantar fascia insertion
    θo = π/3 # radians angle between plantar fascia and talus to back of foot line
    function mdl!(du, u, p, t)
        ys, yv = u # y position, y velocity
        du[1] = dys = yv # dys is the derivative of y position
        du[2] = dyv = (2.0/m)*tantheta(ys)*F_muscle(ys) - g
    end
    function tantheta(ys)
        if ys >= β1 || ys <= 0.0
            return 0.0
        else
            return ((ys/β1)/sqrt(1-(ys/β1)^2))
        end
    end
    function F_muscle(ys)
        if ys >= β1*sin(θo)
            return 0.0 # plantar fascia is slack
        else
            θ = asin(ys/β1)
            return 2*β*k*(cos(θ) - cos(θo)) # Hooke's law
        end
    end
    ys0 = β1*sin(θo)
    yv0 = 0
    tspan = (0.0, 0.5)
    prob = ODEProblem(mdl!, [ys0, yv0], tspan)
    sol = solve(prob, Tsit5(), reltol=1e-8, abstol=1e-8)
    ys_vec = ys_vec = [x[1] for x in sol.u]
    theta = atan.(tantheta.(ys_vec))*180.0/π
    fm = F_muscle.(ys_vec)
    return sol, theta, fm
end

Fmax = 3; b = 2; c = 2; d = 2;
passive_force(t) = Fmax/(1+exp(b-c*(t-d)));
plot(gc, 0:0.1:5.0)
end # module

max_stars_repo_name: praneethnamburi/blender-ScriptViz

max_issues_repo_name: praneethnamburi/blender-ScriptViz

max_forks_repo_name: praneethnamburi/blender-ScriptViz


text:
# @author b33rNc0d3
# @date 2020-06-10
# Using Jags.jl to test an intro model

projDir = dirname(@__FILE__)
cd(projDir)

model_str = "model
    for (i in 1:n) {
        y[i] ~ dnorm(mu, 1.0/sig2)
        }
    mu ~ dt(0.0, 1.0/1.0, 1.0)
    sig2 = 1.0
    }"

monitors = Dict(
    "mu" => true
)

jagsmodel = Jagsmodel(
                        name = "model test",
                        model = model_str,
                        monitor = monitors,
                        #ncommands=1, nchains=4,
                        #deviance=true, dic=true, popt=true,
                        pdir=projDir
                    );

data = Dict(
            "y" => [1.2, 1.4, -0.5, 0.3, 0.9, 2.3, 1.0, 0.1, 1.3, 1.0]
            )

inits = [
    Dict("mu" => 0.0)
]

sim = jags(jagsmodel, data, inits, projDir)

ext: jl


text:
"extracts the type-param name from split_def(...)[:wherevars]"
wherevar(v::Symbol) = v
wherevar(expr::Expr) = expr.args[1]

function qualify_calls!(ast, mod)
    MacroTools.postwalk(ast) do expr
        if isexpr(expr, :call) || isexpr(expr, :macrocall)
            expr.args[1] = qualify_name(mod, expr.args[1])
        end
        expr
    end
end
#TODO: Don't qualify IR.
qualify_name(mod::Module, name) = qualify_name(nameof(mod), name)
qualify_name(mod::Symbol, name::Symbol) = Expr(:., mod, QuoteNode(name))
qualify_name(mod, name) = name ## fallback, don't mess with things

"""
    is_allowable_generated_body(body_ast)

Generated functions are not allowed to do a bunch of things,
in the body they generate.z

"""
is_allowable_generated_body(::Any)=true
function is_allowable_generated_body(body::Expr)
    if (
        body.head ∈ (:comprehension, :generator, :global, :->) ||
        isdef(body)
    )
        return false
    end
    return all(is_allowable_generated_body, body.args)
end


text:
using Metatheory
using Metatheory.EGraphs
using Metatheory.Library
using Metatheory.Util

using DataStructures
using Test

Metatheory.options[:verbose] = true

@metatheory_init

include("test_egraphs.jl")
include("test_ematch.jl")
include("test_ematch_assertions.jl")
include("test_analysis.jl")
include("test_dynamic_ematch.jl")
include("test_extraction.jl")
include("test_mu.jl")
include("test_while_interpreter.jl")
include("test_julog.jl")
include("test_boson.jl")
include("test_theories.jl")
include("test_reductions.jl")
include("test_while_superinterpreter.jl")
include("test_fibonacci.jl")
include("test_cat.jl")

# exported consistency test
for m ∈ [Metatheory, Metatheory.Util, Metatheory.EGraphs, Metatheory.EGraphs.Schedulers]
   for i ∈ propertynames(m)
      x = getproperty(m, i)
   end
end


text:
@cache mutable struct ABDF2ConstantCache{F,N,dtType,rate_prototype} <: OrdinaryDiffEqConstantCache
  uf::F
  nlsolve::N
  eulercache::ImplicitEulerConstantCache
  dtₙ₋₁::dtType
  fsalfirstprev::rate_prototype
end

function alg_cache(alg::ABDF2,u,rate_prototype,uEltypeNoUnits,uBottomEltypeNoUnits,tTypeNoUnits,
                   uprev,uprev2,f,t,dt,reltol,p,calck,::Type{Val{false}})
  @oopnlcachefields
  γ, c = 1//1, 1
  @oopnlsolve
  eulercache = ImplicitEulerConstantCache(uf,nlsolve)
  dtₙ₋₁ = one(dt)
  fsalfirstprev = rate_prototype
  nlsolve.cache.γ = 2//3
  nlsolve.cache.c = 1
  ABDF2ConstantCache(uf, nlsolve, eulercache, dtₙ₋₁, fsalfirstprev)
end

@cache mutable struct ABDF2Cache{uType,rateType,uNoUnitsType,JType,WType,UF,JC,N,F,dtType} <: OrdinaryDiffEqMutableCache
  uₙ::uType
  uₙ₋₁::uType
  uₙ₋₂::uType
  du1::rateType
  fsalfirst::rateType
  fsalfirstprev::rateType
  k::rateType
  z::uType
  zₙ₋₁::uType
  dz::uType
  b::uType
  tmp::uType
  atmp::uNoUnitsType
  J::JType
  W::WType
  uf::UF
  jac_config::JC
  linsolve::F
  nlsolve::N
  eulercache::ImplicitEulerCache
  dtₙ₋₁::dtType
end

function alg_cache(alg::ABDF2,u,rate_prototype,uEltypeNoUnits,uBottomEltypeNoUnits,
                   tTypeNoUnits,uprev,uprev2,f,t,dt,reltol,p,calck,::Type{Val{true}})
  @iipnlcachefields
  γ, c = 1//1, 1
  @iipnlsolve
  atmp = similar(u,uEltypeNoUnits)

  fsalfirstprev = similar(rate_prototype)
  eulercache = ImplicitEulerCache(u,uprev,uprev2,du1,fsalfirst,k,z,dz,b,tmp,atmp,J,W,uf,jac_config,linsolve,nlsolve)
  dtₙ₋₁ = one(dt)
  zₙ₋₁ = similar(u)
  nlsolve.cache.γ = 2//3
  nlsolve.cache.c = 1
  ABDF2Cache(u,uprev,uprev2,du1,fsalfirst,fsalfirstprev,k,z,zₙ₋₁,dz,b,tmp,atmp,J,
              W,uf,jac_config,linsolve,nlsolve,eulercache,dtₙ₋₁)
end

# SBDF

@cache mutable struct SBDFConstantCache{rateType,F,N,uType} <: OrdinaryDiffEqConstantCache
  cnt::Int
  k2::rateType
  uf::F
  nlsolve::N
  uprev2::uType
  uprev4::uType
  uprev3::uType
  k₁::rateType
  k₂::rateType
  k₃::rateType
  du₁::rateType
  du₂::rateType
end

@cache mutable struct SBDFCache{uType,rateType,uNoUnitsType,JType,WType,UF,JC,N,F} <: OrdinaryDiffEqMutableCache
  cnt::Int
  u::uType
  uprev::uType
  fsalfirst::rateType
  k::rateType
  du1::rateType
  z::uType
  dz::uType
  b::uType
  tmp::uType
  atmp::uNoUnitsType
  J::JType
  W::WType
  uf::UF
  jac_config::JC
  linsolve::F
  nlsolve::N
  uprev2::uType
  uprev3::uType
  uprev4::uType
  k₁::rateType
  k₂::rateType
  k₃::rateType
  du₁::rateType
  du₂::rateType
end

function alg_cache(alg::SBDF,u,rate_prototype,uEltypeNoUnits,uBottomEltypeNoUnits,tTypeNoUnits,uprev,uprev2,f,t,dt,reltol,p,calck,::Type{Val{false}})
  @oopnlcachefields
  k2 = rate_prototype
  uprev2 = u
  uprev3 = u
  uprev4 = u
  k₁ = rate_prototype
  k₂ = rate_prototype
  k₃ = rate_prototype
  du₁ = rate_prototype
  du₂ = rate_prototype

  γ, c = 1//1, 1
  @oopnlsolve
  SBDFConstantCache(1,k2,uf,nlsolve,uprev2,uprev3,uprev4,k₁,k₂,k₃,du₁,du₂)
end

function alg_cache(alg::SBDF,u,rate_prototype,uEltypeNoUnits,uBottomEltypeNoUnits,tTypeNoUnits,uprev,uprev2,f,t,dt,reltol,p,calck,::Type{Val{true}})
  @iipnlcachefields
  atmp = similar(u,uEltypeNoUnits)
  order = alg.order
  uprev2 = similar(u)
  uprev3 = order >= 3 ? similar(u) : uprev2
  uprev4 = order == 4 ? similar(u) : uprev2
  k₁ = similar(rate_prototype)
  k₂ = order >= 3 ? zero(rate_prototype) : k₁
  k₃ = order == 4 ? zero(rate_prototype) : k₁
  du₁ = zero(rate_prototype)
  du₂ = zero(rate_prototype)

  γ, c = 1//1, 1
  @iipnlsolve
  SBDFCache(1,u,uprev,fsalfirst,k,du1,z,dz,b,tmp,atmp,J,W,uf,jac_config,linsolve,nlsolve,uprev2,uprev3,uprev4,k₁,k₂,k₃,du₁,du₂)
end

# QNDF1

@cache mutable struct QNDF1ConstantCache{F,N,coefType,coefType1,dtType,uType} <: OrdinaryDiffEqConstantCache
  uf::F
  nlsolve::N
  D::coefType
  D2::coefType1
  R::coefType
  U::coefType
  uprev2::uType
  dtₙ₋₁::dtType
end

@cache mutable struct QNDF1Cache{uType,rateType,coefType,coefType1,coefType2,uNoUnitsType,JType,WType,UF,JC,N,F,dtType} <: OrdinaryDiffEqMutableCache
  uprev2::uType
  du1::rateType
  fsalfirst::rateType
  k::rateType
  z::uType
  dz::uType
  b::uType
  D::coefType1
  D2::coefType2
  R::coefType
  U::coefType
  tmp::uType
  atmp::uNoUnitsType
  utilde::uType
  J::JType
  W::WType
  uf::UF
  jac_config::JC
  linsolve::F
  nlsolve::N
  dtₙ₋₁::dtType
end

function alg_cache(alg::QNDF1,u,rate_prototype,uEltypeNoUnits,uBottomEltypeNoUnits,tTypeNoUnits,uprev,uprev2,f,t,dt,reltol,p,calck,::Type{Val{false}})
  @oopnlcachefields
  uprev2 = u
  dtₙ₋₁ = t

  D = fill(zero(typeof(u)), 1, 1)
  D2 = fill(zero(typeof(u)), 1, 2)
  R = fill(zero(typeof(t)), 1, 1)
  U = fill(zero(typeof(t)), 1, 1)

  U!(1,U)
  γ, c = zero(inv((1-alg.kappa))), 1
  @oopnlsolve

  QNDF1ConstantCache(uf,nlsolve,D,D2,R,U,uprev2,dtₙ₋₁)
end

function alg_cache(alg::QNDF1,u,rate_prototype,uEltypeNoUnits,uBottomEltypeNoUnits,tTypeNoUnits,uprev,uprev2,f,t,dt,reltol,p,calck,::Type{Val{true}})
  @iipnlcachefields
  D = Array{typeof(u)}(undef, 1, 1)
  D2 = Array{typeof(u)}(undef, 1, 2)
  R = fill(zero(typeof(t)), 1, 1)
  U = fill(zero(typeof(t)), 1, 1)

  D[1] = similar(u)
  D2[1] = similar(u); D2[2] = similar(u)

  U!(1,U)

  atmp = similar(u,uEltypeNoUnits)
  utilde = similar(u)
  uprev2 = similar(u)
  dtₙ₋₁ = one(dt)
  γ, c = zero(inv((1-alg.kappa))), 1
  @iipnlsolve

  QNDF1Cache(uprev2,du1,fsalfirst,k,z,dz,b,D,D2,R,U,tmp,atmp,utilde,J,
              W,uf,jac_config,linsolve,nlsolve,dtₙ₋₁)
end

# QNDF2

@cache mutable struct QNDF2ConstantCache{F,N,coefType,coefType1,uType,dtType} <: OrdinaryDiffEqConstantCache
  uf::F
  nlsolve::N
  D::coefType
  D2::coefType
  R::coefType1
  U::coefType1
  uprev2::uType
  uprev3::uType
  dtₙ₋₁::dtType
  dtₙ₋₂::dtType
end

@cache mutable struct QNDF2Cache{uType,rateType,coefType,coefType1,coefType2,uNoUnitsType,JType,WType,UF,JC,N,F,dtType} <: OrdinaryDiffEqMutableCache
  uprev2::uType
  uprev3::uType
  du1::rateType
  fsalfirst::rateType
  k::rateType
  z::uType
  dz::uType
  b::uType
  D::coefType1
  D2::coefType2
  R::coefType
  U::coefType
  tmp::uType
  atmp::uNoUnitsType
  utilde::uType
  J::JType
  W::WType
  uf::UF
  jac_config::JC
  linsolve::F
  nlsolve::N
  dtₙ₋₁::dtType
  dtₙ₋₂::dtType
end

function alg_cache(alg::QNDF2,u,rate_prototype,uEltypeNoUnits,uBottomEltypeNoUnits,tTypeNoUnits,uprev,uprev2,f,t,dt,reltol,p,calck,::Type{Val{false}})
  @oopnlcachefields
  uprev2 = u
  uprev3 = u
  dtₙ₋₁ = zero(t)
  dtₙ₋₂ = zero(t)

  D = fill(zero(typeof(u)), 1, 2)
  D2 = fill(zero(typeof(u)), 1, 3)
  R = fill(zero(typeof(t)), 2, 2)
  U = fill(zero(typeof(t)), 2, 2)

  U!(2,U)

  γ, c = zero(inv((1-alg.kappa))), 1
  @oopnlsolve
  QNDF2ConstantCache(uf,nlsolve,D,D2,R,U,uprev2,uprev3,dtₙ₋₁,dtₙ₋₂)
end

function alg_cache(alg::QNDF2,u,rate_prototype,uEltypeNoUnits,uBottomEltypeNoUnits,tTypeNoUnits,uprev,uprev2,f,t,dt,reltol,p,calck,::Type{Val{true}})
  @iipnlcachefields
  D = Array{typeof(u)}(undef, 1, 2)
  D2 = Array{typeof(u)}(undef, 1, 3)
  R = fill(zero(typeof(t)), 2, 2)
  U = fill(zero(typeof(t)), 2, 2)

  D[1] = similar(u); D[2] = similar(u)
  D2[1] = similar(u);  D2[2] = similar(u); D2[3] = similar(u)

  U!(2,U)

  atmp = similar(u,uEltypeNoUnits)
  utilde = similar(u)
  uprev2 = similar(u)
  uprev3 = similar(u)
  dtₙ₋₁ = zero(dt)
  dtₙ₋₂ = zero(dt)

  γ, c = zero(inv((1-alg.kappa))), 1
  @iipnlsolve
  QNDF2Cache(uprev2,uprev3,du1,fsalfirst,k,z,dz,b,D,D2,R,U,tmp,atmp,utilde,J,
             W,uf,jac_config,linsolve,nlsolve,dtₙ₋₁,dtₙ₋₂)
end

@cache mutable struct QNDFConstantCache{F,N,coefType1,coefType2,coefType3,uType,dtType,dtsType} <: OrdinaryDiffEqConstantCache
  uf::F
  nlsolve::N
  D::coefType3
  D2::coefType2
  R::coefType1
  U::coefType1
  order::Int64
  max_order::Int64
  udiff::uType
  dts::dtsType
  tmp::uType
  h::dtType
  c::Int64
end

@cache mutable struct QNDFCache{uType,rateType,coefType1,coefType,coefType2,coefType3,dtType,dtsType,uNoUnitsType,JType,WType,UF,JC,N,F} <: OrdinaryDiffEqMutableCache
  du1::rateType
  fsalfirst::rateType
  k::rateType
  z::uType
  dz::uType
  b::uType
  D::coefType3
  D2::coefType2
  R::coefType1
  U::coefType1
  order::Int64
  max_order::Int64
  udiff::coefType
  dts::dtsType
  tmp::uType
  atmp::uNoUnitsType
  utilde::uType
  J::JType
  W::WType
  uf::UF
  jac_config::JC
  linsolve::F
  nlsolve::N
  h::dtType
  c::Int64
end

function alg_cache(alg::QNDF,u,rate_prototype,uEltypeNoUnits,uBottomEltypeNoUnits,tTypeNoUnits,uprev,uprev2,f,t,dt,reltol,p,calck,::Type{Val{false}})
  @oopnlcachefields
  udiff = fill(zero(typeof(u)), 1, 6)
  dts = fill(zero(typeof(dt)), 1, 6)
  h = zero(dt)
  tmp = zero(u)

  D = fill(zero(typeof(u)), 1, 5)
  D2 = fill(zero(typeof(u)), 6, 6)
  R = fill(zero(typeof(t)), 5, 5)
  U = fill(zero(typeof(t)), 5, 5)

  max_order = 5

  γ, c = zero(inv((alg.kappa))), 1
  @oopnlsolve
  QNDFConstantCache(uf,nlsolve,D,D2,R,U,1,max_order,udiff,dts,tmp,h,0)
end

function alg_cache(alg::QNDF,u,rate_prototype,uEltypeNoUnits,uBottomEltypeNoUnits,tTypeNoUnits,uprev,uprev2,f,t,dt,reltol,p,calck,::Type{Val{true}})
  @iipnlcachefields
  udiff = Array{typeof(u)}(undef, 1, 6)
  dts = fill(zero(typeof(dt)), 1, 6)
  h = zero(dt)

  D = Array{typeof(u)}(undef, 1, 5)
  D2 = Array{typeof(u)}(undef, 6, 6)
  R = fill(zero(typeof(t)), 5, 5)
  U = fill(zero(typeof(t)), 5, 5)

  for i = 1:5
    D[i] = zero(u)
    udiff[i] = zero(u)
  end
  udiff[6] = zero(u)

  for i = 1:6
    for j = 1:6
      D2[i,j] = zero(u)
    end
  end

  max_order = 5
  atmp = similar(u,uEltypeNoUnits)
  utilde = similar(u)
  γ, c = zero(inv((alg.kappa))), 1
  @iipnlsolve

  QNDFCache(du1,fsalfirst,k,z,dz,b,D,D2,R,U,1,max_order,udiff,dts,tmp,atmp,utilde,J,
            W,uf,jac_config,linsolve,nlsolve,h,0)
end


text:
using BondiToy
using Parameters
using Random

@with_kw struct WH_noise_B2 <: NestedIBVP
    noise_amplitude :: Float64
    # the element of the angular principal matrix Az that controls the
    # hyperbolicity of the toy model.
    az_21 :: Int # 0 for SH; 1 for WH
    # the elements of the matrix B that encodes the sourc terms S,
    # with S = B*state_vector
    b11 :: Int
    b13 :: Int
    b21 :: Int
    b22 :: Int
    b23 :: Int
    b31 :: Int
    b32 :: Int
    b33 :: Int
end

BondiToy.ϕ0_of_uz(u::T, z::T, ibvp::WH_noise_B2) where {T<:Real} =
    ibvp.noise_amplitude * randn(T)

BondiToy.ψv0_of_uz(u::T, z::T, ibvp::WH_noise_B2) where {T<:Real} =
    ibvp.noise_amplitude * randn(T)

BondiToy.ψ0_of_Xz(X::T, z::T, ibvp::WH_noise_B2) where {T<:Real} =
    ibvp.noise_amplitude * randn(T)

toy_model = "WH_noise_B2_norms"
root_dir="./run00"

D = 4
noise_amplitude_drop = 0.25

NX = (17-1)*2^D + 1 #17 coarse
Nz = 16*2^D #16 coarse

# parameters to be passed in the toy model
p = Param(
    NX = NX,
    Nz = Nz,
    cX = 10.0,
    rmin = 2.0,
    umax = 1.0, # total time of the simulation in code units

    # uncomment the appropriate SCALING AMPLITUDE for noisy given data
    # for L2 norm
    # for the LOPSIDED norm
    #noise_amplitude_drop = 0.125,

    out_dir = joinpath(root_dir, toy_model*"_"*string(noise_amplitude_drop),
                       "data_$(NX)_$(Nz)"),

    out_every = 4*16*2^D,
)

ibvp = WH_noise_B2(
    noise_amplitude = noise_amplitude_drop^D,
    az_21 = 1, # 0 for SH; 1 for WH
    b11 = 1,
    b13 = 1,
    b21 = 1,
    b22 = 1,
    b23 = 1,
    b31 = 1,
    b32 = 1,
    b33 = 1,
)

run_toy(p, ibvp)

max_stars_repo_name: ThanasisGiannakopoulos/BondiToy

max_issues_repo_name: ThanasisGiannakopoulos/BondiToy

max_forks_repo_name: ThanasisGiannakopoulos/BondiToy


text:
### Functions to Visualize Pose Graphs and Errors ###
### Ted Steiner ###
### September 2014 ###

###################
### Error Plots ###
###################

function plotCovError( cov_trace, y_max=1000 )
    x = [1:length(cov_trace)]

    fignum = Winston.figure()
    p = Winston.plot(x,cov_trace)
    Winston.ylim(0,y_max)
    display(p)
    return fignum
end

function plotCovError( full_cov_trace, filter_cov_trace, y_max=1000 )
    x1 = [1:length(full_cov_trace)]
    x2 = [1:length(filter_cov_trace)]

    fignum = Winston.figure()
    p = Winston.plot(x1,full_cov_trace,"b-",x2,filter_cov_trace,"r-")
    Winston.ylim(0,y_max)
    display(p)
    return fignum
end

function plotEpsilons( epsilons::Array{Array{Real,1},1}, show_points::Bool=false )
    c = ["-b","-g","-r","-c","-m","-y"]

    for k = 1:ceil(length(epsilons)/length(c))
        push!(c,c...)
    end

    fignum = Winston.figure()
    p = Winston.plot()

    for k = 1:length(epsilons)
        if k == length(epsilons)
            col = "-k"
        else
            col = c[k]
        end

        if show_points
            col *= "o"
        end

        Winston.oplot([1:length(epsilons[k])],epsilons[k],col)
    end

    display(p)
    return fignum
end

##########################
### Pose-Graph Display ###
##########################

function plotPoseGraph( poses::Array{Pose2D,1};
                        poses_truth::Array{Pose2D,1}=Pose2D[],
                        vertices=false,
                        legend=false,
                        width=500,
                        height=0,
                        km=false,
                        nodes::Dict=Dict(),
                        anchors::Vector{Int}=Int[] )
    # Parameters
    g_lw = 2
    v_size = 0.25
    fig_name = "Pose Graph Display"
    g_color = "blue"
    v_color = "black"
    x_lab = "x (m)"
    y_lab = "y (m)"
    fontsize = 4

    if length(poses_truth) > 6
        print("Aligning poses... ")
        alignPoses!(poses_truth,poses)
        println("done.")
    end
    coords = poses2cart(poses)

    if km
        coords /= 1000.0
        x_lab = "x (km)"
        y_lab = "y (km)"
    end

    if height <= 0
        height = width
    end
    fignum = Winston.figure(name=fig_name,height=height,width=width)
    p = Winston.FramedPlot("xlabel",x_lab,"ylabel",y_lab)

    g = Winston.Curve(coords[:,1],coords[:,2],color=g_color,"linewidth",g_lw)
    Winston.setattr(g,"label","Posegraph")
    Winston.add(p,g)

    if vertices
        v = Winston.Points(coords[:,1],coords[:,2],color=v_color,kind="circle",size=v_size)
        Winston.setattr(v,"label","Poses")
        Winston.add(p,v)
    end

    if length(anchors) > 0
        coords_a = zeros(length(anchors),2)
        for k = 1:length(anchors)
            coords_a[k,1] = nodes[anchors[k]].east
            coords_a[k,2] = nodes[anchors[k]].north
        end
        if km
            coords_a /= 1000.0
        end
        a =
        Winston.Points(coords_a[:,1],coords_a[:,2],color="red",kind="circle",size=.75)
        Winston.setattr(a,"label","Database Locations")
        Winston.add(p,a)
    end

    Winston.setattr(p.x1,"label_style",[:fontsize=>fontsize])
    Winston.setattr(p.y1,"label_style",[:fontsize=>fontsize])
    Winston.setattr(p.x1,"ticklabels_style",[:fontsize=>fontsize])
    Winston.setattr(p.y1,"ticklabels_style",[:fontsize=>fontsize])

    if legend
        if length(anchors) > 0
            if vertices
                lgnd = Winston.Legend(0.65,0.9,{g,v,a})
            else
                lgnd = Winston.Legend(0.65,0.9,{g,a})
            end
        elseif vertices
            lgnd = Winston.Legend(0.65,0.9,{g,v})
        else
            lgnd = Winston.Legend(0.65,0.9,{g})
        end
        Winston.add(p,lgnd)
    end

    Winston.display(p)
    return p
end

function poses2cart( poses::Array{Pose2D,1} )
    coords = zeros(length(poses),2)

    for k = 1:length(poses)
        coords[k,1] = poses[k].x
        coords[k,2] = poses[k].y
    end

    return coords
end

function plotPoseGraph( results::String; truth::String="", width=500, height=0, legend=false, vertices=false )
    poses_results = readiSAMOutput(results)

    if truth != ""
        isam_truth = readiSAMTruth(truth)
        poses_truth = isam_truth["poses"]
    else
        poses_truth = nothing
    end

    return plotPoseGraph(poses_results,poses_truth=poses_truth,width=width,height=height,vertices=vertices,legend=legend)
end

function plotPoseGraphTruth( truth::String; width=500, height=0 )
    isam_truth = readiSAMTruth(truth)
    poses_truth = isam_truth["poses"]
    return plotPoseGraph(poses_truth,width=width,height=height)
end


text:
using Poker
using Test

@testset "Poker.jl" begin
    # Write your tests here.
end


text:
mutable struct Box <: Shape
    position::Tuple{Luxor.Point,Luxor.Point}
    color::Union{Blending,Coloring}
    style::Union{Symbol, Vector{Float64}}
end

function Box( ; position, color, style=:fill, kwargs...)
    return Box(position, color, style)
end


text:
using Distributions, MCMC

mcmodel = model(Normal(), init=1.)

mcchain = run(mcmodel, HMC(1.25), SerialMC(steps=10000, burnin=1000))

acceptance(mcchain)

describe(mcchain)


text:
#
# This file is part of the DiscreteEvents.jl Julia package, MIT license
#
# Paul Bayer, 2019
#
# This is a Julia package for discrete event simulation
#
using DiscreteEvents, .Threads

sleeptime = 0.01
println("... testing real time clock ...")

rtc = createRTClock(0.01, 4711)
stopRTClock(rtc)
rtc.time = 4711.0
thrd = nthreads()
str = "RTClock 4711 on thread $thrd: state=:idle, t=4711.0 s, T=0.01 s, prc:0\n   scheduled ev:0, cev:0, sampl:0\n"
@test repr(rtc) == str

rtc = createRTClock(0.01, 4711)
sleep(1.01)
@test tau(rtc) ≥ 1
t = tau(rtc)
resetClock!(rtc)
sleep(sleeptime)
@test tau(rtc) < t

put!(rtc.cmd, DiscreteEvents.Clear())
sleep(sleeptime)
put!(rtc.cmd, DiscreteEvents.Diag())
err = take!(rtc.back).x
@test err[1] isa ErrorException

a = [0]
b = [0]
incr!(x) = x[1] += 1
event!(rtc, fun(incr!, a), every, 0.1)
periodic!(rtc, fun(incr!, b))
sleep(1)
@test a[1] ≥ 10
@test b[1] ≥ 100

old = DiscreteEvents._handle_exceptions[end]
DiscreteEvents._handle_exceptions[end] = false
sleep(1)
@test a[1] ≥ 20
@test b[1] ≥ 200
DiscreteEvents._handle_exceptions[end] = old

stopRTClock(rtc)
t = tau(rtc)
sleep(0.1)
@test t == tau(rtc)


text:
# Tests for align.jl

@testset "Align" begin
    coords_one = [
        1.0 0.0 0.0;
        0.0 1.0 0.0;
        0.0 0.0 0.0;
    ]
    coords_two = [
        0.0 -1.0 0.0;
        1.0 0.0 0.0;
        1.0 1.0 1.0;
    ]
    trans_one_test, trans_two_test, rotation_test = kabschalignment(coords_one, coords_two)
    trans_one_real = [1/3, 1/3, 0]
    trans_two_real = [-1/3, 1/3, 1]
    rotation_real = [
        0.0 -1.0 0.0;
        1.0 0.0 0.0;
        0.0 0.0 1.0;
    ]
    @test isapprox(trans_one_test, trans_one_real)
    @test isapprox(trans_two_test, trans_two_real)
    @test isapprox(rotation_test, rotation_real)

    coords_one = [
        1.0 0.0 0.0;
        0.0 1.0 0.0;
        0.0 0.0 0.0;
    ]
    coords_two = [
        0.0 -1.0 0.0;
        1.0 0.0 0.0;
        1.0 1.0 1.0;
    ]
    devs_test = displacements(coords_one, coords_two)
    devs_real = [sqrt(3), sqrt(3), 1.0]
    @test isapprox(devs_test, devs_real)

    atom_one = Atom("CA", "ALA", 'A', 20, [0.0, 0.0, 0.0], "C")
    atom_two = Atom("C", "ALA", 'A', 20, [0.0, 0.0, 0.0], "C")
    atom_thr = Atom("CA", "ALA", 'A', 21, [0.0, 0.0, 0.0], "C")
    atoms = [atom_one, atom_two, atom_thr]
    coords_one = [
        0.0 1.0 2.0;
        0.0 1.0 0.0;
        0.0 0.0 0.0;
    ]
    coords_two = [
        0.0 -1.0 0.0;
        0.0 0.0 3.0;
        3.0 3.0 3.0;
    ]
    align!(coords_one, coords_two, atoms)
    coords_one_real = [
        0.0 0.5 3.0;
        -1.0 1.5 3.0;
        0.0 2.5 3.0;
    ]
    coords_one_real = [
        0.0 -1.0 0.0;
        0.5 1.5 2.5;
        3.0 3.0 3.0;
    ]
    @test coords_one == coords_one_real

    atom_one = Atom("CA", "ALA", 'A', 20, [0.0, 0.0, 0.0], "C")
    atom_two = Atom("C", "ALA", 'A', 20, [0.0, 0.0, 0.0], "C")
    atom_thr = Atom("CA", "ALA", 'A', 21, [0.0, 0.0, 0.0], "C")
    atoms = [atom_one, atom_two, atom_thr]
    coords_one = [
        0.0 1.0 2.0;
        0.0 1.0 0.0;
        0.0 0.0 0.0;
    ]
    coords_two = [
        0.0 -1.0 0.0;
        0.0 0.0 3.0;
        3.0 3.0 3.0;
    ]
    alignsimple!(coords_one, coords_two, atoms)
    coords_one_real = [
        0.0 -1.0 0.0;
        0.5 1.5 2.5;
        3.0 3.0 3.0;
    ]
    @test coords_one == coords_one_real

    atom_one = Atom("CA", "ALA", 'A', 20, [0.0, 0.0, 0.0], "C")
    atom_two = Atom("C", "ALA", 'A', 20, [1.0, 1.0, 0.0], "C")
    atom_thr = Atom("CA", "ALA", 'A', 21, [2.0, 0.0, 0.0], "C")
    atoms = [atom_one, atom_two, atom_thr]
    atoms_new = deepcopy(atoms)
    coords_ref = [
        0.0 -1.0 0.0;
        0.0 0.0 3.0;
        3.0 3.0 3.0;
    ]
    alignatoms!(atoms, coords_ref)
    coords_real = [
        0.0 -1.0 0.0;
        0.5 1.5 2.5;
        3.0 3.0 3.0;
    ]
    @test atomcoords(atoms) == coords_real
    atoms_ref = atomcoords(atoms, coords_ref)
    alignatoms!(atoms_new, atoms_ref)
    @test atomcoords(atoms_new) == coords_real

    atom_one = Atom("CA", "ALA", 'A', 20, [0.0, 0.0, 0.0], "C")
    atom_two = Atom("CA", "ALA", 'A', 30, [0.0, 0.0, 0.0], "C")
    struc_one = ModelledStructure(0.0, [0.0 5.0; 0.0 5.0; 0.0 5.0])
    struc_two = ModelledStructure(0.0, [1.0 4.0; 1.0 4.0; 1.0 4.0])
    ensemble = ModelledEnsemble([atom_one, atom_two], [struc_one, struc_two])
    average_test = centroid(ensemble)
    average_real = [0.5 4.5; 0.5 4.5; 0.5 4.5]
    @test average_test == average_real

    coords_one = [
        0.0 3.0 13.0;
        0.0 0.0 0.0;
        0.0 0.0 0.0;
    ]
    coords_two = [
        0.0 5.0 10.0;
        1.0 0.0 0.0;
        0.0 0.0 0.0;
    ]
    atom_one = Atom("CA", "ALA", 'A', 20, [0.0, 0.0, 0.0], "C")
    atom_two = Atom("CA", "ALA", 'A', 30, [0.0, 0.0, 0.0], "C")
    atom_thr = Atom("C", "ALA", 'A', 40, [0.0, 0.0, 0.0], "C")
    atoms = [atom_one, atom_two, atom_thr]
    @test isapprox(rmsd(coords_one, coords_two, atoms), sqrt(2.5))

    coords_one = [
        0.0 3.0;
        0.0 0.0;
        0.0 0.0;
    ]
    coords_two = [
        0.0 5.0;
        1.0 0.0;
        0.0 0.0;
    ]
    @test isapprox(rmsd(coords_one, coords_two), sqrt(2.5))
end


text:
module Revealables

using Interact
using Reactive

export Revealable
export revealable
export encode!
export encode
export decode!
export decode

mutable struct Revealable
    markdown::String
    label::String
    show::Bool
    encoded::Bool
end

Revealable(markdown::String, label::String = "Show/Hide", show = false, encoded = false) = Revealable(markdown, label, show, encoded)

function revealable(markdown::String, label::String, show::Bool)
    x = Revealable(markdown, label, show)
    revealable(x)
end

function revealable(markdown::String, label::String = "Show/Hide")
    x = Revealable(markdown, label, false)
    revealable(x)
end

function revealable(x::Revealable)
    @manipulate for n in toggle(x.label; value=x.show)
        x.show = n
        x
    end
end

function rot(text::String, key::Int)
    map(text) do c
        if 'a' <= c <= 'z'
            Char(mod(c - 'a' + key, 26) + 'a')
        elseif 'A' <= c <= 'Z'
            Char(mod(c - 'A' + key, 26) + 'A')
        elseif '&' <= c <= '?'
            Char(mod(c - '&' + key, 26) + '&')
        else
            c
        end
    end
end

function encode!(x::Revealable, password::String)
    if x.encoded
        x
    else
        key = sum(map(x->convert(Int, x), collect(password)))
        x.markdown = rot(x.markdown, key)
        x.encoded = true
        x
    end
end

function encode(x::Revealable, password::String)
    r = Revealable(x.markdown, x.label, x.show)
    encode!(r, password)
end

function decode!(x::Revealable, password::String)
    if x.encoded
        key = 26 - sum(map(x->convert(Int, x), collect(password)))
        x.markdown = x.markdown = rot(x.markdown, key)
        x.encoded = false
        x
    else
        x
    end
end

function decode(x::Revealable, password::String)
    r = Revealable(x.markdown, x.label, x.show)
    decode!(r, password)
end

function Base.show(io::IO, ::MIME"text/markdown", x::Revealable)
    if x.show
        println(io, x.markdown)
    else
        println(io, "")
    end
end

end # module


text:
# This file was generated by the Julia Swagger Code Generator
# Do not modify this file directly. Modify the swagger specification instead.

mutable struct NetworkInterfaceIPConfigurationPropertiesFormat2 <: SwaggerModel
    virtualNetworkTaps::Any # spec type: Union{ Nothing, Vector{VirtualNetworkTap} } # spec name: virtualNetworkTaps
    applicationGatewayBackendAddressPools::Any # spec type: Union{ Nothing, Vector{ApplicationGatewayBackendAddressPool} } # spec name: applicationGatewayBackendAddressPools
    loadBalancerBackendAddressPools::Any # spec type: Union{ Nothing, Vector{BackendAddressPool} } # spec name: loadBalancerBackendAddressPools
    loadBalancerInboundNatRules::Any # spec type: Union{ Nothing, Vector{InboundNatRule} } # spec name: loadBalancerInboundNatRules
    privateIPAddress::Any # spec type: Union{ Nothing, String } # spec name: privateIPAddress
    privateIPAllocationMethod::Any # spec type: Union{ Nothing, IPAllocationMethod } # spec name: privateIPAllocationMethod
    privateIPAddressVersion::Any # spec type: Union{ Nothing, IPVersion } # spec name: privateIPAddressVersion
    subnet::Any # spec type: Union{ Nothing, Subnet } # spec name: subnet
    primary::Any # spec type: Union{ Nothing, Bool } # spec name: primary
    publicIPAddress::Any # spec type: Union{ Nothing, PublicIPAddress } # spec name: publicIPAddress
    applicationSecurityGroups::Any # spec type: Union{ Nothing, Vector{ApplicationSecurityGroup} } # spec name: applicationSecurityGroups
    provisioningState::Any # spec type: Union{ Nothing, ProvisioningState } # spec name: provisioningState
    privateLinkConnectionProperties::Any # spec type: Union{ Nothing, NetworkInterfaceIPConfigurationPrivateLinkConnectionProperties2 } # spec name: privateLinkConnectionProperties

    function NetworkInterfaceIPConfigurationPropertiesFormat2(;virtualNetworkTaps=nothing, applicationGatewayBackendAddressPools=nothing, loadBalancerBackendAddressPools=nothing, loadBalancerInboundNatRules=nothing, privateIPAddress=nothing, privateIPAllocationMethod=nothing, privateIPAddressVersion=nothing, subnet=nothing, primary=nothing, publicIPAddress=nothing, applicationSecurityGroups=nothing, provisioningState=nothing, privateLinkConnectionProperties=nothing)
        o = new()
        validate_property(NetworkInterfaceIPConfigurationPropertiesFormat2, Symbol("virtualNetworkTaps"), virtualNetworkTaps)
        setfield!(o, Symbol("virtualNetworkTaps"), virtualNetworkTaps)
        validate_property(NetworkInterfaceIPConfigurationPropertiesFormat2, Symbol("applicationGatewayBackendAddressPools"), applicationGatewayBackendAddressPools)
        setfield!(o, Symbol("applicationGatewayBackendAddressPools"), applicationGatewayBackendAddressPools)
        validate_property(NetworkInterfaceIPConfigurationPropertiesFormat2, Symbol("loadBalancerBackendAddressPools"), loadBalancerBackendAddressPools)
        setfield!(o, Symbol("loadBalancerBackendAddressPools"), loadBalancerBackendAddressPools)
        validate_property(NetworkInterfaceIPConfigurationPropertiesFormat2, Symbol("loadBalancerInboundNatRules"), loadBalancerInboundNatRules)
        setfield!(o, Symbol("loadBalancerInboundNatRules"), loadBalancerInboundNatRules)
        validate_property(NetworkInterfaceIPConfigurationPropertiesFormat2, Symbol("privateIPAddress"), privateIPAddress)
        setfield!(o, Symbol("privateIPAddress"), privateIPAddress)
        validate_property(NetworkInterfaceIPConfigurationPropertiesFormat2, Symbol("privateIPAllocationMethod"), privateIPAllocationMethod)
        setfield!(o, Symbol("privateIPAllocationMethod"), privateIPAllocationMethod)
        validate_property(NetworkInterfaceIPConfigurationPropertiesFormat2, Symbol("privateIPAddressVersion"), privateIPAddressVersion)
        setfield!(o, Symbol("privateIPAddressVersion"), privateIPAddressVersion)
        validate_property(NetworkInterfaceIPConfigurationPropertiesFormat2, Symbol("subnet"), subnet)
        setfield!(o, Symbol("subnet"), subnet)
        validate_property(NetworkInterfaceIPConfigurationPropertiesFormat2, Symbol("primary"), primary)
        setfield!(o, Symbol("primary"), primary)
        validate_property(NetworkInterfaceIPConfigurationPropertiesFormat2, Symbol("publicIPAddress"), publicIPAddress)
        setfield!(o, Symbol("publicIPAddress"), publicIPAddress)
        validate_property(NetworkInterfaceIPConfigurationPropertiesFormat2, Symbol("applicationSecurityGroups"), applicationSecurityGroups)
        setfield!(o, Symbol("applicationSecurityGroups"), applicationSecurityGroups)
        validate_property(NetworkInterfaceIPConfigurationPropertiesFormat2, Symbol("provisioningState"), provisioningState)
        setfield!(o, Symbol("provisioningState"), provisioningState)
        validate_property(NetworkInterfaceIPConfigurationPropertiesFormat2, Symbol("privateLinkConnectionProperties"), privateLinkConnectionProperties)
        setfield!(o, Symbol("privateLinkConnectionProperties"), privateLinkConnectionProperties)
        o
    end
end # type NetworkInterfaceIPConfigurationPropertiesFormat2

const _property_map_NetworkInterfaceIPConfigurationPropertiesFormat2 = Dict{Symbol,Symbol}(Symbol("virtualNetworkTaps")=>Symbol("virtualNetworkTaps"), Symbol("applicationGatewayBackendAddressPools")=>Symbol("applicationGatewayBackendAddressPools"), Symbol("loadBalancerBackendAddressPools")=>Symbol("loadBalancerBackendAddressPools"), Symbol("loadBalancerInboundNatRules")=>Symbol("loadBalancerInboundNatRules"), Symbol("privateIPAddress")=>Symbol("privateIPAddress"), Symbol("privateIPAllocationMethod")=>Symbol("privateIPAllocationMethod"), Symbol("privateIPAddressVersion")=>Symbol("privateIPAddressVersion"), Symbol("subnet")=>Symbol("subnet"), Symbol("primary")=>Symbol("primary"), Symbol("publicIPAddress")=>Symbol("publicIPAddress"), Symbol("applicationSecurityGroups")=>Symbol("applicationSecurityGroups"), Symbol("provisioningState")=>Symbol("provisioningState"), Symbol("privateLinkConnectionProperties")=>Symbol("privateLinkConnectionProperties"))
const _property_types_NetworkInterfaceIPConfigurationPropertiesFormat2 = Dict{Symbol,String}(Symbol("virtualNetworkTaps")=>"Vector{VirtualNetworkTap}", Symbol("applicationGatewayBackendAddressPools")=>"Vector{ApplicationGatewayBackendAddressPool}", Symbol("loadBalancerBackendAddressPools")=>"Vector{BackendAddressPool}", Symbol("loadBalancerInboundNatRules")=>"Vector{InboundNatRule}", Symbol("privateIPAddress")=>"String", Symbol("privateIPAllocationMethod")=>"IPAllocationMethod", Symbol("privateIPAddressVersion")=>"IPVersion", Symbol("subnet")=>"Subnet", Symbol("primary")=>"Bool", Symbol("publicIPAddress")=>"PublicIPAddress", Symbol("applicationSecurityGroups")=>"Vector{ApplicationSecurityGroup}", Symbol("provisioningState")=>"ProvisioningState", Symbol("privateLinkConnectionProperties")=>"NetworkInterfaceIPConfigurationPrivateLinkConnectionProperties2")
Base.propertynames(::Type{ NetworkInterfaceIPConfigurationPropertiesFormat2 }) = collect(keys(_property_map_NetworkInterfaceIPConfigurationPropertiesFormat2))
Swagger.property_type(::Type{ NetworkInterfaceIPConfigurationPropertiesFormat2 }, name::Symbol) = Union{Nothing,eval(Base.Meta.parse(_property_types_NetworkInterfaceIPConfigurationPropertiesFormat2[name]))}
Swagger.field_name(::Type{ NetworkInterfaceIPConfigurationPropertiesFormat2 }, property_name::Symbol) =  _property_map_NetworkInterfaceIPConfigurationPropertiesFormat2[property_name]

function check_required(o::NetworkInterfaceIPConfigurationPropertiesFormat2)
    true
end

function validate_property(::Type{ NetworkInterfaceIPConfigurationPropertiesFormat2 }, name::Symbol, val)
end


text:
# This file is part of the IntervalArithmetic.jl package; MIT licensed

using IntervalArithmetic
using Test

setprecision(Interval, Float64)

@testset "Consistency tests" begin

    a = @interval(0.1, 1.1)
    b = @interval(0.9, 2.0)
    c = @interval(0.25, 4.0)

    @testset "Interval types and constructors" begin

        @test isa( @interval(1,2), Interval )
        @test isa( @interval(0.1), Interval )
        @test isa( zero(b), Interval )

        @test zero(b) == 0.0
        @test zero(b) == zero(typeof(b))
        @test one(a) == 1.0
        @test one(a) == one(typeof(a))
        @test one(a) == big(1.0)
        @test !(a == b)
        @test a != b
        @test eps(typeof(a)) === eps(one(typeof(a)))
        @test typemin(typeof(a)) === Interval(-Inf, nextfloat(-Inf))
        @test typemax(typeof(a)) === Interval(prevfloat(Inf), Inf)
        @test typemin(a) === typemin(typeof(a))
        @test typemax(a) === typemax(typeof(a))
        @test typemin(Interval{Int64}) === Interval(typemin(Int64))
        @test typemax(Interval{Int64}) === Interval(typemax(Int64))

        @test a == Interval(a.lo, a.hi)
        @test @interval(1, Inf) == Interval(1.0, Inf)
        @test @interval(-Inf, 1) == Interval(-Inf, 1.0)
        @test @biginterval(1, Inf) == Interval{BigFloat}(1.0, Inf)
        @test @biginterval(-Inf, 1) == Interval{BigFloat}(-Inf, 1.0)
        @test @interval(-Inf, Inf) == entireinterval(Float64)
        @test entireinterval(Int) == entireinterval(Float64)
        @test emptyinterval(Rational{Int}) == ∅
        @test emptyinterval(Int) == ∅

        @test 1 == zero(a)+one(b)
        @test Interval(0,1) + emptyinterval(a) == emptyinterval(a)
        @test @interval(0.25) - one(c)/4 == zero(c)
        @test emptyinterval(a) - Interval(0,1) == emptyinterval(a)
        @test Interval(0,1) - emptyinterval(a) == emptyinterval(a)
        @test a*b == Interval(a.lo*b.lo, a.hi*b.hi)
        @test Interval(0,1) * emptyinterval(a) == emptyinterval(a)
        @test a * Interval(0) == zero(a)
    end

    @testset "inv" begin

        @test inv( zero(a) ) == emptyinterval()
        @test inv( @interval(0, 1) ) == Interval(1, Inf)
        @test inv( @interval(1, Inf) ) == Interval(0, 1)
        @test inv(c) == c
        @test one(b)/b == inv(b)
        @test a/emptyinterval(a) == emptyinterval(a)
        @test emptyinterval(a)/a == emptyinterval(a)
        @test inv(@interval(-4.0,0.0)) == @interval(-Inf, -0.25)
        @test inv(@interval(0.0,4.0)) == @interval(0.25, Inf)
        @test inv(@interval(-4.0,4.0)) == entireinterval(Float64)
        @test @interval(0)/@interval(0) == emptyinterval()
        @test typeof(emptyinterval()) == Interval{Float64}
    end

    @testset "fma consistency" begin
        @test fma(emptyinterval(), a, b) == emptyinterval()
        @test fma(entireinterval(), zero(a), b) == b
        @test fma(entireinterval(), one(a), b) == entireinterval()
        @test fma(zero(a), entireinterval(), b) == b
        @test fma(one(a), entireinterval(), b) == entireinterval()
        @test fma(a, zero(a), c) == c
        @test fma(Interval(1//2), Interval(1//3), Interval(1//12)) == Interval(3//12)
    end

    @testset "∈ tests" begin
        @test !(Inf ∈ entireinterval())
        @test 0.1 ∈ @interval(0.1)
        @test 0.1 in @interval(0.1)
        @test !(-Inf ∈ entireinterval())
        @test !(Inf ∈ entireinterval())

        @test_throws ArgumentError (3..4) ∈ (3..4)
    end

    @testset "Inclusion tests" begin
        @test b ⊆ c
        @test emptyinterval(c) ⊆ c
        @test !(c ⊆ emptyinterval(c))
        @test isinterior(b,c)
        @test !(b ⪽ emptyinterval(b))
        @test emptyinterval(c) ⪽ c
        @test emptyinterval(c) ⪽ emptyinterval(c)
        @test b ⊂ c
        @test !(b ⊂ b)
        @test emptyinterval(c) ⊂ c
        @test !(c ⊂ emptyinterval(c))
        @test c ⊃ b
        @test !(b ⊃ b)
        @test !(emptyinterval(c) ⊃ c)
        @test c ⊃ emptyinterval(c)
        @test c ⊇ b
        @test b ⊇ b
        @test !(emptyinterval(c) ⊇ c)
        @test c ⊇ emptyinterval(c)
        @test isdisjoint(a, @interval(2.1))
        @test !(isdisjoint(a, b))
        @test isdisjoint(emptyinterval(a), a)
        @test isdisjoint(emptyinterval(), emptyinterval())
    end

    @testset "Comparison tests" begin
        @test IntervalArithmetic.islessprime(a.lo, b.lo) == (a.lo < b.lo)
        @test IntervalArithmetic.islessprime(Inf, Inf)
        @test ∅ <= ∅
        @test !(Interval(1.0,2.0) <= ∅)
        @test Interval(-Inf,Inf) <= Interval(-Inf,Inf)
        @test !(Interval(-0.0,2.0) ≤ Interval(-Inf,Inf))
        @test precedes(∅,∅)
        @test precedes(Interval(3.0,4.0),∅)
        @test !(precedes(Interval(0.0,2.0),Interval(-Inf,Inf)))
        @test precedes(Interval(1.0,3.0),Interval(3.0,4.0))
        @test strictprecedes(Interval(3.0,4.0),∅)
        @test !(strictprecedes(Interval(-3.0,-1.0),Interval(-1.0,0.0)))
        @test !(iscommon(emptyinterval()))
        @test !(iscommon(entireinterval()))
        @test iscommon(a)
        @test !(isunbounded(emptyinterval()))
        @test isunbounded(entireinterval())
        @test isunbounded(Interval(-Inf, 0.0))
        @test isunbounded(Interval(0.0, Inf))
        @test !(isunbounded(a))
    end

    @testset "Intersection tests" begin
        @test emptyinterval() == Interval(Inf, -Inf)
        @test (a ∩ @interval(-1)) == emptyinterval(a)
        @test isempty(a ∩ @interval(-1) )
        @test !(isempty(a))
        @test !(emptyinterval(a) == a)
        @test emptyinterval() == emptyinterval()

        @test intersect(a, hull(a,b)) == a
        @test union(a,b) == Interval(a.lo, b.hi)

        # n-ary intersection
        @test intersect(Interval(1.0, 2.0),
                        Interval(-1.0, 5.0),
                        Interval(1.8, 3.0)) == Interval(1.8, 2.0)
        @test intersect(a, emptyinterval(), b) == emptyinterval()
        @test intersect(0..1, 3..4, 0..1, 0..1) == emptyinterval()
    end

    @testset "Hull and union tests" begin
        @test hull(1..2, 3..4) == Interval(1, 4)
        @test hull(Interval(1//3, 3//4), Interval(3, 4)) == @interval(1/3, 4)

        @test union(1..2, 3..4) == Interval(1, 4)
        @test union(Interval(1//3, 3//4), Interval(3, 4)) == @interval(1/3, 4)
    end

    @testset "Special interval tests" begin

        @test entireinterval(Float64) == Interval(-Inf, Inf)
        @test isentire(entireinterval(a))
        @test isentire(Interval(-Inf, Inf))
        @test !(isentire(a))
        @test Interval(-Inf, Inf) ⪽ Interval(-Inf, Inf)

        @test nai(a) === nai(a)
        @test nai(Float64) === DecoratedInterval(NaN)
        @test isnan(interval(nai(BigFloat)).lo)
        @test isnai(nai())
        @test !(isnai(a))

        @test inf(a) == a.lo
        @test sup(a) == a.hi
        @test inf(emptyinterval(a)) == Inf
        @test sup(emptyinterval(a)) == -Inf
        @test inf(entireinterval(a)) == -Inf
        @test sup(entireinterval(a)) == Inf
        @test isnan(sup(nai(BigFloat)))
    end

    @testset "mid" begin

        @test mid(Interval(1//2)) == 1//2
        @test mid(1..2) == 1.5
        @test mid(0.1..0.3) == 0.2
        @test mid(-10..5) == -2.5
        @test mid(-∞..1) == nextfloat(-∞)
        @test mid(1..∞) == prevfloat(∞)
        @test isnan(mid(emptyinterval()))
    end

    @testset "mid with parameter" begin
        @test mid(0..1, 0.75) == 0.75
        @test mid(1..∞, 0.75) > 0
        @test mid(-∞..∞, 0.75) > 0
        @test mid(-∞..∞, 0.25) < 0
    end

    @testset "mid with large floats" begin
        @test mid(0.8e308..1.2e308) == 1e308
        @test mid(-1e308..1e308) == 0
        @test isfinite(mid(0.8e308..1.2e308, 0.75))
        @test isfinite(mid(-1e308..1e308, 0.75))
    end

    @testset "diam" begin

        @test diam( Interval(1//2) ) == 0//1
        @test diam( @interval(1//10) ) == eps(0.1)
        @test diam( @interval(0.1) ) == eps(0.1)
        @test isnan(diam(emptyinterval()))
        @test diam(a) == 1.0000000000000002
    end

    @testset "mig and mag" begin

        @test mig(@interval(-2,2)) == BigFloat(0.0)
        @test mig( Interval(1//2) ) == 1//2
        @test isnan(mig(emptyinterval()))
        @test mag(-b) == b.hi
        @test mag( Interval(1//2) ) == 1//2
        @test isnan(mag(emptyinterval()))
    end

    @testset "cancelplus tests" begin

        x = Interval(-2.0, 4.440892098500622e-16)
        y = Interval(-4.440892098500624e-16, 2.0)
        @test cancelminus(x, y) == entireinterval(Float64)
        @test cancelplus(x, y) == entireinterval(Float64)
        x = Interval(-big(1.0), eps(big(1.0))/4)
        y = Interval(-eps(big(1.0))/2, big(1.0))
        @test cancelminus(x, y) == entireinterval(BigFloat)
        @test cancelplus(x, y) == entireinterval(BigFloat)
        x = Interval(-big(1.0), eps(big(1.0))/2)
        y = Interval(-eps(big(1.0))/2, big(1.0))
        @test cancelminus(x, y) ⊆ Interval(-one(BigFloat), one(BigFloat))
        @test cancelplus(x, y) == Interval(zero(BigFloat), zero(BigFloat))
        @test cancelminus(emptyinterval(), emptyinterval()) == emptyinterval()
        @test cancelplus(emptyinterval(), emptyinterval()) == emptyinterval()
        @test cancelminus(emptyinterval(), Interval(0.0, 5.0)) == emptyinterval()
        @test cancelplus(emptyinterval(), Interval(0.0, 5.0)) == emptyinterval()
        @test cancelminus(entireinterval(), Interval(0.0, 5.0)) == entireinterval()
        @test cancelplus(entireinterval(), Interval(0.0, 5.0)) == entireinterval()
        @test cancelminus(Interval(5.0), Interval(-Inf, 0.0)) == entireinterval()
        @test cancelplus(Interval(5.0), Interval(-Inf, 0.0)) == entireinterval()
        @test cancelminus(Interval(0.0, 5.0), emptyinterval()) == entireinterval()
        @test cancelplus(Interval(0.0, 5.0), emptyinterval()) == entireinterval()
        @test cancelminus(Interval(0.0), Interval(0.0, 1.0)) == entireinterval()
        @test cancelplus(Interval(0.0), Interval(0.0, 1.0)) == entireinterval()
        @test cancelminus(Interval(0.0), Interval(1.0)) == Interval(-1.0)
        @test cancelplus(Interval(0.0), Interval(1.0)) == Interval(1.0)
        @test cancelminus(Interval(-5.0, 0.0), Interval(0.0, 5.0)) == Interval(-5.0)
        @test cancelplus(Interval(-5.0, 0.0), Interval(0.0, 5.0)) == Interval(0.0)
    end

    @testset "mid and radius" begin
        @test radius(Interval(-1//10,1//10)) == diam(Interval(-1//10,1//10))/2
        @test isnan(IntervalArithmetic.radius(emptyinterval()))
        @test mid(c) == 2.125
        @test isnan(mid(emptyinterval()))
        @test mid(entireinterval()) == 0.0
        @test isnan(mid(nai()))
        if VERSION < v"0.7.0-DEV"
            @test_throws ArgumentError nai(Interval(1//2))
        else
            @test_throws InexactError nai(Interval(1//2))
        end
    end

    @testset "abs, min, max, sign" begin

        @test abs(entireinterval()) == Interval(0.0, Inf)
        @test abs(emptyinterval()) == emptyinterval()
        @test abs(Interval(-3.0,1.0)) == Interval(0.0, 3.0)
        @test abs(Interval(-3.0,-1.0)) == Interval(1.0, 3.0)
        @test abs2(Interval(-3.0,1.0)) == Interval(0.0, 9.0)
        @test abs2(Interval(-3.0,-1.0)) == Interval(1.0, 9.0)
        @test min(entireinterval(), Interval(3.0,4.0)) == Interval(-Inf, 4.0)
        @test min(emptyinterval(), Interval(3.0,4.0)) == emptyinterval()
        @test min(Interval(-3.0,1.0), Interval(3.0,4.0)) == Interval(-3.0, 1.0)
        @test min(Interval(-3.0,-1.0), Interval(3.0,4.0)) == Interval(-3.0, -1.0)
        @test max(entireinterval(), Interval(3.0,4.0)) == Interval(3.0, Inf)
        @test max(emptyinterval(), Interval(3.0,4.0)) == emptyinterval()
        @test max(Interval(-3.0,1.0), Interval(3.0,4.0)) == Interval(3.0, 4.0)
        @test max(Interval(-3.0,-1.0), Interval(3.0,4.0)) == Interval(3.0, 4.0)
        @test sign(entireinterval()) == Interval(-1.0, 1.0)
        @test sign(emptyinterval()) == emptyinterval()
        @test sign(Interval(-3.0,1.0)) == Interval(-1.0, 1.0)
        @test sign(Interval(-3.0,-1.0)) == Interval(-1.0, -1.0)

        # Test putting functions in @interval:
        @test log(@interval(-2,5)) == @interval(-Inf,log(5.0))
        @test @interval(sin(0.1) + cos(0.2)) == sin(@interval(0.1)) + cos(@interval(0.2))

        f(x) = 2x
        @test @interval(f(0.1)) == f(@interval(0.1))

        # midpoint-radius representation
        a = @interval(0.1)
        midpoint, radius = midpoint_radius(a)

        @test interval_from_midpoint_radius(midpoint, radius) ==
            Interval(0.09999999999999999, 0.10000000000000002)
    end

    @testset "Precision tests" begin
        setprecision(Interval, 100)
        @test precision(Interval) == (BigFloat, 100)

        setprecision(Interval, Float64)
        @test precision(Interval) == (Float64, 100)

        a = @interval(0.1, 0.3)

        b = setprecision(Interval, 64) do
            @interval(0.1, 0.3)
        end

        @test b ⊆ a

        @test precision(Interval) == (Float64, 100)
    end

    # @testset "Interval rounding tests" begin
    #     # setrounding(Interval, :wide)
    #     @test rounding(Interval) == :wide
    #
    #     @test_throws ArgumentError # setrounding(Interval, :hello)
    #
    #     # setrounding(Interval, :narrow)
    #     @test rounding(Interval) == :narrow
    # end

    @testset "Interval power of an interval" begin

        setprecision(Interval, Float64)

        a = @interval(1, 2)
        b = @interval(3, 4)

        @test a^b == @interval(1, 16)
        @test a^@interval(0.5, 1) == a
        @test a^@interval(0.3, 0.5) == @interval(1, sqrt(2))

        @test b^@interval(0.3) == Interval(1.3903891703159093, 1.5157165665103982)
    end

    @testset "isatomic" begin
        @test isatomic(Interval(1))
        @test isatomic(Interval(2.3, 2.3))
        @test isatomic(emptyinterval())
        @test isatomic(@interval(∞))  # Interval(floatmax(), Inf)

        @test !isatomic(1..2)
        @test !isatomic(Interval(1, nextfloat(1.0, 2)))

    end

    @testset "iszero" begin
        @test iszero(Interval(0))
        @test iszero(Interval(0//1))
        @test iszero(Interval(big(0)))
        @test iszero(Interval(-0.0))
        @test iszero(Interval(-0.0, 0.0))

        @test !iszero(1..2)
        @test !iszero(Interval(0.0, nextfloat(0.0)))
    end

    @testset "Difference between Interval and interval" begin
        @test interval(1, 2) == Interval(1, 2)

        @test inf(Interval(3, 2)) == 3
        @test_logs (:warn,) @test isempty(interval(3, 2))

        @test sup(Interval(Inf, Inf)) == Inf
        @test_logs (:warn,) @test isempty(interval(Inf, Inf))

    end

    @testset "Type stability" begin
        for T in (Float32, Float64, BigFloat)

            xs = [3..4, 0..4, 0..0, -4..0, -4..4, -Inf..4, 4..Inf, -Inf..Inf]

            for x in xs
                for y in xs
                    xx = Interval{T}(x)
                    yy = Interval{T}(y)

                    for op in (+, -, *, /, atan)
                        @inferred op(x, y)
                    end
                end

                for op in (sin, cos, exp, log, tan, abs, mid, diam)
                    @inferred op(x)
                end
            end
        end
    end

end


text:
export ≃, ≄,
    alpha_equivalent,
    evaluate,
    evaluateonce,
    freevars,
    reify,
    substitute,
    freevartype,
    boundvartype

export AbstractTerm,
    Index,
    Name

abstract type AbstractTerm end

const Index = Int
const Name = Symbol

"""
    alpha_equivalent(term, term)

Determine syntactic equivalence between terms (modulo bound variables).
"""
function alpha_equivalent end

const ≃ = alpha_equivalent
const ≄ = !≃

"""
    evaluate(term[, maxsteps])

Evaluate `term` in normal order, using maximally `maxsteps` reductions.
"""
function evaluate end

"""
    evaluateonce(term)

Evaluate `term` by one step in normal order (i.e., the leftmost, outermost redex).  If there
is no redex, return `nothing`.
"""
function evaluateonce end

"""
    freevars(term) -> Set

Calculate the set of free variables in `term`.
"""
function freevars end

"""
    reify(term) -> Expr

Construct an expression which, when evaluated, returns `term`.
"""
function reify end

"""
    substitute(v, s::Term, t::Term) -> Term

Capture-avoiding substitution of variable `v` in `t` by `s`, commonly written like `t[v -> s]`.
Will rename bound variables, if required.
"""
function substitute end

"""
    freevartype(type) -> Type

Determine the type of free variables used in term type `type`.
"""
function freevartype end

freevartype(t::T) where {T} = freevartype(T)

"""
    boundvartype(type) -> Type

Determine the type of bound variables used in term type `type`.
"""
function boundvartype end

boundvartype(t::T) where {T} = boundvartype(T)


text:
module bbgTS

using DataFrames
using TimeSeries
using Base.Dates
using Blpapi
using Gadfly
using GLM
using JuliaInXL
using Sauhaufen

export connObject
export createConn
export instrument
export TS
export BarFrame
export intrRotFact
export intrRotFactXL

# using JuliaInXL:xldate
# fromDate = DateTime(xldate(xlFromDate))

type connObject

  IP
  Port
  session

end

function createConn(IP = "localhost", Port = 8194)
  try
    session = createSession(IP, Port)
    conn = connObject(IP, Port, session)
  catch e
    e_msg = string(sprint(io->Base.showerror(io,e)), sprint(io->Base.show_backtrace(io,catch_backtrace())))
    println(e_msg)
    return e_msg
  end
end

type instrument

  ticker
  fields
  startDate
  endDate

end

function TS(con = connection, inst = ibm)

  response = bdh(con.session, [inst.ticker], [inst.fields], inst.startDate, inst.endDate; periodicitySelection = "DAILY")
  data = response[inst.ticker, inst.fields]

  dformat = Dates.DateFormat("y-m-d")
  dates = similar(data[:,1], Date)
  prices = similar(data[:,2], Float64)

  for i in (1:length(data[:,1]))
    dates[i] = Date(data[i,1], dformat)
    prices[i] = data[i,2]
  end

  k = sortperm(dates)
  dates = dates[k]
  prices = prices[k]

  data = TimeArray(dates, prices, [inst.ticker])

end

function BarFrame(con, inst, barsize)

    Response = bar(con.session, inst.ticker, inst.fields, string(inst.startDate), string(inst.endDate); interval=barsize)

    df = DataFrame()
    df[:Dates] = Response.datetimes
    df[:Open] = zeros(length(Response.datetimes))
    df[:High] = zeros(length(Response.datetimes))
    df[:Low] = zeros(length(Response.datetimes))
    df[:Close] = zeros(length(Response.datetimes))
    df[:Volume] = zeros(length(Response.datetimes))
    df[:RotFact] = zeros(length(Response.datetimes))

    for i in 1:length(Response.datetimes)
    df[i,:Open] = Response[Response.datetimes[i]].openVar
    df[i,:High] = Response[Response.datetimes[i]].highVar
    df[i,:Low] = Response[Response.datetimes[i]].lowVar
    df[i,:Close] = Response[Response.datetimes[i]].closeVar
    df[i,:Volume] = Response[Response.datetimes[i]].volumeVar
    end

    for i in collect(nrow(df):-1:2)
        if df[i,:High] > df[i-1,:High] && df[i,:Low] > df[i-1,:Low]
            df[i,:RotFact] = mean([df[i,:High], df[i,:Low]])*df[i,:Volume]
        elseif df[i,:High] < df[i-1,:High] && df[i,:Low] < df[i-1,:Low]
            df[i,:RotFact] = mean([df[i,:High], df[i,:Low]])*df[i,:Volume]*-1
        else
        df[i,:RotFact] = 0
        end
    end

    return df

end

function intrRotFact(commodity, days_back)

    df = bbgTS.VolAnalytics[commodity]
    df = Array{Any}(df[Date(df[:,:Dates]) .== Date(now())-Day(days_back), [:Dates, :Volume, :RotFact]])
    df[:,1] = toXLDate.(df[:,1])
    return df

end

function intrRotFactXL(commodity, days_back)

    inst = bbgTS.contracts[commodity]
    inst.startDate = now() - Dates.Month(2)
    inst.endDate = now()
    df = BarFrame(bbgTS.conInternal, inst, bbgTS.n)
    df = Array{Any}(df[Date(df[:,:Dates]) .== Date(now())-Dates.Day(days_back), [:Dates, :Volume, :RotFact]])
    df[:,1] = toXLDate.(df[:,1])
    return df

end

t = now()
startDate = t - Dates.Month(2)
conInternal = createConn()
n = 30

VolAnalytics = Dict([("Gas", BarFrame(conInternal, instrument("FNA Comdty", "TRADE", startDate, t), n)),
                ("Brent", BarFrame(conInternal, instrument("COA Comdty", "TRADE", startDate, t), n)),
                ("Bund", BarFrame(conInternal, instrument("RXA Comdty", "TRADE", startDate, t), n))])

contracts = Dict([("Gas", instrument("FNA Comdty", "TRADE", startDate, t)),
                    ("Brent", instrument("COA Comdty", "TRADE", startDate, t)),
                    ("Bund", instrument("RXA Comdty", "TRADE", startDate, t))])

end


text:
using Clang.Generators

function generate_ceed_bindings(ceed_path)
    # libCEED include dir and header files
    include_dir = joinpath(ceed_path, "include") |> normpath
    header_files = ["ceed/ceed.h", "ceed/cuda.h", "ceed/backend.h"]
    headers = [joinpath(include_dir, header) for header in header_files]

    # load options from generator TOML file
    options = load_options(joinpath(@__DIR__, "generator.toml"))

    # add compiler flags
    args = get_default_args()
    push!(args, "-I$include_dir")

    # create context
    ctx = create_context(headers, args, options)

    # run generator
    build!(ctx)

    # remove trailing newline from output file
    outfile = options["general"]["output_file_path"]
    write(outfile, readchomp(outfile))
    return
end

max_stars_repo_name: AdelekeBankole/libCEED

max_issues_repo_name: AdelekeBankole/libCEED

max_forks_repo_name: AdelekeBankole/libCEED


text:
using BinaryBuilder

# zlib version
version = v"1.2.11"

# Collection of sources required to build zlib
sources = [
    "https://zlib.net/zlib-$(version).tar.gz" =>
    "c3e5e9fdd5004dcb542feda5ee4f0ff0744628baf8ed2dd5d66f8ca1197cb1a1",
]

# Bash recipe for building across all platforms
script = raw"""
cd $WORKSPACE/srcdir/zlib-*

# On windows platforms, our ./configure and make invocations differ a bit
if [[ ${target} == *-w64-mingw* ]]; then
    EXTRA_CONFIGURE_FLAGS="--sharedlibdir=${prefix}/bin"
    EXTRA_MAKE_FLAGS="SHAREDLIB=libz.dll SHAREDLIBM=libz-1.dll SHAREDLIBV=libz-1.2.11.dll LDSHAREDLIBC= "
fi

if [[ ${target} == *-freebsd* ]]; then
    cmake -DCMAKE_INSTALL_PREFIX=${prefix} -DCMAKE_TOOLCHAIN_FILE=/opt/${target}/${target}.toolchain
else
    ./configure ${EXTRA_CONFIGURE_FLAGS} --prefix=${prefix}
fi

make install ${EXTRA_MAKE_FLAGS} -j${nproc}
"""

# Build for ALL THE PLATFORMS!
platforms = supported_platforms()

# The products that we will ensure are always built
products = prefix -> [
    LibraryProduct(prefix, "libz", :libz),
]

# Dependencies that must be installed before this package can be built
dependencies = [
]

build_tarballs(ARGS, "Zlib", version, sources, script, platforms, products, dependencies)


text:
# Test that the minimum image distance is correctly calculated

@testset "Minimum image distance" begin
@testset "fcc" begin
    @test MkCell.score_image_distance(fcc1*cellfcc)   ≈ 0.7071067811865476
    @test MkCell.score_image_distance(fcc4*cellfcc)   ≈ 1.000
    @test MkCell.score_image_distance(fcc7*cellfcc)   ≈ 1.224744871391589
    @test MkCell.score_image_distance(fcc13*cellfcc)  ≈ 1.5811388300841898
    @test MkCell.score_image_distance(fcc23*cellfcc)  ≈ 1.7320508075688772
    @test MkCell.score_image_distance(fcc26*cellfcc)  ≈ 1.8708286933869707
    @test MkCell.score_image_distance(fcc32*cellfcc)  ≈ 2.000
    @test MkCell.score_image_distance(fcc38*cellfcc)  ≈ 2.1213203435596424
    @test MkCell.score_image_distance(fcc50*cellfcc)  ≈ 2.345207879911715
    @test MkCell.score_image_distance(fcc70*cellfcc)  ≈ 2.5495097567963922
    @test MkCell.score_image_distance(fcc92*cellfcc)  ≈ 2.7386127875258306
    @test MkCell.score_image_distance(fcc96*cellfcc)  ≈ 2.8284271247461903
    @test MkCell.score_image_distance(fcc100*cellfcc) ≈ 2.9154759474226504
    @test MkCell.score_image_distance(fcc108*cellfcc) ≈ 3.000
end;
@testset "cubic" begin
    @test MkCell.score_image_distance(cubic1*cellcubic)   ≈ 1.000
    @test MkCell.score_image_distance(cubic3*cellcubic)   ≈ 1.4142135623730951
    @test MkCell.score_image_distance(cubic7*cellcubic)   ≈ 1.7320508075688772
    @test MkCell.score_image_distance(cubic8*cellcubic)   ≈ 2.000
    @test MkCell.score_image_distance(cubic13*cellcubic)  ≈ 2.23606797749979
    @test MkCell.score_image_distance(cubic14*cellcubic)  ≈ 2.449489742783178
    @test MkCell.score_image_distance(cubic24*cellcubic)  ≈ 2.8284271247461903
    @test MkCell.score_image_distance(cubic27*cellcubic)  ≈ 3.000
    @test MkCell.score_image_distance(cubic33*cellcubic)  ≈ 3.1622776601683795
    @test MkCell.score_image_distance(cubic38*cellcubic)  ≈ 3.3166247903554
    @test MkCell.score_image_distance(cubic52*cellcubic)  ≈ 3.605551275463989
    @test MkCell.score_image_distance(cubic56*cellcubic)  ≈ 3.7416573867739413
    @test MkCell.score_image_distance(cubic64*cellcubic)  ≈ 4.000
    @test MkCell.score_image_distance(cubic73*cellcubic)  ≈ 4.123105625617661
    @test MkCell.score_image_distance(cubic76*cellcubic)  ≈ 4.242640687119285
    @test MkCell.score_image_distance(cubic93*cellcubic)  ≈ 4.358898943540674
    @test MkCell.score_image_distance(cubic100*cellcubic) ≈ 4.47213595499958
end;
@testset "bcc" begin
    @test MkCell.score_image_distance(bcc1*cellbcc)   ≈ 0.8660254037844386
    @test MkCell.score_image_distance(bcc2*cellbcc)   ≈ 1.000
    @test MkCell.score_image_distance(bcc6*cellbcc)   ≈ 1.4142135623730951
    @test MkCell.score_image_distance(bcc9*cellbcc)   ≈ 1.6583123951777
    @test MkCell.score_image_distance(bcc16*cellbcc)  ≈ 2.000
    @test MkCell.score_image_distance(bcc21*cellbcc)  ≈ 2.179449471770337
    @test MkCell.score_image_distance(bcc25*cellbcc)  ≈ 2.23606797749979
    @test MkCell.score_image_distance(bcc28*cellbcc)  ≈ 2.449489742783178
    @test MkCell.score_image_distance(bcc35*cellbcc)  ≈ 2.598076211353316
    @test MkCell.score_image_distance(bcc48*cellbcc)  ≈ 2.8284271247461903
    @test MkCell.score_image_distance(bcc53*cellbcc)  ≈ 2.958039891549808
    @test MkCell.score_image_distance(bcc54*cellbcc)  ≈ 3.000
    @test MkCell.score_image_distance(bcc65*cellbcc)  ≈ 3.278719262151
    @test MkCell.score_image_distance(bcc84*cellbcc)  ≈ 3.3166247903554
    @test MkCell.score_image_distance(bcc91*cellbcc)  ≈ 3.570714214271425
    @test MkCell.score_image_distance(bcc103*cellbcc) ≈ 3.605551275463989
    @test MkCell.score_image_distance(bcc107*cellbcc) ≈ 3.7416573867739413
    @test MkCell.score_image_distance(bcc112*cellbcc) ≈ 3.840572873934304
    @test MkCell.score_image_distance(bcc128*cellbcc) ≈ 4.000
end;
@testset "hcp" begin
    @test MkCell.score_image_distance(hcp1*cellhcp)   ≈ 0.5612
    @test MkCell.score_image_distance(hcp3*cellhcp)   ≈ 0.9164357624332797
    @test MkCell.score_image_distance(hcp6*cellhcp)   ≈ 0.972026913207654
    @test MkCell.score_image_distance(hcp8*cellhcp)   ≈ 1.1224
    @test MkCell.score_image_distance(hcp11*cellhcp)  ≈ 1.3359232113660824
    @test MkCell.score_image_distance(hcp14*cellhcp)  ≈ 1.4490121692610682
    @test MkCell.score_image_distance(hcp16*cellhcp)  ≈ 1.4847956357694483
    @test MkCell.score_image_distance(hcp21*cellhcp)  ≈ 1.7448417081978143
    @test MkCell.score_image_distance(hcp27*cellhcp)  ≈ 1.9168629232855088
    @test MkCell.score_image_distance(hcp37*cellhcp)  ≈ 2.023435375790391
    @test MkCell.score_image_distance(hcp39*cellhcp)  ≈ 2.0746696957989883
    @test MkCell.score_image_distance(hcp42*cellhcp)  ≈ 2.149232371491428
    @test MkCell.score_image_distance(hcp53*cellhcp)  ≈ 2.221293593081893
    @test MkCell.score_image_distance(hcp62*cellhcp)  ≈ 2.358820914496619
    @test MkCell.score_image_distance(hcp65*cellhcp)  ≈ 2.4246611199643273
    @test MkCell.score_image_distance(hcp69*cellhcp)  ≈ 2.4462140871150257
    @test MkCell.score_image_distance(hcp76*cellhcp)  ≈ 2.6122438375210435
    @test MkCell.score_image_distance(hcp80*cellhcp)  ≈ 2.6718464227321648
    @test MkCell.score_image_distance(hcp88*cellhcp)  ≈ 2.7301481180819964
    @test MkCell.score_image_distance(hcp90*cellhcp)  ≈ 2.749307287299839
    @test MkCell.score_image_distance(hcp100*cellhcp) ≈ 2.806
end;
end;


text:
# Copyright 2022 RelationalAI, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Low level HTTP interface to the RAI REST API. Handles authentication of
# requests and other protocol level details.

using Dates: now
import HTTP
import JSON3

"""
    Context

Contains the settings required to make requests against the RelationalAI
REST APIs in the given region, using the given credentials. It's also possible
to set the host, port and URL scheme, although typically clients will use the
default values for those settings.
"""
struct Context
    region::String
    scheme::String
    host::String
    port::String
    credentials::Union{Credentials,Nothing}

    Context(region, scheme, host, port, credentials) =
        new(region, scheme, host, port, credentials)

    # todo: consider use of kwargs like we do in the python SDK
    #   consider use of @Base.kwdef
    function Context(cfg::Config)
        region = !isnothing(cfg.region) ? cfg.region : "us-east"
        scheme = !isnothing(cfg.scheme) ? cfg.scheme : "https"
        host = !isnothing(cfg.host) ? cfg.host : "azure.relationalai.com"
        port = !isnothing(cfg.port) ? cfg.port : "443"
        new(region, scheme, host, port, cfg.credentials)
    end
end

# Answers if the given `headers` contains a key that is a case insensitive
# match for the given key.
function _haskeyfold(headers::HTTP.Headers, key::AbstractString)::Bool
    key = lowercase(key)
    for (k, _) in headers
        key == lowercase(k) && return true
    end
    return false
end

# Returns the default User-Agent string for this library.
function _user_agent()
    return "rai-sdk-julia/$PROJECT_VERSION"
end

# Ensures that the given headers contain the required values.
function _ensure_headers!(h)
    h = HTTP.Headers(h)
    return _ensure_headers!(h)
end

function _ensure_headers!(h::HTTP.Headers = HTTP.Headers())::HTTP.Headers
    _haskeyfold(h, "accept") || push!(h, "Accept" => "application/json")
    _haskeyfold(h, "content-type") || push!(h, "Content-Type" => "application/json")
    _haskeyfold(h, "user-agent") || push!(h, "User-Agent" => _user_agent())
    return h
end

function get_access_token(ctx::Context, creds::ClientCredentials)::AccessToken
    url = _get_client_credentials_url(creds)
    h = _ensure_headers!()
    body = """{
        "client_id": "$(creds.client_id)",
        "client_secret": "$(creds.client_secret)",
        "audience": "https://$(ctx.host)",
        "grant_type": "client_credentials"
    }"""
    opts = (readtimeout = 5, redirect = false, retry = false)
    rsp = HTTP.request("POST", url, h, body; opts...)
    data = JSON3.read(rsp.body)
    return AccessToken(data.access_token, data.scope, data.expires_in, now())
end

function _get_client_credentials_url(creds::ClientCredentials)
    return !isnothing(creds.client_credentials_url) ?
           creds.client_credentials_url : "https://login.relationalai.com/oauth/token"
end

function _authenticate!(ctx::Context, headers::HTTP.Headers)
    if !isnothing(ctx.credentials)
        _authenticate!(ctx, ctx.credentials, headers)
    end
    return nothing
end

function _authenticate!(
    ctx::Context,
    creds::ClientCredentials,
    headers::HTTP.Headers
)::Nothing
    if isnothing(creds.access_token)
        creds.access_token = get_access_token(ctx, creds)
    end

    if isexpired(creds.access_token)
        creds.access_token = get_access_token(ctx, creds)
    end
    push!(headers, "Authorization" => "Bearer $(creds.access_token.token)")
    return nothing
end

# Note, this function is deliberately patterend on the HTTP.jl request funciton.
function request(
    ctx::Context, method, url, h = HTTP.Header[], b = UInt8[];
    headers = h, query = nothing, body = b, kw...
)::HTTP.Response
    isnothing(body) && (body = UInt8[])
    headers = _ensure_headers!(headers)
    _authenticate!(ctx, headers)
    opts = (redirect = false, retry = false)
    return HTTP.request(method, url, headers; query = query, body = body, opts..., kw...)
end

max_stars_repo_name: RelationalAI/rai-sdk-julia

max_issues_repo_name: RelationalAI/rai-sdk-julia

max_forks_repo_name: RelationalAI/rai-sdk-julia


text:
using RiceBPH.PostProcess
using JLD2

result_dir = joinpath(@__DIR__, "sample-results")
result_files = joinpath.(result_dir, readdir(result_dir))
result_files = filter(endswith("jld2"), result_files)
result_file = rand(result_files)

@testset "Plotting" begin
    p = PostProcess.plot_bph(result_file)
    savefig(p, "bph.png")
    @test true
    p = PostProcess.plot_rice(result_file)
    savefig(p, "rice.png")
    @test true
end

@testset "Hypothesis Testing" begin
    test_rice(result_file, 0.01)
    @test true
    batch_test_rice(result_dir, 0.01; alpha=0.05, clean=true)
    @test true
end

@testset "Population peak" begin
    local df = jldopen(f -> f["1"], result_file)
    peak_population(df.count_bph)
    @test true
    peak_population(result_file)
    @test true
    batch_peak_population(result_dir)
    @test true
end

max_stars_repo_name: ndgnuh/RiceBPH

max_issues_repo_name: ndgnuh/RiceBPH

max_forks_repo_name: ndgnuh/RiceBPH


text:
module DataDrivenControl

using LinearAlgebra
using UnPack
using Transducers

## Costs
export QuadraticInInputCost, QuadraticCost
## IRL
# Linear IRL
export LinearIRL, value_iteration!, policy_iteration!
export optimal_input

## Stop conditions
export DistanceStopCondition

include("utils/utils.jl")
include("irl/irl.jl")

end