text:
###############################################################################
# Helpers
###############################################################################
pluck(objarr, sym) = map((obj)->getfield(obj, sym), objarr)

"""
`ismatch{T<:Any}(query::Dict{Symbol, T}, obj)`
Given a query Dict specifying equality queries of the form `fieldname=value`
returns whether the `obj` is a match for all queries.
If `query` is empty returns `true`.
"""
Base.ismatch{T<:Any}(query::Dict{Symbol, T}, obj) = begin
    all((getfield(obj, fld) == val) ||
        (isa(val, AbstractArray) && getfield(obj, fld) in val)
                for (fld,val) in query)

end

"""
`filterquery{T<:Any}(query::Dict{Symbol, T}, collection::AbstractArray)`
Given an iterable of objects, `collection`, returns a new iterable of all
objects in collection who match `query` as tested by `ismatch(query, obj)`
"""
filterquery{T<:Any}(query::Dict{Symbol, T}, collection::AbstractArray) = begin
    isempty(query) && return collection #XXX non-copy if empty query
    #TODO change to return a view not a copy
    filter(collection) do obj ismatch(query, obj) end
end

"""
Create default auto-incremented numbered location for the tracepoint

n.b. File and line number of call site in macro-expansion isn't possible yet.
Waiting on https://github.com/JuliaLang/julia/issues/9577
"""
next_global_location() = begin
    global _num_trace_locations
    _num_trace_locations += 1
end

function add_expr_equalities(kwargs, args, arginfo, lv, rv)
    kwargs[:exprstr] = string(lv)
    kwargs[:val] = rv
    (:exprstr, :val)
end

location_spec = Dict(:aliases=>[:location, :loc, :l],
                    :convert=>string, :default=>next_global_location)

lcount_spec = Dict(:aliases=>[:lcount, :lc],
                    :convert=>Int, :default=>0)

throttle_spec = Dict(:aliases=>[:everyN, :every, :N],
                    :convert=>Int, :default=>1)

if_spec = Dict(:aliases=>[:iff, :when, :onlyif], :default=>true)

path_spec = Dict(:aliases=>[:path, :file], :default=>"traces.jld")

trace_kwargspec = Dict(
    :location=>location_spec,
    :lcount=>lcount_spec,
    :everyN=>throttle_spec,
    :iff=>if_spec,
    :_and_the_rest=>Dict(:fn=>add_expr_equalities)
)

"""
spec[:default] can be a value or a nullary function that when called returns the default
"""
get_default(spec) = begin
    !haskey(spec, :default) && return nothing
    !isempty(methods(spec[:default])) ?
                        spec[:default]() : spec[:default]
end

"""
`kwargparse(kwargspec, exprs; no_defaults=false)`
Parse keyword args passed to your macro
For each keyword argument you want to handle, provide a argument specification:
    :aliases ::Vector{Symbol} #possible names used for this variable
    :default ::Union{Function, Literal} #(optional) default value for the var if keyword not provided
    :convert ::Function #(optional) - called after arg is parsed to e.g. convert it to a correct type
kwargspec (key word argument specification) is then a Dict from your symbol names => their argument specification as defined above
Returns: a tuple `(kwargs::Dict{Symbol, Any}, args::Vector{Expr}, arginfo::Dict{Symbol, Dict{Symbol, Any}})`
kwargs has values for all symbols in your kwargspec, args holds remaining non-kw expressions.
`arginfo[:sym][:provided]` which tells you if the variable was provided or not.
#### kwargs
If `no_defaults` is true then the returned Dict will only contain symbols actually specified in exprs, i.e. no default values from the kwargspec will be returned.
If `dropextras` is true then kwargs not in the spec will return false
"""
kwargparse(kwargspec, exprs; no_defaults=false, dropextras=false) = begin
    kwargs = Dict{Symbol, Any}(key => get_default(spec) for (key, spec) in kwargspec)
    kwextras = Dict{Symbol, Any}()
    arginfo = Dict{Symbol, Any}(key => arginfo_default() for (key, spec) in kwargspec)
    args = []
    for expr in exprs
        if typeof(expr) == Expr && expr.head == Symbol("=")
            sym, val = expr.args[1], expr.args[2]
            added = false
            for (key, spec) in kwargspec
                key == :_and_the_rest && continue
                if sym in spec[:aliases]
                    added = true
                    arginfo[key][:provided] = true
                    if get(spec, :accumulate, false)
                        push!(kwargs[key], val)
                    else
                        kwargs[key] = val
                    end
                end
            end
            if !added
                if haskey(kwargspec, :_and_the_rest)
                    argsrestfn = kwargspec[:_and_the_rest][:fn]
                    kwargs_added =
                        argsrestfn(kwargs, args, arginfo,
                                sym, val)
                    foreach(kwargs_added) do kwarg;
                        arginfo[kwarg] = Dict(:provided => true)
                    end
                else
                    !dropextras && (kwextras[sym] = val)
                end
            end
        else
            push!(args, expr)
        end
    end
    for (key, spec) in kwargspec
        haskey(spec, :convert) && (kwargs[key] = spec[:convert](kwargs[key]))
    end
    if no_defaults
        for dic in (kwargs, arginfo)
            filter!(dic) do key,val
                arginfo[key][:provided]
            end
        end
    end
    kwargs, kwextras, args, arginfo
end

arginfo_default() = Dict(:provided=>false)

max_stars_repo_name: JobJob/RickTracy


text:
mutable struct PlateSimulateState{U}
    score::Float64
    is_empty::Bool
    args::U
end

function simulate_new_trace!(gen::Plate{T,U}, key::Int, state::PlateSimulateState) where {T,U}
    kernel_args = get_args_for_key(state.args, key)
    subtrace::U = simulate(gen.kernel, kernel_args)
    state.is_empty = state.is_empty && !has_choices(subtrace)
    call::CallRecord = get_call_record(subtrace)
    state.score += call.score
    (subtrace, call.retval::T)
end

function simulate(gen::Plate{T,U}, args) where {T,U}
    len = length(args[1])

    # collect initial state
    state = PlateSimulateState(0., true, args)
    subtraces = Vector{U}(undef, len)
    retvals = Vector{T}(undef, len)

    # visit each new application and run generate (or simulate) on it
    for key=1:len
        (subtraces[key], retvals[key]) = simulate_new_trace!(gen, key, state)
    end

    call = CallRecord{PersistentVector{T}}(state.score, PersistentVector{T}(retvals), args)
    VectorTrace{T,U}(PersistentVector{U}(subtraces), call, state.is_empty)
end

ext: jl

max_stars_repo_name: BoltzmannBrain/Gen

max_issues_repo_name: BoltzmannBrain/Gen

max_forks_repo_name: BoltzmannBrain/Gen


text:
using SMC
abstract type Sampler end

function estimate_elbo(p::Sampler, q::Sampler, KP::Int, KQ::Int)
    p_log_weights = Array{Float64,1}(KP)
    q_log_weights = Array{Float64,1}(KQ)
    x, p_log_weights[1] = simulate(p)
    for k=2:KP
        p_log_weights[k] = regenerate(p, x)
    end
    for k=1:KQ
        q_log_weights[k] = regenerate(q, x)
    end
    ((logsumexp(q_log_weights) - log(KQ)) -
     (logsumexp(p_log_weights) - log(KP)))
end

function estimate_elbo_par(p::Sampler, q::Sampler, KP::Int, KQ::Int, N::Int)
    f = (i::Int) -> estimate_elbo(p, q, KP, KQ)
    estimates::Array{Float64,1} = pmap(f, 1:N)
    estimates
end

function aide(gold_standard_sampler::Sampler, target_sampler::Sampler,
              num_gold_standard_metainference::Int, num_target_metainference::Int,
              num_gold_standard_inference::Int, num_target_inference::Int)
    a = -estimate_elbo_par(gold_standard_sampler, target_sampler,
                           num_gold_standard_metainference, num_target_metainference,
                           num_gold_standard_inference)
    b = -estimate_elbo_par(target_sampler, gold_standard_sampler,
                           num_target_metainference, num_gold_standard_metainference,
                           num_target_inference)
    return a + b
end

immutable SMCSampler <: Sampler
    scheme::SMCScheme
    # the evalutaor for the target density p(x,y)
    log_joint_probability_evaluator
end

function simulate(p::SMCSampler)
    x, lml_estimate = smc(p.scheme)
    log_weight = p.log_joint_probability_evaluator(x) - lml_estimate
    (x, log_weight)
end

function regenerate(p::SMCSampler, x)
    lml_estimate = conditional_smc(p.scheme, x)
    p.log_joint_probability_evaluator(x) - lml_estimate
end

immutable HMMExactSampler <: Sampler
    hmm::HiddenMarkovModel
    observations::Array{Int,1}
end

function simulate(p::HMMExactSampler)
    x = hmm_posterior_sample(p.hmm, p.observations)
    log_weight = hmm_log_joint_probability(p.hmm, x, p.observations)
    (x, log_weight)
end

function regenerate(p::HMMExactSampler, x)
    hmm_log_joint_probability(p.hmm, x, p.observations)
end


text:
module TestDotEnv

using DotEnv

@static if VERSION < v"0.7.0-DEV.2005"
    using Base.Test
else
    using Test
end

println("Testing DotEnv")

const dir = dirname(@__FILE__)

# There is no "USER" variable on windows.
initial_value = haskey(ENV, "USER") ? ENV["USER"] : "WINDOWS"
ENV["USER"] = initial_value

@testset "basic" begin
    #basic input
    str = "BASIC=basic"
    file = joinpath(dir, ".env.override")
    file2 = joinpath(dir, ".env")

    #iobuffer, string, file
    @test DotEnv.parse(str) == Dict("BASIC"=>"basic")
    @test DotEnv.parse(read(file)) == Dict("CUSTOMVAL123"=>"yes","USER"=>"replaced value")
    @test DotEnv.config(file).dict == Dict("CUSTOMVAL123"=>"yes","USER"=>"replaced value")

    #should trigger a warning too, but I cant test that
    @test isempty(DotEnv.config("inexistentfile.env"))

    #length of returned values
    @test length(DotEnv.config(file2).dict) === 10

    #shouldn't replace ENV vars
    cfg = DotEnv.config(file)

    @test ENV["USER"] != cfg["USER"]
    @test ENV["USER"] == initial_value

    #appropiately loaded into ENV if CUSTOM_VAL is non existent
    @test ENV["CUSTOMVAL123"] == "yes"

    # Test that EnvDict is reading from ENV
    ENV["SOME_RANDOM_KEY"] = "abc"
    cfg = DotEnv.config(file)
    @test !haskey(cfg.dict, "SOME_RANDOM_KEY")
    @test cfg["SOME_RANDOM_KEY"] == "abc"
    @test get(cfg, "OTHER_RANDOM_KEY", "zxc") == "zxc"

    #test alias
    @test DotEnv.load(file).dict == DotEnv.config(file).dict
    @test DotEnv.load(; path = file).dict == DotEnv.config(file).dict
end

@testset "Override" begin
    #basic input
    file = joinpath(dir, ".env.override")

    # Can force override
    cfg = DotEnv.config(file, true)
    @test ENV["USER"] == cfg["USER"]
    @test ENV["USER"] == "replaced value"

    # Restore previous environment
    ENV["USER"] = initial_value
end

@testset "parsing" begin

    #comment
    @test DotEnv.parse("#HIMOM") == Dict()

    #spaces without quotes
    @test begin
        p = DotEnv.parse("TEST=hi  the  re")
        count(c -> c == ' ', collect(p["TEST"])) == 4
    end

    #single quotes
    @test DotEnv.parse("TEST=''")["TEST"] == ""
    @test DotEnv.parse("TEST='something'")["TEST"] == "something"

    #double quotes
    @test DotEnv.parse("TEST=\"\"")["TEST"] == ""
    @test DotEnv.parse("TEST=\"something\"")["TEST"] == "something"

    #inner quotes are mantained
    @test DotEnv.parse("TEST=\"\"json\"\"")["TEST"] == "\"json\""
    @test DotEnv.parse("TEST=\"'json'\"")["TEST"] == "'json'"
    @test DotEnv.parse("TEST=\"\"\"")["TEST"] == "\""
    @test DotEnv.parse("TEST=\"'\"")["TEST"] == "'"

    #line breaks
    @test DotEnv.parse("TEST=\"\\n\"")["TEST"] == "" #It's null because of final trim
    @test DotEnv.parse("TEST=\"\\n\\n\\nsomething\"")["TEST"] == "something"
    @test DotEnv.parse("TEST=\"something\\nsomething\"")["TEST"] == "something\nsomething"
    @test DotEnv.parse("TEST=\"something\\n\\nsomething\"")["TEST"] == "something\n\nsomething"
    @test DotEnv.parse("TEST='\\n'")["TEST"] == "\\n"
    @test DotEnv.parse("TEST=\\n")["TEST"] == "\\n"

    #empty vars
    @test DotEnv.parse("TEST=")["TEST"] == ""

    #trim spaces with and without quotes
    @test DotEnv.parse("TEST='  something  '")["TEST"] == "something"
    @test DotEnv.parse("TEST=\"  something  \"")["TEST"] == "something"
    @test DotEnv.parse("TEST=  something  ")["TEST"] == "something"
    @test DotEnv.parse("TEST=    ")["TEST"] == ""
end

end # module


text:
parse_board(b) = parse.(Int, (reduce(hcat, split.(b, " "; keepempty=false))))
function load(::Day{4}, path)
    lines = readlines(path)
    draws = parse.(Int, split(lines[1], ","))
    boards = [parse_board(lines[i:(i + 4)]) for i in 3:6:(length(lines) - 4)]
    return draws, boards
end

# Part 1
@inline is_win(check) = is_win_col(check) || is_win_row(check)
@inline is_win_col(check) = any(sum.(eachcol(check)) .== 5)
@inline is_win_row(check) = any(sum.(eachrow(check)) .== 5)

# Score board without multiplying by draw. Return 0 if not won.
@inline score(board, check) = is_win(check) ? sum(board[.!check]) : 0

# We don't really need any error-handling as the there are 100 draws,
# so the end of the game is guaranteed for any player
function solve1(::Day{4}, data) # winning score
    draws, boards = data
    checks = [zeros(Bool, 5, 5) for i in 1:length(boards)]
    @inbounds for draw in draws
        scores = map(zip(boards, checks)) do (b, c)
            c[findall(n -> n == draw, b)] .= true
            score(b, c)
        end
        if any(scores .> 0)
            return maximum(scores) * draw
        end
    end
end

# Part 2
# Luckily, we don't need to find the index of the board, just its score.
function solve2(::Day{4}, data) # last score
    draws, boards = data
    checks = [zeros(Bool, 5, 5) for i in 1:length(boards)]
    @inbounds for draw in draws
        scores = map(zip(boards, checks)) do (b, c)
            c[findall(n -> n == draw, b)] .= true
            score(b, c)
        end
        if all(scores .> 0)
            return minimum(scores) * draw
        else
            keep = findall(iszero, scores)
            boards = boards[keep]
            checks = checks[keep]
        end
    end
end

testresult1(::Day{4}) = 4512
testresult2(::Day{4}) = 1924


text:
"""
The output is in different form from the other functions
Here voxels are tranposed and faces are in 2-D array.
"""
function get_surface_grid_per_voxel(data3d::Array; voxelsize_mm::Array=[1,1,1])
    # Get vertices and count the voxesl (*4 face number)
    verts, nvoxels = LarSurf.vertices_and_count_voxels_as_the_square_face_preprocessing(data3d, voxelsize_mm)

    # Create square faces

    threshold = 0
    faces = LarSurf.create_square_faces(data3d, nvoxels, threshold)

    new_verts, new_faces = LarSurf.keep_surface_faces(verts, faces)

    verts = new_verts
    faces = new_faces

    return verts, faces

end

# function continue(verts, faces)
    # # Triangulation
    #
    # trifaces = LarSurf.triangulation(faces)
    #
    # # Visualization
    # LarSurf.check_vf(verts, trifaces)
    #
    # V, EV, FE = LarSurf.to_lar(verts, trifaces)
    #
    # EVc = Lar.cop2lar(EV)
    # Vnew = convert(Array, transpose(V))
    # VV = [i for i=1:length(Vnew)]
    # return Vnew, [VV, EV]
# end


text:
"""
Rule for game-of-life style cellular automata.
$(FIELDDOCTABLE)
"""
@description @limits @flattenable @default_kw struct Life{R,N,B,S} <: NeighborhoodRule{R}
    neighborhood::N | RadialNeighborhood{1}() | false | nothing | "Any Neighborhood"
    b::B | (3, 3) | true | (0, 8) | "Array, Tuple or Iterable of integers to match neighbors when cell is empty"
    s::S | (2, 3) | true | (0, 8) | "Array, Tuple or Iterable of integers to match neighbors cell is full"
end

Life(neighborhood::N, b::B, s::S) where {N,B,S} =
    Life{radius(neighborhood),N,B,S}(neighborhood, b, s)

"""
    rule(rule::Life, state)

Rule for game-of-life style cellular automata. This is a demonstration of
Cellular Automata more than a seriously optimised game of life rule.

Cells becomes active if it is empty and the number of neightbors is a number in
the b array, and remains active the cell is active and the number of neightbors is
in the s array.

Returns: boolean

## Examples (gleaned from CellularAutomata.jl)

```julia
# Life.
init = round.(Int64, max.(0.0, rand(-3.0:0.1:1.0, 300,300)))
output = REPLOutput{:block}(init; fps=10, color=:red)
sim!(output, rule, init; time=1000)

# Dimoeba
init = rand(0:1, 400, 300)
init[:, 100:200] .= 0
output = REPLOutput{:braile}(init; fps=25, color=:blue)
sim!(output, Ruleset(Life(b=(3,5,6,7,8), s=(5,6,7,8))), init; time=1000)

# Replicator
init = fill(1, 300,300)
init[:, 100:200] .= 0
init[10, :] .= 0
output = REPLOutput{:block}(init; fps=60, color=:yellow)
sim!(output, Ruleset(Life(b=(1,3,5,7), s=(1,3,5,7))), init; time=1000)
```

"""
applyrule(rule::Life, data, state, index, buf) = begin
    # Sum neighborhood
    cc = neighbors(rule.neighborhood, rule, buf, state)
    # Determine next state based on current state and neighborhood total
    counts = (rule.b, rule.s)[state+1]
    for i = 1:length(counts)
        if counts[i] == cc
            return oneunit(state)
        end
    end
    return zero(state)
end


text:
#
# acquisition.jl -
#
# Implements acquisition of images for Julia interface to ActiveSilicon Phoenix
# (PHX) library.
#
#------------------------------------------------------------------------------
#
# This file is part of the `Phoenix.jl` package which is licensed under the MIT
# "Expat" License.
#
# Copyright (C) 2017-2019, Éric Thiébaut (https://github.com/emmt/Phoenix.jl).
# Copyright (C) 2016, Éric Thiébaut & Jonathan Léger.
#

const SUCCESS = Cint(0)
const FAILURE = Cint(-1)

"""
    _offsetof(x::DataType, s::Symbol)

yields the byte offset of field `s` in structure `x`.  Beware that this is
slower than requested the offset by index.

"""
function _offsetof(::Type{T}, s::Symbol) where {T}
    for i in 1:nfields(T)
        if fieldname(T, i) == s
            return fieldoffset(T, i)
        end
    end
    throw(ArgumentError("type `$T` has no field `$s`"))
end

const _offsetof_context_cond      = _offsetof(AcquisitionContext, :cond)
const _offsetof_context_mutex     = _offsetof(AcquisitionContext, :mutex)
const _offsetof_context_imgbuf    = _offsetof(AcquisitionContext, :imgbuf)
const _offsetof_context_imgctx    = _offsetof(AcquisitionContext, :imgctx)
const _offsetof_context_index     = _offsetof(AcquisitionContext, :index)
const _offsetof_context_sec       = _offsetof(AcquisitionContext, :sec)
const _offsetof_context_usec      = _offsetof(AcquisitionContext, :usec)
const _offsetof_context_number    = _offsetof(AcquisitionContext, :number)
const _offsetof_context_overflows = _offsetof(AcquisitionContext, :overflows)
const _offsetof_context_synclosts = _offsetof(AcquisitionContext, :synclosts)
const _offsetof_context_pending   = _offsetof(AcquisitionContext, :pending)
const _offsetof_context_events    = _offsetof(AcquisitionContext, :events)

const _offsetof_framedata_sec     = _offsetof(FrameData, :sec)
const _offsetof_framedata_usec    = _offsetof(FrameData, :usec)
const _offsetof_framedata_index   = _offsetof(FrameData, :index)

@assert _offsetof_context_imgctx == _offsetof_context_imgbuf + sizeof(Ptr{Cvoid})
@assert _offsetof_context_usec == _offsetof_context_sec + sizeof(_typeof_tv_sec)

# similar to unsafe_load but re-cast pointer as needed.
@inline _load(::Type{T}, ptr::Ptr) where {T} =
    unsafe_load(Ptr{T}(ptr))

@inline _load(::Type{T}, ptr::Ptr{T}) where {T} =
    unsafe_load(ptr)

# similar to unsafe_store! but re-cast pointer as needed.
@inline _store!(::Type{T}, ptr::Ptr, val) where {T} =
    unsafe_store!(Ptr{T}(ptr), val)

@inline _store!(::Type{T}, ptr::Ptr{T}, val) where {T} =
    unsafe_store!(ptr, val)

@inline _increment!(::Type{T}, ptr::Ptr) where {T} =
    _increment!(T, Ptr{T}(ptr))

@inline _increment!(::Type{T}, ptr::Ptr{T}) where {T} =
    unsafe_store!(ptr, unsafe_load(ptr) + one(T))

@inline _decrement!(::Type{T}, ptr::Ptr) where {T} =
    _decrement!(T, Ptr{T}(ptr))

@inline _decrement!(::Type{T}, ptr::Ptr{T}) where {T} =
    unsafe_store!(ptr, unsafe_load(ptr) - one(T))

"""
Callback for acquisition.

This method does not use any Julia internals (unless the pointer
`_PHX_StreamRead[]` is incorrectly initialized) as you can figure out by
calling:

    code_native(Phoenix._callback, (Phoenix.Handle, UInt32, Ptr{Cvoid}))

which has only a call to `jl_throw` if the above mentioned pointer is
incorrect.  This callback is therefore thread safe.

"""
function _callback(handle::Handle, events::UInt32, ctx::Ptr{Cvoid})
    #ccall(:printf, Cint, (Cstring, Cuint, Ptr{Cvoid}),
    #      "_callback called events=0x%0x, ctx=0x%p\n", events, ctx)
    mutex = _load(Ptr{Cvoid}, ctx + _offsetof_context_mutex)
    cond  = _load(Ptr{Cvoid}, ctx + _offsetof_context_cond)
    if ccall(:pthread_mutex_lock, Cint, (Ptr{Cvoid},), mutex) == SUCCESS
        if (PHX_INTRPT_BUFFER_READY & events) != 0
            # A new frame is available.
            # Take its arrival time stamp.
            ccall(:gettimeofday, Cint, (Ptr{Cvoid}, Ptr{Cvoid}),
                  ctx + _offsetof_context_sec, C_NULL)
            # Get last captured image buffer.
            status = ccall(_PHX_StreamRead[],
                           Status, (Handle, Acq, Ptr{ImageBuff}),
                           handle, PHX_BUFFER_GET,
                           ctx + _offsetof_context_imgbuf)
            if status != PHX_OK
                # FIXME: this is not an overflow
                _increment!(Int, ctx + _offsetof_context_overflows)
            else
                # Store the index of the last captured image.
                imgctx = _load(Ptr{Cvoid}, ctx + _offsetof_context_imgctx)
                _store!(Int, ctx + _offsetof_context_index,
                        _load(Int, imgctx + _offsetof_framedata_index))
                # Store the time stamp.
                _store!(_typeof_tv_sec, imgctx + _offsetof_framedata_sec,
                        _load(_typeof_tv_sec, ctx + _offsetof_context_sec))
                _store!(_typeof_tv_usec, imgctx + _offsetof_framedata_usec,
                        _load(_typeof_tv_usec, ctx + _offsetof_context_usec))
                # Update counters.
                _increment!(Int, ctx + _offsetof_context_number)
                _increment!(Int, ctx + _offsetof_context_pending)
            end
        end
        if (PHX_INTRPT_FIFO_OVERFLOW & events) != 0
            # Fifo overflow.
            _increment!(Int, ctx + _offsetof_context_number)
            _increment!(Int, ctx + _offsetof_context_overflows)
        end
        if (PHX_INTRPT_SYNC_LOST & events) != 0
            # Synchronization lost.
            _increment!(Int, ctx + _offsetof_context_number)
            _increment!(Int, ctx + _offsetof_context_synclosts)
        end
        if (_load(UInt, ctx + _offsetof_context_events) & events) != 0
            # Signal condition for waiting thread.
            ccall(:pthread_cond_signal, Cint, (Ptr{Cvoid},), cond)
        end
        ccall(:pthread_mutex_unlock, Cint, (Ptr{Cvoid},), mutex)
    end
    return nothing
end

# Extend method.
wait(cam::Camera, timeout::Float64, drop::Bool) =
    wait(cam, TimeSpec(time() + timeout), drop)

# FIXME: Something not specified in the doc. is that, when continuous
# acquisition and blocking mode are both enabled, all calls to `PHX_BUFFER_GET`
# yield the same image buffer until `PHX_BUFFER_RELEASE` is called.  It seems
# that there is no needs to have a `PHX_BUFFER_GET` matches a
# `PHX_BUFFER_RELEASE` and that every `PHX_BUFFER_RELEASE` moves to the next
# buffer.  However, acquisition buffers are used in their given order so it is
# not too difficult to figure out where we are if we count the number of
# frames.
#

function wait(cam::Camera, timeout::TimeSpec, drop::Bool)
    # Check state.
    if cam.state != 2
        if cam.state == 0 || cam.state == 1
            error("acquisition has not been started")
        else
            error("camera instance corrupted")
        end
    end

    # Because we cannot throw anything while the mutex is locked, we defer
    # reporting of error and use the following variables to keep track of what
    # happens while the mutex was locked.
    #
    # `index` is the index of the next image buffer to process, 0 if there
    #         are none, -1 if there have been some errors;
    #
    # `errname` is the identifier of the origin of the failure to return a new
    #         image buffer to process;
    #
    # `errcode` is the associated error code (may be: a Phoenix status or a
    #         POSIX thread error code);
    local index::Int = 0 # index of frame to process if any
    local errname::Symbol = Symbol()
    local errcode::Int    = 0
    imgbuf = Ref{ImageBuff}()
    ctx = cam.context # shortcut

    # Lock mutex and wait for next image, taking care to not throw anything
    # while the mutex is locked.
    code = ccall(:pthread_mutex_lock, Cint, (Ptr{Cvoid},), ctx.mutex)
    if code != SUCCESS
        index, errname, errcode = -1, :lock, Int(code)
    else
        # While there are no pending frames, wait for the condition to be
        # signaled or an error to occur.  This is done in a `while` loop to
        # cope with spurious signaled conditions.
        while ctx.pending == 0
            # This code is prepared to face spurious signaled conditions.
            if isforever(timeout)
                code = ccall(:pthread_cond_wait, Cint,
                             (Ptr{Cvoid}, Ptr{Cvoid}),
                             ctx.cond, ctx.mutex)
                if code != SUCCESS
                    index, errname, errcode = -1, :wait, Int(code)
                    break
                end
            else
                code = ccall(:pthread_cond_timedwait, Cint,
                             (Ptr{Cvoid}, Ptr{Cvoid}, Ptr{TimeSpec}),
                             ctx.cond, ctx.mutex, Ref(timeout))
                if code != SUCCESS
                    index, errname, errcode = -1, :timedwait, Int(code)
                    break
                end
            end
        end
        if index ≥ 0 && drop
            # If no errors occured so far, get rid of unprocessed pending image
            # buffers.
            while ctx.pending > 1
                status = _readstream(cam, PHX_BUFFER_RELEASE, C_NULL)
                if status != PHX_OK
                    index, errname, errcode = -1, :releasebuffer, Int(status)
                    break
                end
                ctx.pending -= 1
                ctx.overflows += 1
            end
        end
        if index ≥ 0 && ctx.pending ≥ 1
            # If no errors occured so far and at least one image buffer is
            # unprocessed, manage to return the index of this buffer.
            ctx.pending -= 1
            index = ctx.index - ctx.pending
            if index ≤ 0
                index += length(cam.imgs)
            end
        end
        # Unlock the mutex (whatever the errors so far).
        code = ccall(:pthread_mutex_unlock, Cint, (Ptr{Cvoid},), ctx.mutex)
        if code != SUCCESS && index ≥ 0
            index, errname, errcode = -1, :unlock, Int(code)
        end
    end

    # Mutex has been unlocked, report errors if any.
    if index ≤ 0
        if errname == :timedwait && errcode == Libc.ETIMEDOUT
            throw(TimeoutError())
        end
        msg = (errname == :lock ?
               "failed to lock mutex" :
               errname == :unlock ?
               "failed to unlock mutex" :
               errname == :wait || errname == :timedwait ?
               "failed to wait for condition" :
               errname == :getbuffer ?
               "failed to get image buffer [$(geterrormessage(errcode))]" :
               errname == :releasebuffer ?
               "failed to release image buffer [$(geterrormessage(errcode))]" :
               "some error occured while waiting for next frame [$errname, $errcode]")
        error(msg)
    end

    # Retrieve time stamp of last frame and fix registered time stamp to be
    # (approximately) that of the previous frame.
    ticks = cam.ctxs[index].sec + cam.ctxs[index].usec*1E-6
    return (cam.imgs[index], ticks)
end

# Extend method.
function read(cam::Camera, ::Type{T}, num::Int;
              skip::Integer = 0,
              timeout::Real = defaulttimeout(cam),
              truncate::Bool = false) where {T}
    # Check arguments.
    num ≥ 1 || throw(ArgumentError("invalid number of images"))
    skip ≥ 0 || throw(ArgumentError("invalid number of images to skip"))
    timeout > zero(timeout) || throw(ArgumentError("invalid timeout"))

    # Start acquisition with given callback and collect images.
    imgs = Vector{Array{T,2}}(undef, num)
    cnt = 0
    start(cam, T, num + 1) # FIXME: hack to avoid loosing one frame
    while cnt < num
        try
            img, ticks = wait(cam, timeout, false)
            if skip > zero(skip)
                # Skip this frame.
                skip -= one(skip)
                release(cam)
            else
                # Store this frame.
                cnt += 1
                imgs[cnt] = img
                release(cam)
            end
        catch err
            if truncate && isa(err, TimeoutError)
                @warn "Acquisition timeout after $cnt image(s)"
                num = cnt
                resize!(imgs, num)
            else
                abort(cam)
                rethrow(err)
            end
        end
    end

    # Stop immediately.
    abort(cam)

    # Return images.
    return imgs
end

# Extend method.
function read(cam::Camera, ::Type{T};
              skip::Integer = 0,
              timeout::Real = defaulttimeout(cam)) where {T}
    # Check arguments.
    skip ≥ 0 || throw(ArgumentError("invalid number of images to skip"))
    timeout > zero(timeout) || throw(ArgumentError("invalid timeout"))

    # Acquire a single image.
    start(cam, T, (skip > zero(skip) ? 2 : 1))
    while true
        try
            img, ticks = wait(cam, timeout, false)
            if skip > zero(skip)
                # Skip this frame.
                skip -= one(skip)
                release(cam)
            else
                # Stop immediately and return image.
                abort(cam)
                return img
            end
        catch err
            abort(cam)
            rethrow(err)
        end
    end
end

# Extend method.
function getcapturebitstype(cam::Camera)
    bufpix = capture_format(cam[PHX_DST_FORMAT])
    T = equivalentbitstype(bufpix)
    return (T == Nothing ? UInt8 : T)
end

# Extend method.
release(cam::Camera) =
    readstream(cam, PHX_BUFFER_RELEASE, C_NULL)

#
# Allocates image buffers for acquisition with camera `cam` and start
# continuous acquisition.
#
# On entry, it is assumed that the frame grabber configuration is consistent
# with the camera settings.  In particular:
#
# * The size of the region of interest (ROI) to capture is given by parameters
#   `PHX_ROI_XLENGTH` and `PHX_ROI_YLENGTH`.
#
# * The pixel format of the captured image is given by the parameter
#   `PHX_DST_FORMAT`.
#
# On exit, `nbufs` image buffers of type `T` are allocated and referenced by
# `cam`, their size as small as possible but sufficient to store the captured
# ROI and the following parameters are updated accordingly:
#
# * `PHX_ROI_DST_XOFFSET` and `PHX_ROI_DST_YOFFSET` are both set to 0.
#
# * `PHX_BUF_DST_XLENGTH` is set to the number of bytes per row of the ROI and
#   `PHX_BUF_DST_YLENGTH` is set to the number of rows in the ROI.
#
# * `PHX_ACQ_IMAGES_PER_BUFFER`, `PHX_ACQ_BUFFER_START` and
#   `PHX_COUNT_BUFFER_READY` are all set to `1`.
#
# * `PHX_ACQ_NUM_BUFFERS` (alias `PHX_ACQ_NUM_IMAGES`) is set to `nbufs` while
#   `PHX_DST_PTRS_VIRT` and `PHX_DST_PTR_TYPE` are set to require the frame
#   grabber to use the provided image buffers.
#
function start(cam::Camera, ::Type{T}, nbufs::Int = 4) where {T}
    # Check arguments.
    if cam.state != 1
        if cam.state == 0
            error("camera must be open")
        elseif cam.state == 2
            error("acquisition must not be running")
        else
            error("camera instance corrupted")
        end
    end
    nbufs ≥ 1 || throw(ArgumentError("invalid number of image buffers"))

    _debug(cam, "abort acquisition...")
    readstream(cam, PHX_ABORT, C_NULL)
    _stophook(cam)

    _debug(cam, "set acquisition parameters...")

    # FIXME: Benchmark this to see whether it is worth avoiding recreating the
    #        virtual buffers.

    # Figure out buffer size.
    width  = Int(cam[PHX_ROI_XLENGTH])
    height = Int(cam[PHX_ROI_YLENGTH])
    if width < 1 || height < 1
        error("invalid ROI dimension(s) (`PHX_ROI_XLENGTH`, `PHX_ROI_YLENGTH`)")
    end
    dstbits = capture_format_bits(cam[PHX_DST_FORMAT])
    if dstbits ≤ 0
        error("invalid capture pixel format (`PHX_DST_FORMAT`)")
    end
    arrbits = sizeof(T)*8
    if arrbits != dstbits
        @warn "capture format does not exactly fit in chosen pixel type"
    end
    width = div(width*dstbits + arrbits - 1, arrbits) # roundup array width
    cam[PHX_ROI_DST_XOFFSET] = 0
    cam[PHX_ROI_DST_YOFFSET] = 0
    cam[PHX_BUF_DST_XLENGTH] = width*sizeof(T)
    cam[PHX_BUF_DST_YLENGTH] = height

    # Allocate image buffers.
    imgs = [zeros(T, width, height) for i in 1:nbufs]
    ctxs = [FrameData(0, 0, i) for i in 1:nbufs]
    bufs = [i ≤ nbufs ?
            ImageBuff(pointer(imgs[i]),
                      pointer(ctxs) + (i - 1)*sizeof(FrameData)) :
            ImageBuff(C_NULL, C_NULL) for i in 1:nbufs+1]

    # Instruct Phoenix to use the virtual buffers. The PHX_CACHE_FLUSH here is
    # to make sure that the new buffers do replace the old ones, if any, before
    # they may be claimed by the garbage collector.  (FIXME: I am not sure
    # whether this is really needed and I do not known the effects of the
    # `PHX_FORCE_REWRITE` flag.)
    cam[PHX_ACQ_IMAGES_PER_BUFFER] = 1
    cam[PHX_ACQ_BUFFER_START]      = 1
    cam[PHX_ACQ_NUM_BUFFERS]       = nbufs
    cam[PHX_DST_PTRS_VIRT]         = bufs
    cam[(PHX_DST_PTR_TYPE|PHX_CACHE_FLUSH|
         PHX_FORCE_REWRITE)] = PHX_DST_PTR_USER_VIRT

    # Store image buffers and metadata in camera instance to prevent claim by
    # garbage collector.
    cam.imgs = imgs
    cam.ctxs = ctxs
    cam.bufs = bufs # FIXME: Not sure this is needed if the above has immediate
                    #        effects.  We can check this by not setting this
                    #        reference, call the garbage collector and attempt
                    #        acquisition, the result should be quite obvious...

    # Configure frame grabber for continuous acquisition and enable interrupts
    # for expected events.
    cam[PHX_ACQ_BLOCKING]       = PHX_ENABLE
    cam[PHX_ACQ_CONTINUOUS]     = PHX_ENABLE
    cam[PHX_COUNT_BUFFER_READY] = 1
    cam[PHX_INTRPT_CLR]         = ~zero(ParamValue)
    cam[PHX_INTRPT_SET]         = (PHX_INTRPT_GLOBAL_ENABLE |
                                   PHX_INTRPT_FIFO_OVERFLOW |
                                   PHX_INTRPT_SYNC_LOST |
                                   PHX_INTRPT_BUFFER_READY)

    # Configure acquisition context.
    cam.context.imgbuf    = C_NULL
    cam.context.imgctx    = C_NULL
    cam.context.index     = 0
    cam.context.sec       = 0
    cam.context.usec      = 0
    cam.context.number    = 0
    cam.context.overflows = 0
    cam.context.synclosts = 0
    cam.context.pending   = 0
    cam.context.events    = PHX_INTRPT_BUFFER_READY;
    cam[PHX_EVENT_CONTEXT] = Ref(cam.context)

    # Explicitly flush configuration even though this is automatically done by
    # the readstream() command.
    _debug(cam, "flush cache...")
    flushcache(cam)

    # Start acquisition with our own callback.
    _debug(cam, "start acquisition...")
    readstream(cam, PHX_START, _CALLBACK_REF[])

    # Send specific start command, aborting acquisition in case of errors.
    _debug(cam, "apply start hook...")
    try
        _starthook(cam)
    catch err
        _readstream(cam, PHX_ABORT, C_NULL)
        _readstream(cam, PHX_UNLOCK, C_NULL)
        rethrow(err)
    end

    # Finally, set camera state.
    _debug(cam, "OK acquisition started")
    cam.state = 2
    return nothing
end

"""
    stop(cam)

stops acquisition by camera `cam` after current image.

See also: [`abort`](@ref), [`start`](@ref), [`_stophook`](@ref).

"""
stop(cam::Camera) = _stop(cam, PHX_STOP)

"""
    abort(cam)

aborts acquisition by camera `cam` without waiting for current image.

See also: [`stop`](@ref), [`start`](@ref).

"""
abort(cam::Camera) = _stop(cam, PHX_ABORT)

function _stop(cam::Camera, cmd::Acq)
    if cam.state == 0
        error("camera must be open")
    elseif cam.state == 1
        @warn "no acquisition is running"
    elseif cam.state == 2
        # Stop/abort acquisition.
        status = _readstream(cam, cmd, C_NULL)
        if status != PHX_OK
            @warn string("Failure in ", :PHX_StreamRead, " with ",
                         (cmd == PHX_STOP  ? :PHX_STOP :
                          cmd == PHX_ABORT ? :PHX_ABORT : cmd),
                         " :\n         ", geterrormessage(status))
        end
        # Unlock all buffers.
        status = _readstream(cam, PHX_UNLOCK, C_NULL)
        if status != PHX_OK && status != PHX_ERROR_NOT_IMPLEMENTED
            @warn string("Failure in ", :PHX_StreamRead, " with ",
                         :PHX_UNLOCK, ":\n         ",
                         geterrormessage(status))
        end
        # Call specific stop command.
        try
            _stophook(cam)
        catch err
            rethrow(err)
        finally
            cam.state = 1
        end
    else
        error("camera instance corrupted")
    end
    return nothing
end

"""

`_starthook(cam)` is called to perform specific actions for starting
acquisition.  This function should return nothing but may throw exceptions to
signal errors.

See also: [`start`](@ref), [`_stophook`](@ref).

"""
_starthook(::Camera) = nothing

"""

`_stophook(cam)` is called to perform specific actions for stopping
acquisition.  This function should return nothing but may throw exceptions to
signal errors.

See also: [`stop`](@ref), [`_starthook`](@ref).

"""
_stophook(::Camera) = nothing


text:
# Demand response.

#=
WORK IN PROGRESS

See https://github.com/NREL/PowerSystems.jl/tree/demand-response/docs/src/man/demand.svg
for a type diagram.

In order to handle PHEVs, buildings, home appliances, industrial facilities,
etc., in addition to BEVs, serveral new types and subtypes will be introduced.
The organization of `FlexibleDemand` will change, but its numerical content will
remain the same.

There are really four types of demands:
1.  Inflexible, just a fixed timeseries.
2.  Flexible, without storage, like an industrial facility, that can reduce its
    production in response to price signals or contractual conditions.
3.  Flexible, with storage and its own generation, like a PHEV or a building
    with CHP, that can adjust its demand and shift to other energy sources.
4.  Constrained, dependent on storage, like a BEV, that can adjust its demand but
    has no other source of energy.

We'll probably end up with types along the following lines:
*   InflexibleDemand, FlexibleDemand, ConstrainedDemand
*   BEV, PHEV, CHP, . . .
Type-specific methods will specialize the behavior of the types of demands.

Locations will be mappable to Bus and demands will be mappable to
PowerSystems.StaticLoad and PowerSystems.InterruptibleLoad.
=#

# Abstract.

include("demand/demand.jl")
include("demand/inflexible.jl")
include("demand/flexible.jl")

# Concrete.

include("demand/stationary_inflexible.jl")
include("demand/interruptible.jl")
include("demand/bev_demand.jl")


text:
# AUTO GENERATED FILE - DO NOT EDIT

export multiselectfilterable

"""
    multiselectfilterable(;kwargs...)

A MultiSelectFilterable component.
MultiSelect
Keyword arguments:
- `disabled` (Bool; optional): Disable the control
- `style` (Dict; optional)
- `locale` (String; optional): Specify the locale of the control.
Used for the default compareItems used for sorting the list of items in the control.
- `light` (Bool; optional): true to use the light version.
- `selectionFeedback` (a value equal to: 'top', 'fixed', 'top-after-reopen'; optional): Specify feedback (mode) of the selection.
top: selected item jumps to top
fixed: selected item stays at it's position
top-after-reopen: selected item jump to top after reopen dropdown
default top-after-reopen
- `direction` (a value equal to: 'bottom, top'; optional): Specify the direction of the multiselect dropdown. Can be either top or bottom.
default bottom
- `id` (String; required): Id of the element
- `invalid` (Bool; optional): Is the current selection invalid.
- `invalidText` (String; optional): The text to show if it is invalid.
- `options` (required): List of items. options has the following type: Array of String | lists containing elements 'label', 'value'.
Those elements have the following types:
  - `label` (String; optional)
  - `value` (Bool | Real | String | Dict | Array; optional)s
- `label` (String; optional): Generic label that will be used as the textual representation of what this field is for
- `size` (a value equal to: 'sm', 'lg', 'xl'; optional): Specify the size of the ListBox. Currently supports either sm, lg or xl as an option.
- `titleText` (String; optional): Provide text to be used in a <label> element that is tied to the multiselect via ARIA attributes.
- `value` (Array of Bool | Real | String | Dict | Arrays; optional): The list of the selected items
"""
function multiselectfilterable(; kwargs...)
        available_props = Symbol[:disabled, :style, :locale, :light, :selectionFeedback, :direction, :id, :invalid, :invalidText, :options, :label, :size, :titleText, :value]
        wild_props = Symbol[]
        return Component("multiselectfilterable", "MultiSelectFilterable", "dash_carbon_components", available_props, wild_props; kwargs...)
end

max_stars_repo_name: Matheus-Rangel/dash-carbon-components

max_issues_repo_name: Matheus-Rangel/dash-carbon-components

max_forks_repo_name: Matheus-Rangel/dash-carbon-components


text:
using Distributed
addprocs()

using MLJBase
if !MLJBase.TESTING
    error("To test MLJBase, the environment variable "*
          "`TEST_MLJBASE` must be set to `\"true\"`\n"*
          "You can do this in the REPL with `ENV[\"TEST_MLJBASE\"]=\"true\"")
end

@info "nprocs() = $(nprocs())"
@static if VERSION >= v"1.3.0-DEV.573"
    import .Threads
    @info "nthreads() = $(Threads.nthreads())"
else
    @info "Running julia $(VERSION). Multithreading tests excluded. "
end

@everywhere begin
    using MLJModelInterface
    using MLJBase
    using Test
    using CategoricalArrays
    using Logging
    using ComputationalResources
    using StableRNGs
end

import TypedTables
using Tables

function include_everywhere(filepath)
    include(filepath) # Load on Node 1 first, triggering any precompile
    if nprocs() > 1
        fullpath = joinpath(@__DIR__, filepath)
        @sync for p in workers()
            @async remotecall_wait(include, p, fullpath)
        end
    end
end

include("test_utilities.jl")

# load Models module containing model implementations for testing:
print("Loading some models for testing...")
include_everywhere("_models/models.jl")
print("\r                                           \r")

@testset "misc" begin
   @test include("utilities.jl")
   @test include("static.jl")
end

@testset "interface" begin
    @test include("interface/interface.jl")
    @test include("interface/data_utils.jl")
end

@testset "univariate finite" begin
    @test include("univariate_finite/methods.jl")
    @test include("univariate_finite/arrays.jl")
end

@testset "measures" begin
    @test include("measures/measures.jl")
    @test include("measures/measure_search.jl")
end

@testset "resampling" begin
    @test include("resampling.jl")
end

@testset "data" begin
    @test include("data/data.jl")
    @test include("data/datasets.jl")
    @test include("data/datasets_synthetic.jl")
end

@testset "sources" begin
    @test include("sources.jl")
end

@testset "machines" begin
    @test include("machines.jl")
end

@testset "composition - learning_networks" begin
    @test include("composition/learning_networks/nodes.jl")
    @test include("composition/learning_networks/inspection.jl")
    @test include("composition/learning_networks/machines.jl")
    # VERSION ≥ v"1.3.0-" &&
    #     @test include("composition/learning_networks/arrows.jl")
end

@testset "composition - models" begin
    @test include("composition/models/methods.jl")
    @test include("composition/models/from_network.jl")
    @test include("composition/models/inspection.jl")
    @test include("composition/models/pipelines.jl")
    @test include("composition/models/pipelines2.jl")
    @test include("composition/models/stacking.jl")
    @test include("composition/models/_wrapped_function.jl")
    @test include("composition/models/static_transformers.jl")
end

@testset "operations.jl" begin
    @test include("operations.jl")
end

@testset "hyperparam" begin
    @test include("hyperparam/one_dimensional_ranges.jl")
    @test include("hyperparam/one_dimensional_range_methods.jl")
end


text:
"""
Use input srcwav to fill wavelets and returns frequency bounds.
"""
function fill_wavelets!(ipw, iss, wavelets, srcwav, sflags)

    nt = size(wavelets, 1)
    sfields = names(srcwav[ipw][iss].d)[1]
    ns = srcwav[ipw][iss][:ns]
    δt = step(srcwav[ipw][iss].grid)

    freqmin = 0.0
    freqpeaks= []
    freqmax = Inf
    for sfield in sfields
        for is = 1:ns
            snt = length(srcwav[ipw][1].grid)
            if (sflags[ipw] == 0)
                # nothing # just put zeros, no sources added
                for it = 1:nt
                    wavelets[it][sfield][is] = 0.0
                end
            elseif (sflags[ipw] == 1)
                "ϕ[t] = s[t]"
                for it = 1:snt
                    source_term = srcwav[ipw][iss].d[sfield][it, is]
                    wavelets[it][sfield][is] = source_term
                end
            elseif (sflags[ipw] == -1)
                "source sink for 1"
                "ϕ[t] = -s[t]"
                for it = 2:snt
                    source_term = srcwav[ipw][iss].d[sfield][it, is]
                    wavelets[nt-it+2][sfield][is] = -1.0 * source_term
                end
            elseif (sflags[ipw] == 2)
                "ϕ[t] = ∑₁ᵗ⁻¹ s[t]"
                source_term_stack = 0.0
                if (sfield == :p)
                    for it = 1:snt-1
                        source_term_stack += (srcwav[ipw][iss].d[sfield][it, is] .* δt)
                        wavelets[it+1][sfield][is] = source_term_stack
                    end
                else
                    for it = 2:snt-1
                        source_term_stack += (
                            (
                                (srcwav[ipw][iss].d[sfield][it, is] .* δt) +
                                (srcwav[ipw][iss].d[sfield][it-1, is] .* δt)
                            ) * 0.5
                        )
                        wavelets[it+1][sfield][is] = source_term_stack
                    end

                end
                if (nt > snt)
                    wavelets[snt+1:end][sfield][is] = wavelets[snt][sfield][is]
                end
            elseif (sflags[ipw] == -2)
                "source sink for 2"
                # multiplication with -1 for subtraction #time reversal
                # as the source wavelet has to be subtracted before the propagation step, I shift here by one sample"
                source_term_stack = 0.0
                for it = 1:snt-1
                    source_term_stack += (srcwav[ipw][iss].d[sfield][it, is] .* δt)
                    wavelets[nt-it+1][sfield][is] = -1.0 * source_term_stack
                end
                if (nt > snt)
                    nt_diff = nt - snt
                    wavelets[1:nt_diff+1][sfield][is] = wavelets[nt_diff+2][sfield][is]
                end
            end
            w = [wavelets[it][sfield][is] for it = 1:nt]
            freqmax = min(
                GeoPhyInv.Utils.findfreq(w, srcwav[ipw][iss].grid, attrib = :max),
                freqmax,
            )
            freqmin = max(
                GeoPhyInv.Utils.findfreq(w, srcwav[ipw][iss].grid, attrib = :min),
                freqmin,
            )
            push!(freqpeaks,GeoPhyInv.Utils.findfreq(w, srcwav[ipw][iss].grid, attrib = :peak))
        end
    end
    return freqmin, freqmax, Statistics.mean(freqpeaks)
end

# This routine ABSOLUTELY should not allocate any memory, called inside time loop.
@inbounds @fastmath function add_source!(it::Int64, issp::Int64, iss::Int64, pac, pap)
    # aliases
    ageom = pac.ageom
    """
    adding source to pressure field at [it]
    """
    for ipw in pac.activepw
        p = pap[ipw].w1[:t]
        wavelets = pap[ipw].ss[issp].wavelets
        sindices = pap[ipw].ss[issp].sindices
        ssprayw = pap[ipw].ss[issp].ssprayw
        sfields = pac.sfields[ipw]
        if (pac.sflags[ipw] ≠ 0) # only if sflags is non-zero
            for sfield in sfields
                @simd for is = 1:ageom[ipw][iss].ns
                    """
                    use wavelets at [it], i.e., sum of source terms
                    until [it-1]
                    division of source term with δx and δz (see Jan's fdelmodc manual)
                    """
                    source_term =
                        wavelets[it][sfield][is] *
                        pac.fc[:dt] *
                        prod(inv.(step.(pac.medium.mgrid)))

                    for (i, si) in enumerate(sindices[sfield][is])
                        p[sfield][si] +=
                            source(source_term, ssprayw[sfield][is][i], pac, si, eval(sfield)())
                    end
                end
            end
        end
    end
end

# multiplication with modK
# on pressure grid
source(source_term, spray, pac::P_common{FdtdAcou}, si, ::p) =
    source_term * spray * pac.mod[:K][si]

# on vx grid
source(source_term, spray, pac::P_common{FdtdAcou}, si, ::vx) = source_term * spray #* pac.mod[:rhovxI][si]
source(source_term, spray, pac::P_common{FdtdElastic}, si, ::vx) = source_term * spray #* pac.mod[:rhovxI][si]

# on vz grid
source(source_term, spray, pac::P_common{FdtdAcou}, si, ::vz) = source_term * spray #* pac.mod[:rhovzI][si]
source(source_term, spray, pac::P_common{FdtdElastic}, si, ::vz) = source_term * spray #* pac.mod[:rhovzI][si]

# testing source on tauxx (need to check it)
source(source_term, spray, pac::P_common{FdtdElastic}, si, ::tauxx) =
    source_term * spray * 10^14
source(source_term, spray, pac::P_common{FdtdElastic}, si, ::tauyy) =
    source_term * spray * 10^14


text:
module ExtendedIntegers

export FlexibleUInt, FixedUInt

using Base: BitUnsigned, front, tail, fill_to_length, setindex

include("bits.jl")
include("vectors.jl")
include("tuples.jl")

## FixedUInt
##============
struct FixedUInt{N,U<:BitUnsigned} <: Unsigned
    parts::NTuple{N,U}
end
function FixedUInt{N,U}(a::BitUnsigned) where {N, U<:BitUnsigned}
    t = fill_to_length((), zero(U), Val{N})
    t = _tfill(t, a)
    return FixedUInt{N,U}(t)
end
FixedUInt{N,U}(a::FixedUInt{N,U}) where {N, U<:BitUnsigned} = a

function Base.show(io::IO, a::FixedUInt{N}) where {N}
    print(io,"0x")
    for k = N:-1:1
        print(io, " ", repr(a.parts[k])[3:end])
    end
end

Base.promote_rule(F::Type{<:FixedUInt}, ::Type{<:Signed}) = F
Base.promote_rule(F::Type{<:FixedUInt}, ::Type{<:BitUnsigned}) = F
Base.promote_rule(::Type{FixedUInt{N,U1}}, ::Type{FixedUInt{N,U2}}) where {N,U1<:BitUnsigned,U2<:BitUnsigned} = FixedUInt{N,promote_type(U1,U2)}
Base.@pure Base.promote_rule(::Type{FixedUInt{N1,U}}, ::Type{FixedUInt{N2,U}}) where {N1,N2,U<:BitUnsigned} = FixedUInt{max(N1,N2),U}

Base.convert(::Type{F}, a::F) where {F<:FixedUInt} = a
Base.convert(F::Type{<:FixedUInt}, a::Unsigned) = F(a)
Base.convert(F::Type{<:FixedUInt}, a::Signed) = F(convert(Unsigned, a))
function Base.convert(::Type{U}, a::FixedUInt{N, V}) where {U<:BitUnsigned, N, V<:BitUnsigned}
    b = zero(U)
    x = a.parts
    shift = unsigned(0)
    for k = 1:N
        db = convert(U, x[k])
        leading_zeros(db) < shift && throw(InexactError())
        b += (db << shift)
        shift += fullshift(V)
    end
    return b
end
function Base.convert(::Type{BigInt}, a::FixedUInt{N, V}) where {N, V<:BitUnsigned}
    b = zero(BigInt)
    x = a.parts
    shift = unsigned(0)
    for k = 1:N
        db = convert(BigInt, x[k])
        b += (db << shift)
        shift += fullshift(V)
    end
    return b
end

# zero and one
Base.iszero(a::FixedUInt) = all(iszero, a.parts)
Base.zero(::Type{FixedUInt{N, U}}) where {N, U<:BitUnsigned} =
    FixedUInt{N, U}(fill_to_length((), zero(U), Val{N}))
Base.one(::Type{FixedUInt{N, U}}) where {N, U<:BitUnsigned} =
    FixedUInt{N, U}(fill_to_length((one(U),), zero(U), Val{N}))

# comparison
Base.:<(a1::F, a2::F) where {F<:FixedUInt} = _tcmp(a1.parts, a2.parts) < 0
Base.:<=(a1::F, a2::F) where {F<:FixedUInt} = _tcmp(a1.parts, a2.parts) <= 0

# bit manipulation
Base.:<<(a::F, n::UInt) where {F<:FixedUInt} = F(_tleftshift(a.parts, n))
Base.:>>(a::F, n::UInt) where {F<:FixedUInt} = F(_trightshift(a.parts, n))
Base.:>>>(a::FixedUInt, n::UInt) = >>(a, n)
Base.:&(a1::F, a2::F) where {F<:FixedUInt} = F(_tand(a1.parts, a2.parts))
Base.:|(a1::F, a2::F) where {F<:FixedUInt} = F(_tor(a1.parts, a2.parts))
Base.:~(a::FixedUInt) = F(_tnot(a.parts))

# arithmitic
Base.:+(a1::F, a2::F) where {F<:FixedUInt} = F(_tadd(a1.parts, a2.parts))
Base.:-(a1::F, a2::F) where {F<:FixedUInt} = F(_tsub(a1.parts, a2.parts))
Base.:*(a1::F, a2::F) where {F<:FixedUInt} = F(_tmul(a1.parts, a2.parts))
function Base.divrem(n::F, d::F) where {F<:FixedUInt}
    q, r = _tdivrem(n.parts, d.parts)
    return F(q), F(r)
end

## FlexibleUInt
##===============
struct FlexibleUInt{U<:BitUnsigned} <: Unsigned
    parts::Vector{U}
end
function FlexibleUInt{U}(a::BitUnsigned) where {U<:BitUnsigned}
    x = U[]
    while !iszero(a)
        push!(x, convert(U, a & typemax(U)))
        a >>= fullshift(U)
    end
    return FlexibleUInt{U}(x)
end
FlexibleUInt{U}(a::FlexibleUInt{U}) where {U<:BitUnsigned} = a
function Base.show(io::IO, a::FlexibleUInt)
    print(io,"0x")
    for k = length(a.parts):-1:1
        print(io, " ", repr(a.parts[k])[3:end])
    end
end

Base.promote_rule(F::Type{<:FlexibleUInt}, ::Type{<:Signed}) = F
Base.promote_rule(F::Type{<:FlexibleUInt}, ::Type{<:BitUnsigned}) = F
Base.promote_rule(::Type{FlexibleUInt{U1}}, ::Type{FlexibleUInt{U2}}) where {U1<:BitUnsigned,U2<:BitUnsigned} = FlexibleUInt{promote_type(U1,U2)}

Base.convert(::Type{F}, a::F) where {F<:FlexibleUInt} = a
Base.convert(F::Type{<:FlexibleUInt}, a::Unsigned) = F(a)
Base.convert(F::Type{<:FlexibleUInt}, a::Signed) = F(convert(Unsigned, a))
function Base.convert(::Type{U}, a::FlexibleUInt{V}) where {U<:BitUnsigned, V<:BitUnsigned}
    b = zero(U)
    x = a.parts
    shift = unsigned(0)
    for k = 1:length(x)
        db = convert(U, x[k])
        leading_zeros(db) < shift && throw(InexactError())
        b += (db << shift)
        shift += fullshift(V)
    end
    return b
end

# zero and one
Base.iszero(a::FlexibleUInt) = length(a.parts) == 0 # quick test
Base.zero(::Type{FlexibleUInt{U}}) where {U<:BitUnsigned} = FlexibleUInt{U}(U[])
Base.one(::Type{FlexibleUInt{U}}) where {U<:BitUnsigned} = FlexibleUInt{U}([one(U)])

# comparison
Base.:<(a1::FlexibleUInt{U}, a2::FlexibleUInt{U}) where {U<:Unsigned} = _vcmp(a1.parts, a2.parts) < 0
Base.:<=(a1::FlexibleUInt{U}, a2::FlexibleUInt{U}) where {U<:Unsigned} = _vcmp(a1.parts, a2.parts) <= 0
Base.:(==)(a1::FlexibleUInt{U}, a2::FlexibleUInt{U}) where {U<:Unsigned} = a1.parts == a2.parts

# bit manipulation
Base.:<<(a::F, n::UInt) where {F<:FlexibleUInt} = F(_vleftshift!(copy(a.parts), n))
Base.:>>(a::F, n::UInt) where {F<:FlexibleUInt} = F(_vrightshift!(copy(a.parts), n))
Base.:>>>(a::FlexibleUInt, n::UInt) = >>(a, n)
Base.:&(a1::F, a2::F) where {F<:FlexibleUInt} =
    length(a1.parts) > length(a2.parts) ? F(_vand!(copy(a2.parts), a1.parts)) :
                                            F(_vand!(copy(a1.parts), a2.parts))
Base.:|(a1::F, a2::F) where {F<:FlexibleUInt} =
    length(a1.parts) > length(a2.parts) ? F(_vor!(copy(a1.parts), a2.parts)) :
                                            F(_vor!(copy(a2.parts), a1.parts))

function Base.trailing_zeros(a::FlexibleUInt)
    isempty(a.parts) && return InexactError() # behavior of BigInt
    numzeros = 0
    k = 1
    @inbounds while iszero(a.parts[k])
        numzeros += trailing_zeros(a.parts[k])
        k += 1
    end
    numzeros += trailing_zeros(a.parts[k])
end

# arithmitic
Base.:+(a1::F, a2::F) where {F<:FlexibleUInt} =
    length(a1.parts) > length(a2.parts) ? F(_vadd!(copy(a1.parts), a2.parts)) :
                                        F(_vadd!(copy(a2.parts), a1.parts))
Base.:-(a1::F, a2::F) where {F<:FlexibleUInt} =
    a2 <= a1 ? F(_vsub!(copy(a1.parts), a2.parts)) : throw(OverflowError())
Base.:*(a1::F, a2::F) where {U<:BitUnsigned,F<:FlexibleUInt{U}} =
    F(_vmuladd!(fill(zero(U), length(a1.parts)+length(a2.parts)), a1.parts, a2.parts))
Base.divrem(n::F, d::F) where {F<:FlexibleUInt} = map(F, _vdivrem!(copy(n.parts), d.parts))
Base.div(n::F, d::F) where {F<:FlexibleUInt} = divrem(n, d)[1]
Base.rem(n::F, d::F) where {F<:FlexibleUInt} = divrem(n, d)[2]
Base.checked_abs(a::FlexibleUInt) = a

function Base.factorial(a::FlexibleUInt{U}) where {U<:BitUnsigned}
    b = copy(a.parts)
    u = [one(U)]
    f1 = copy(a.parts)
    f2 = Vector{U}()
    while true
        _vsub!(b, u)
        length(b) == 0 && break
        _vmuladd!(f2, f1, b)
        f1, f2 = f2, f1
        fill!(resize!(f2, length(f1)+length(b)), zero(U))
    end
    return FlexibleUInt{U}(f1)
end

end # module


text:
type AnnealingSoftmax <: BanditAlgorithm
  counts::Vector{Int64}
  values::Vector{Float64}
end

function AnnealingSoftmax(n_arms::Int64)
  AnnealingSoftmax(zeros(Int64, n_arms), zeros(n_arms))
end

function initialize(algo::AnnealingSoftmax, n_arms::Int64)
  algo.counts = zeros(Int64, n_arms)
  algo.values = zeros(n_arms)
end

function initialize(algo::AnnealingSoftmax, arms::Vector)
  initialize(algo, length(arms))
end

function select_arm(algo::AnnealingSoftmax)
  t = sum(algo.counts) + 1
  temperature = 1 / log(t + eps(1.0))
  z = sum(exp(algo.values ./ temperature))
  probs = exp(algo.values ./ temperature) ./ z
  return rand(Categorical(probs))
end

function update(algo::AnnealingSoftmax, chosen_arm::Int64, reward::Real)
  algo.counts[chosen_arm] += 1
  n = algo.counts[chosen_arm]

  value = algo.values[chosen_arm]
  algo.values[chosen_arm] = ((n - 1) / n) * value + (1 / n) * reward
end

max_stars_repo_name: rmminusrslash/BanditsBook

max_issues_repo_name: rmminusrslash/BanditsBook

max_forks_repo_name: rmminusrslash/BanditsBook


text:
module CollocatedAcoustic
using LinearAlgebra
using SparseArrays
import sbp
using sbp.Operator: OperatorData
using sbp.Sparse: diag_block_matrix_2x2, block_matrix_2x2, block_matrix,
                  block_matrix_insert
using sbp.Collocated: build_operators_2d, boundary_matrix,
                   build_covariant_basis
using sbp.Metrics: build_jacobian,
                   build_contravariant_basis,
                   contravariant_metric_tensor_to_matrix,
                   ContravariantMetricTensor

struct AcousticOperators
        n::Int64
        nx::Int64
        ny::Int64
        J::AbstractArray
        Ji::AbstractArray
        D1::AbstractArray
        D2::AbstractArray
        H::AbstractArray
        G::ContravariantMetricTensor
        B1::AbstractArray
        B2::AbstractArray
end

function init_operators(nx::Int64, ny::Int64, builder::Module, desc_D::OperatorData,
                        desc_H::OperatorData, fx::AbstractArray,
                        fy::AbstractArray)

        x, h, Dx, Hx = builder.build_operators(desc_D, desc_H, nx)
        y, h, Dy, Hy = builder.build_operators(desc_D, desc_H, ny)
        Bx = boundary_matrix(nx)
        By = boundary_matrix(ny)
        op = build_operators_2d(Dx, Dy, Hx, Hy, Bx, By)
        n = nx * ny
        n1 = nx
        n2 = ny
        a = build_covariant_basis(fx, fy, op)
        J = build_jacobian(a)
        b = build_contravariant_basis(J, a)
        Ji = spdiagm(0 => 1 ./J)
        J = spdiagm(0 => J)
        G = sbp.Metrics.build_contravariant_metric_tensor(b)
        G = contravariant_metric_tensor_to_matrix(G)
        D1 = op.Dx
        D2 = op.Dy
        H = op.Hx * op.Hy
        Hxi = spdiagm(0 => 1 ./ diag(op.Hx))
        Hyi = spdiagm(0 => 1 ./ diag(op.Hy))
        B1 = Hxi * op.Bx
        B2 = Hyi * op.By
        return AcousticOperators(n, nx, ny, J, Ji, D1, D2, H, G, B1, B2)

end

function grid(nx::Int64, ny::Int64)
        x1, h = sbp.Grid.grid_xp(nx)
        y1, h = sbp.Grid.grid_xp(ny)
        x = sbp.Grid.grid_2d_x(x1, ny)
        y = sbp.Grid.grid_2d_y(y1, nx)
        return x, y
end

function pressure_norm(op::AcousticOperators)
        return op.H * op.J
end

function velocity_norm(op::AcousticOperators)
        H = diag_block_matrix_2x2(op.H, op.H)
        J = diag_block_matrix_2x2(op.J, op.J)
        return H * J
end

function energy_norm(HJp::AbstractArray, HJ::AbstractArray, Gp::AbstractArray)
        rows = [size(HJp,1), size(HJ,1)]
        E = block_matrix(rows, rows)
        E = block_matrix_insert(E, rows, rows, 1, 1, HJp)
        Gip = inv(Matrix(Gp))
        E = block_matrix_insert(E, rows, rows, 2, 2, HJ * Gip)
        return E
end

function contravariant_metric_tensor(op::AcousticOperators)
        G11 = op.G.b11
        G12 = op.G.b12
        G21 = op.G.b21
        G22 = op.G.b22
        return block_matrix_2x2(G11, G12, G21, G22)
end

function divergence(op::AcousticOperators)
        rows = [op.n]
        cols = [op.n, op.n]
        Ap = block_matrix(rows, cols)
        Ap1 = op.Ji * op.D1 * op.J
        Ap2 = op.Ji * op.D2 * op.J
        Ap = block_matrix_insert(Ap, rows, cols, 1, 1, Ap1)
        Ap = block_matrix_insert(Ap, rows, cols, 1, 2, Ap2)
        return Ap
end

function gradient(op::AcousticOperators, G::AbstractArray)
        rows = [op.n, op.n]
        cols = [op.n]
        Av = block_matrix(rows, cols)
        A1 = op.D1
        A2 = op.D2
        Av = block_matrix_insert(Av, rows, cols, 1, 1, A1)
        Av = block_matrix_insert(Av, rows, cols, 2, 1, A2)
        return G * Av

end

function spatial_discretization(Ap::AbstractArray, Av::AbstractArray)
        rows = [size(Ap,1), size(Av,1)]
        cols = [size(Av,2), size(Ap,2)]
        A = block_matrix(rows, cols)
        A = block_matrix_insert(A, rows, cols, 1, 2, Ap)
        A = block_matrix_insert(A, rows, cols, 2, 1, Av)
        return A
end

function pressure_sat(op::AcousticOperators, G::AbstractArray)
        rows = [op.n, op.n]
        cols = [op.n]
        S = block_matrix(rows, cols)
        S = block_matrix_insert(S, rows, cols, 1, 1, op.B1)
        S = block_matrix_insert(S, rows, cols, 2, 1, op.B2)
        return G * S
end

function pressure_source(op::AcousticOperators,
                         r1_s::Float64,
                         r2_s::Float64,
                         num_moment::Int64,
                         num_smoothness::Int64)
        rows = [op.n, op.n, op.n]
        cols = [1]
        r1, h1 = sbp.Grid.grid_xp(op.nx)
        r2, h2 = sbp.Grid.grid_xp(op.ny)
        d = sbp.Source.source_discretize_2d(r1_s, r2_s, num_moment,
                                            num_smoothness, r1, r2, h1,
                                            h2)
        S = block_matrix(rows, cols)
        S = block_matrix_insert(S, rows, cols, 1, 1, d)
        return S
end

function pressure_receiver(op::AcousticOperators,
                         r1_s::Float64,
                         r2_s::Float64,
                         num_moment::Int64,
                         num_smoothness::Int64)
        rows = [op.n, op.n, op.n]
        cols = [1]
        r1, h1 = sbp.Grid.grid_xp(op.nx)
        r2, h2 = sbp.Grid.grid_xp(op.ny)
        r = sbp.Source.source_discretize_2d(r1_s, r2_s, num_moment,
                                            num_smoothness, r1, r2, 1.0,
                                            1.0)
        S = block_matrix(rows, cols)
        S = block_matrix_insert(S, rows, cols, 1, 1, r)
        return S
end

end

max_stars_repo_name: ooreilly/sbpjl

max_issues_repo_name: ooreilly/sbpjl

max_forks_repo_name: ooreilly/sbpjl


text:
# Script to transform data

using DataFrames, XLSX

# ---------- Load data --------------------------------------------------------------------------------------------------------

# File in ".xlsb" format, hence, need to transform manually into ".csv" first (download from http://www.wiod.org/database/wiots16)
url = "http://www.wiod.org/protected3/data16/wiot_ROW/WIOT2014_Nov16_ROW.xlsb" # does not work because of "xlsb"
url = "data/WIOT2014_Nov16_ROW.xlsx"

raw = DataFrame(XLSX.readxlsx(url)["2014"][:], :auto)

# ---------- Data wrangling ---------------------------------------------------------------------------------------------------

# Naming convention
# --- r...reporter
# --- p...partner
# --- s...sector
# --- ctry...country/countries

raw = raw[3:end, :] # delete empty rows
raw[1:2, 1] .= missing # delete table legend in top left corner

# table in long format (need to broadcast countries and sectors)
# idea is to name the columns as a combination of sectors and countries, transform into long format and then seperate names again
names_sector_iso = collect(raw[1, 5:end])
names_sector_long = collect(raw[2, 5:end])
names_sector_short = collect(raw[4, 5:end])
names_ctry = collect(raw[3, 5:end])
seperator = fill("___", size(collect(raw[3, 5:end]), 1)) # take 3 "_" as there are some in the text as well
colnames = names_sector_iso .* seperator .* names_sector_long .* seperator .* names_sector_short .* seperator .* names_ctry # combination of names

colnames = vcat(["r_s_iso", "r_s_long", "r_ctry", "r_s_short"], colnames) # name the reporter columns
rename!(raw, Symbol.(colnames))

table_matching = raw[1:4, 5:end] # save the table of names for later, possibly need to match sectors/countries later

raw = raw[5:end, :] # get rid of the now useless first 4 rows

raw_long = stack(raw, Not(1:4)) # transform to long format

# split the column with the combined names along "___" into four columns
raw_long = hcat(raw_long, DataFrame(reduce(vcat, permutedims.(split.(raw_long.variable, "___"))), [:p_s_iso, :p_s_long, :p_s_short, :p_ctry]))
#raw_long = raw_long[:, Not(:variable)] # delete combined named column

begin
    EU27 = ["AUT", "BEL", "BGR", "HRV", "CYP", "CZE", "DNK", "EST", "FIN", "FRA", "DEU", "GRC", "HUN", "IRL", "ITA", "LVA",
    "LTU", "LUX", "MLT", "NLD", "POL", "PRT", "ROU", "SVK", "SVN", "ESP", "SWE"]
end

raw_long_EU = filter(row -> row.r_ctry in [EU27; "GBR"], raw_long)
filter!(row -> row.p_ctry in [EU27; "GBR"], raw_long_EU)

# delete extra columns which where split before and return to wide format (not possible to match multiple into one column name yet)
select!(raw_long_EU, Not([:p_s_iso, :p_s_long, :p_s_short, :p_ctry]))
raw_wide_EU = unstack(raw_long_EU, [:r_s_iso, :r_s_long, :r_s_short, :r_ctry], :variable, :value)

# get original column names (4 rows) and combine it with table
col_names = names(raw_wide_EU[1,5:end]) # gives the names in the right order
col_names = split.(col_names, "___") # splits along seperator
col_names = [col_names[i][j] for i in 1:size(col_names, 1), j in 1:4]
col_names = permutedims(col_names) # gives transpose of string matrix
col_names = convert.(String, col_names) # could not write excel file with type String{String}
col_names = DataFrame(hcat(zeros(4, 4), col_names), :auto) # transform into dataframe

raw_wide_EU = vcat(col_names, DataFrame(Matrix(raw_wide_EU), :auto)) # transform column names so they can be joined

XLSX.writetable("clean/raw_wide_EU.xlsx", raw_wide_EU, overwrite=true)


text:
using Base.Meta: parse

# TODO: Replace this macro, see issue #514
"""
Usage: @VarName x[1,2][1+5][45][3]
  return: (:x,[1,2],6,45,3)
"""
macro VarName(expr::Union{Expr, Symbol})
    ex = deepcopy(expr)
    isa(ex, Symbol) && return var_tuple(ex)
    (ex.head == :ref) || throw("VarName: Mis-formed variable name $(expr)!")
    inds = :(())
    while ex.head == :ref
        if length(ex.args) >= 2
            strs = map(x -> :(string($x)), ex.args[2:end])
            pushfirst!(inds.args, :("[" * join($(Expr(:vect, strs...)), ", ") * "]"))
        end
        ex = ex.args[1]
        isa(ex, Symbol) && return var_tuple(ex, inds)
    end
    throw("VarName: Mis-formed variable name $(expr)!")
end
function var_tuple(sym::Symbol, inds::Expr=:(()))
    return esc(:($(QuoteNode(sym)), $inds, $(QuoteNode(gensym()))))
end

function wrong_dist_errormsg(l)
    return "Right-hand side of a ~ must be subtype of Distribution or a vector of " *
        "Distributions on line $(l)."
end

"""
    generate_observe(observation, dist, model_info)

Generate an observe expression for observation `observation` drawn from
a distribution or a vector of distributions (`dist`).
"""
function generate_observe(observation, dist, model_info)
    main_body_names = model_info[:main_body_names]
    vi = main_body_names[:vi]
    sampler = main_body_names[:sampler]
    return quote
        isdist = if isa($dist, AbstractVector)
            # Check if the right-hand side is a vector of distributions.
            all(d -> isa(d, Distribution), $dist)
        else
            # Check if the right-hand side is a distribution.
            isa($dist, Distribution)
        end
        @assert isdist @error($(wrong_dist_errormsg(@__LINE__)))
        $vi.logp += Turing.observe($sampler, $dist, $observation, $vi)
    end
end

"""
    generate_assume(var, dist, model_info)

Generate an assume expression for parameters `var` drawn from
a distribution or a vector of distributions (`dist`).
"""
function generate_assume(var::Union{Symbol, Expr}, dist, model_info)
    main_body_names = model_info[:main_body_names]
    vi = main_body_names[:vi]
    sampler = main_body_names[:sampler]

    varname = gensym(:varname)
    sym, idcs, csym = gensym(:sym), gensym(:idcs), gensym(:csym)
    csym_str, indexing, syms = gensym(:csym_str), gensym(:indexing), gensym(:syms)

    if var isa Symbol
        varname_expr = quote
            $sym, $idcs, $csym = Turing.@VarName $var
            $csym = Symbol($(QuoteNode(model_info[:name])), $csym)
            $varname = Turing.VarName{$sym}($csym, "")
        end
    else
        varname_expr = quote
            $sym, $idcs, $csym = Turing.@VarName $var
            $csym_str = string($(QuoteNode(model_info[:name])))*string($csym)
            $indexing = foldl(*, $idcs, init = "")
            $varname = Turing.VarName{$sym}(Symbol($csym_str), $indexing)
        end
    end

    lp = gensym(:lp)
    return quote
        $varname_expr
        isdist = if isa($dist, AbstractVector)
            # Check if the right-hand side is a vector of distributions.
            all(d -> isa(d, Distribution), $dist)
        else
            # Check if the right-hand side is a distribution.
            isa($dist, Distribution)
        end
        @assert isdist @error($(wrong_dist_errormsg(@__LINE__)))

        ($var, $lp) = if isa($dist, AbstractVector)
            Turing.assume($sampler, $dist, $varname, $var, $vi)
        else
            Turing.assume($sampler, $dist, $varname, $vi)
        end
        $vi.logp += $lp
    end
end

"""
    tilde(left, right, model_info)

The `tilde` function generates observation expression for data variables and assumption expressions for parameter variables, updating `model_info` in the process.
"""
function tilde(left, right, model_info)
    return generate_observe(left, right, model_info)
end
function tilde(left::Union{Symbol, Expr}, right, model_info)
    return _tilde(getvsym(left), left, right, model_info)
end

function _tilde(vsym, left, dist, model_info)
    main_body_names = model_info[:main_body_names]
    model_name = main_body_names[:model]

    model_info[:tent_dvars_list] = copy(model_info[:arg_syms])
    if vsym in model_info[:arg_syms]
        Turing.DEBUG && @debug " Observe - `$(vsym)` is an observation"
        return quote
            if Turing.in_pvars($(Val(vsym)), $model_name)
                $(generate_assume(left, dist, model_info))
            else
                $(generate_observe(left, dist, model_info))
            end
        end
    else
        # Assume it is a parameter.
        if !(vsym in model_info[:tent_pvars_list])
            Turing.DEBUG && @debug begin
                msg = " Assume - `$(vsym)` is a parameter"
                if isdefined(Main, vsym)
                    msg  *= " (ignoring `$(vsym)` found in global scope)"
                end
                msg
            end
            push!(model_info[:tent_pvars_list], vsym)
        end

        return generate_assume(left, dist, model_info)
    end
end

#################
# Main Compiler #
#################

"""
    @model(body)

Macro to specify a probabilistic model.

Example:

Model definition:

```julia
@model model_generator(x = default_x, y) = begin
    ...
end
```

Expanded model definition

```julia
# Allows passing arguments as kwargs
model_generator(; x = nothing, y = nothing)) = model_generator(x, y)
function model_generator(x = nothing, y = nothing)
    pvars, dvars = Turing.get_vars(Tuple{:x, :y}, (x = x, y = y))
    data = Turing.get_data(dvars, (x = x, y = y))
    defaults = Turing.get_default_values(dvars, (x = default_x, y = nothing))

    inner_function(sampler::Turing.AbstractSampler, model) = inner_function(model)
    function inner_function(model)
        return inner_function(Turing.VarInfo(), Turing.SampleFromPrior(), model)
    end
    function inner_function(vi::Turing.VarInfo, model)
        return inner_function(vi, Turing.SampleFromPrior(), model)
    end
    # Define the main inner function
    function inner_function(vi::Turing.VarInfo, sampler::Turing.AbstractSampler, model)
        local x
        if isdefined(model.data, :x)
            if model.data.x isa Type && (model.data.x <: AbstractFloat || model.data.x <: AbstractArray)
                x = Turing.Core.get_matching_type(sampler, vi, model.data.x)
            else
                x = model.data.x
            end
        else
            x = model_defaults.x
        end
        local y
        if isdefined(model.data, :y)
            if model.data.y isa Type && (model.data.y <: AbstractFloat || model.data.y <: AbstractArray)
                y = Turing.Core.get_matching_type(sampler, vi, model.data.y)
            else
                y = model.data.y
            end
        else
            y = model.defaults.y
        end

        vi.logp = zero(Real)
        ...
    end
    model = Turing.Model{pvars, dvars}(inner_function, data, defaults)
    return model
end
```

Generating a model: `model_generator(x_value)::Model`.
"""
macro model(input_expr)
    build_model_info(input_expr) |> translate_tilde! |> update_args! |> build_output
end

"""
    build_model_info(input_expr)

Builds the `model_info` dictionary from the model's expression.
"""
function build_model_info(input_expr)
    # Extract model name (:name), arguments (:args), (:kwargs) and definition (:body)
    modeldef = MacroTools.splitdef(input_expr)
    # Function body of the model is empty
    warn_empty(modeldef[:body])
    # Construct model_info dictionary

    # Extracting the argument symbols from the model definition
    arg_syms = map(modeldef[:args]) do arg
        # @model demo(x)
        if (arg isa Symbol)
            arg
        # @model demo(::Type{T}) where {T}
        elseif MacroTools.@capture(arg, ::Type{T_} = Tval_)
            T
        # @model demo(x = 1)
        elseif MacroTools.@capture(arg, x_ = val_)
            x
        else
            throw(ArgumentError("Unsupported argument $arg to the `@model` macro."))
        end
    end
    args = map(modeldef[:args]) do arg
        if (arg isa Symbol)
            arg
        elseif MacroTools.@capture(arg, ::Type{T_} = Tval_)
            if in(T, modeldef[:whereparams])
                S = :Any
            else
                ind = findfirst(x -> MacroTools.@capture(x, T1_ <: S_) && T1 == T, modeldef[:whereparams])
                ind != nothing || throw(ArgumentError("Please make sure type parameters are properly used. Every `Type{T}` argument need to have `T` in the a `where` clause"))
            end
            Expr(:kw, :($T::Type{<:$S}), Tval)
        else
            arg
        end
    end
    model_info = Dict(
        :name => modeldef[:name],
        :input_expr => input_expr,
        :main_body => modeldef[:body],
        :arg_syms => arg_syms,
        :args => args,
        :kwargs => modeldef[:kwargs],
        :whereparams => modeldef[:whereparams],
        :tent_dvars_list => Symbol[],
        :tent_pvars_list => Symbol[],
        :main_body_names => Dict(
            :vi => gensym(:vi),
            :sampler => gensym(:sampler),
            :model => gensym(:model),
            :pvars => gensym(:pvars),
            :dvars => gensym(:dvars),
            :data => gensym(:data),
            :inner_function => gensym(:inner_function),
            :defaults => gensym(:defaults)
        )
    )

    return model_info
end

"""
    translate_tilde!(model_info)

Translates ~ expressions to observation or assumption expressions, updating `model_info`.
"""
function translate_tilde!(model_info)
    ex = model_info[:main_body]
    ex = MacroTools.postwalk(x -> @capture(x, L_ ~ R_) ? tilde(L, R, model_info) : x, ex)
    model_info[:main_body] = ex
    return model_info
end

"""
    update_args!(model_info)

Extracts default argument values and replaces them with `nothing`.
"""
function update_args!(model_info)
    fargs = Vector{Union{Symbol, Expr}}(model_info[:args])
    fargs_default_values = []
    for i in 1:length(fargs)
        if isa(fargs[i], Symbol)
            push!(fargs_default_values, :($(fargs[i]) = :nothing))
            fargs[i] = Expr(:kw, fargs[i], :nothing)
        elseif isa(fargs[i], Expr) && MacroTools.@capture(fargs[i], T_::Type{<:S_} = Tval_)
            nothing
            #push!(fargs_default_values, :($T = $Tval))
        elseif isa(fargs[i], Expr) && fargs[i].head == :kw
            push!(fargs_default_values, :($(fargs[i].args[1]) = $(fargs[i].args[2])))
            fargs[i] = Expr(:kw, fargs[i].args[1], :nothing)
        else
            throw("Unsupported argument type $(fargs[i]).")
        end
    end
    if length(fargs_default_values) == 0
        tent_arg_defaults_nt = :(NamedTuple())
    else
        tent_arg_defaults_nt = :($(fargs_default_values...),)
    end
    model_info[:args] = fargs
    model_info[:tent_arg_defaults_nt] = tent_arg_defaults_nt
    return model_info
end

"""
    build_output(model_info)

Builds the output expression.
"""
function build_output(model_info)
    # Construct user-facing function
    main_body_names = model_info[:main_body_names]
    vi_name = main_body_names[:vi]
    model_name = main_body_names[:model]
    sampler_name = main_body_names[:sampler]
    data_name = main_body_names[:data]
    pvars_name = main_body_names[:pvars]
    dvars_name = main_body_names[:dvars]
    inner_function_name = main_body_names[:inner_function]
    defaults_name = main_body_names[:defaults]

    # Arguments with default values
    args = model_info[:args]
    # Argument symbols without default values
    arg_syms = model_info[:arg_syms]
    # Default values of the arguments
    whereparams = model_info[:whereparams]
    tent_arg_defaults_nt = model_info[:tent_arg_defaults_nt]
    # Model generator name
    outer_function_name = model_info[:name]
    # Tentative list of parameter variables
    tent_pvars_list = model_info[:tent_pvars_list]
    # Tentative list of data variables
    tent_dvars_list = model_info[:tent_dvars_list]
    # Main body of the model
    main_body = model_info[:main_body]

    if length(tent_dvars_list) == 0
        tent_dvars_nt = :(NamedTuple())
    else
        nt_type = Expr(:curly, :NamedTuple,
            Expr(:tuple, QuoteNode.(tent_dvars_list)...),
            Expr(:curly, :Tuple, [:(Turing.Core.get_type($x)) for x in tent_dvars_list]...)
        )
        tent_dvars_nt = Expr(:call, nt_type, Expr(:tuple, tent_dvars_list...))
    end
    #= Does the following for each of the tentative dvars
        local x
        if isdefined(model.data, :x)
            x = model.data.x
        else
            x = default_x
        end
    =#
    unwrap_data_expr = Expr(:block)
    for var in tent_dvars_list
        push!(unwrap_data_expr.args, quote
            local $var
            if isdefined($model_name.data, $(QuoteNode(var)))
                # The `Type{T}` arguments will always show up in the `model.data` named tuple.
                # This is because we are not replacing the default value of these arguments with `nothing` but keeping the same value defined by by the user, e.g. `Float64`.
                # So if the value is indeed correct, i.e. a type then it should just work
                # If the value is not a type, i.e. `::Type{T} = 1` and the user doesn't pass it something for this argument, then it will give an error when constructing the model, which is a correct Julia error.
                # This means that we don't need an expression for the default value of the `Type{T}` arguments in `model.defaults`.
                if $model_name.data.$var isa Type && ($model_name.data.$var <: AbstractFloat || $model_name.data.$var <: AbstractArray)
                    $var = Turing.Core.get_matching_type($sampler_name, $vi_name, $model_name.data.$var)
                else
                    $var = $model_name.data.$var
                end
            else
                $var = $model_name.defaults.$var
            end
        end)
    end
    return esc(quote
        # Allows passing arguments as kwargs
        $outer_function_name(;$(args...)) = $outer_function_name($(arg_syms...))
        # Outer function with `nothing` as default values except for Type{T} arguments
        function $outer_function_name($(args...))
            # Adds variables equal to `nothing` or `missing` or whose `eltype` is `Missing` to pvars and the rest to dvars
            # `tent_pvars_list` is the tentative list of pvars
            # `tent_dvars_nt` is the tentative named tuple of dvars
            $pvars_name, $dvars_name = Turing.get_vars($(Tuple{tent_pvars_list...}), $(tent_dvars_nt))
            # Filter out the dvars equal to `nothing` or `missing`, or whose `eltype` is `Missing`
            $data_name = Turing.get_data($dvars_name, $tent_dvars_nt)
            # Replace default values of inputs whose values are Vector{Missing} by a Vector{Real} of the same length as the input
            $defaults_name = Turing.get_default_values($tent_dvars_nt, $tent_arg_defaults_nt)

            # Define fallback inner functions
            function $inner_function_name($sampler_name::Turing.AbstractSampler, $model_name)
                return $inner_function_name($model_name)
            end
            function $inner_function_name($model_name)
                return $inner_function_name(Turing.VarInfo(), Turing.SampleFromPrior(), $model_name)
            end
            function $inner_function_name($vi_name::Turing.VarInfo, $model_name)
                return $inner_function_name($vi_name, Turing.SampleFromPrior(), $model_name)
            end

            # Define the main inner function
            function $inner_function_name(
                $vi_name::Turing.VarInfo,
                $sampler_name::Turing.AbstractSampler,
                $model_name
                )

                $unwrap_data_expr
                $vi_name.logp = zero(Real)
                $main_body
            end
            $model_name = Turing.Model{$pvars_name, $dvars_name}($inner_function_name, $data_name, $defaults_name)
            return $model_name
        end
    end)
end

# A hack for NamedTuple type specialization
# (T = Int,) has type NamedTuple{(:T,), Tuple{DataType}} by default
# With this function, we can make it NamedTuple{(:T,), Tuple{Type{Int}}}
# Both are correct, but the latter is what we want for type stability
get_type(::Type{T}) where {T} = Type{T}
get_type(t) = typeof(t)

# Replaces the default for `Vector{Missing}` inputs by `Vector{Real}` of the same length as the input.
@generated function get_default_values(tent_dvars_nt::Tdvars, tent_arg_defaults_nt::Tdefaults) where {Tdvars <: NamedTuple, Tdefaults <: NamedTuple}
    dvar_names = Tdvars.names
    dvar_types = Tdvars.parameters[2].types
    defaults = []
    for (n, t) in zip(dvar_names, dvar_types)
        if eltype(t) == Missing
            push!(defaults, :($n = similar(tent_dvars_nt.$n, Real)))
        elseif in(n, tent_arg_defaults_nt.names)
            push!(defaults, :($n = tent_arg_defaults_nt.$n))
        end
    end
    if length(defaults) == 0
        return :(NamedTuple())
    else
        return :($(defaults...),)
    end
end

@generated function get_vars(tent_pvars::Type{Tpvars}, tent_dvars_nt::NamedTuple) where {Tpvars <: Tuple}
    tent_pvar_syms = [Tpvars.types...]
    tent_dvar_syms = [tent_dvars_nt.names...]
    dvar_types = [tent_dvars_nt.types...]
    append!(tent_pvar_syms, [tent_dvar_syms[i] for i in 1:length(tent_dvar_syms) if dvar_types[i] == Nothing || dvar_types[i] == Missing || eltype(dvar_types[i]) == Missing])
    setdiff!(tent_dvar_syms, tent_pvar_syms)
    pvars_tuple = Tuple{tent_pvar_syms...}
    dvars_tuple = Tuple{tent_dvar_syms...}

    return :($pvars_tuple, $dvars_tuple)
end

@inline get_data(Tdvars::Type{<:Tuple}, nt::NamedTuple) = _get_data(Tuple(Tdvars.types), nt)
@inline function _get_data(dvars::Tuple, nt::NamedTuple)
    length(dvars) === 0 && return NamedTuple()
    n = dvars[1]
    f = getfield(nt, n)
    return merge(NamedTuple{(n,), Tuple{get_type(f)}}((f,)), _get_data(Base.tail(dvars), nt))
end

function warn_empty(body)
    if all(l -> isa(l, LineNumberNode), body.args)
        @warn("Model definition seems empty, still continue.")
    end
    return
end

####################
# Helper functions #
####################

getvsym(s::Symbol) = s
function getvsym(expr::Expr)
    @assert expr.head == :ref "expr needs to be an indexing expression, e.g. :(x[1])"
    return getvsym(expr.args[1])
end

"""
    data(dict::Dict, keys::Vector{Symbol})
Construct a tuple with values filled according to `dict` and keys
according to `keys`.
"""
function data(dict::Dict, keys::Vector{Symbol})

    @assert mapreduce(k -> haskey(dict, k), &, keys)

    r = Expr(:tuple)
    for k in keys
        push!(r.args, Expr(:(=), k, dict[k]))
    end
    return Main.eval(r)
end

"""
    get_matching_type(spl, vi, ::Type{T}) where {T}
Get the specialized version of type `T` for sampler `spl`. For example,
if `T === Float64` and `spl::Hamiltonian`, the matching type is `eltype(vi[spl])`.
"""
get_matching_type(spl, vi, ::Type{T}) where {T} = T


text:
:foo

typeof(ans)

:foo == Symbol("foo")

Symbol("func", 10)

Symbol(:var,'_',"sym")

max_stars_repo_name: phrb/PDP

max_issues_repo_name: phrb/PDP

max_forks_repo_name: phrb/PDP


text:
## Exercise 4-4
## Add another parameter, named len, to square. Modify the body so length of the sides is len, and then modify the function call to provide a second argument. Run the macro again. Test with a range of values for len.
using ThinkJulia

println("Ans: ")

function square(turtle::Turtle, distance::Int = 100)
    @svg begin
        for i in 1:3
            forward(turtle, distance)
            turn(turtle, -90)
        end

        forward(turtle, distance)
    end
end

function drawSquare(len::Int)
    turtle = Turtle()
    square(turtle, len)
end

drawSquare(200)

println("End.")


text:
import Base.in
function in(mesh::CompScienceMeshes.AbstractMesh)
    cells_mesh = sort.(mesh)
    function f(cell)
        sort(cell) in cells_mesh
    end
    return f
end

"""
Creates a predicate that can be used to check wheter an edge is interior to
a surface (true) or on its boundary (false). This predicate is based on combinatorics.
In particular it expects as argument a tuple of indices pointing into the vertex
buffer of `mesh`.
"""
function interior_tpredicate(mesh::AbstractMesh{U,3} where {U})

    # @assert dimension(mesh) == 2

    vtoc, vton = vertextocellmap(mesh)

    function pred(simplex::SVector{2,Int} where {N})
        v = simplex[1]
        n = vton[v]
        a = vtoc[v,1:n]

        v = simplex[2]
        n = vton[v]
        b = vtoc[v,1:n]

        ab = a ∩ b
        return length(ab) > 1
    end

    return pred
end

function interior_tpredicate(mesh::Mesh{U,2} where {U})

    # @assert dimension(mesh) == 2

    vtoc, vton = vertextocellmap(mesh)

    function pred(simplex::SVector{1,Int} where {N})
        v = simplex[1]
        n = vton[v]
        a = vtoc[v,1:n]

        return length(a) > 1
    end

    return pred
end

function interior_tpredicate(mesh::Mesh{U,4} where {U})

    bnd = boundary(mesh)
    bnd_cells = Set(sort(c) for c in cells(bnd))
    function pred(cell::SVector{3,Int})
        !(sort(cell) in bnd_cells)
    end

    return pred
end

"""
Creates a predicate that can be used to check wheter a vertex is interior to
a surface (true) or on its boundary (false).
In particular it expects as argument an index pointing into the vertex buffer of `mesh`.
"""
function interior_vpredicate(mesh::AbstractMesh)
    #TODO: update to accept simplex as argument
    @assert dimension(mesh) == 2
    skel = skeleton(mesh,1)
    edges = cells(skel)
    vtoc,vton = vertextocellmap(skel)
    pred = interior_tpredicate(mesh)
    function vpred(vidx)
        for j = 1:vton[vidx]
            pred(edges[vtoc[vidx,j]]) ? nothing : return false;
        end
        return true
    end
    return vpred
end

max_stars_repo_name: krcools/CompScienceMeshes

max_issues_repo_name: krcools/CompScienceMeshes

max_forks_repo_name: krcools/CompScienceMeshes


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

mutable struct ApplicationGatewayRequestRoutingRule <: SwaggerModel
    id::Any # spec type: Union{ Nothing, String } # spec name: id

    function ApplicationGatewayRequestRoutingRule(;id=nothing)
        o = new()
        validate_property(ApplicationGatewayRequestRoutingRule, Symbol("id"), id)
        setfield!(o, Symbol("id"), id)
        o
    end
end # type ApplicationGatewayRequestRoutingRule

const _property_map_ApplicationGatewayRequestRoutingRule = Dict{Symbol,Symbol}(Symbol("id")=>Symbol("id"))
const _property_types_ApplicationGatewayRequestRoutingRule = Dict{Symbol,String}(Symbol("id")=>"String")
Base.propertynames(::Type{ ApplicationGatewayRequestRoutingRule }) = collect(keys(_property_map_ApplicationGatewayRequestRoutingRule))
Swagger.property_type(::Type{ ApplicationGatewayRequestRoutingRule }, name::Symbol) = Union{Nothing,eval(Base.Meta.parse(_property_types_ApplicationGatewayRequestRoutingRule[name]))}
Swagger.field_name(::Type{ ApplicationGatewayRequestRoutingRule }, property_name::Symbol) =  _property_map_ApplicationGatewayRequestRoutingRule[property_name]

function check_required(o::ApplicationGatewayRequestRoutingRule)
    true
end

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


text:
function Base.show(io::IO, mime::MIME"text/plain", stack::AbstractDimStack)
    print(io, nameof(typeof(stack)))
    Dimensions.print_dims(io, mime, dims(stack))
    nlayers = length(keys(stack))
    layers_str = nlayers == 1 ? "layer" : "layers"
    printstyled(io, "\nand "; color=:light_black)
    print(io, "$nlayers $layers_str:\n")
    maxlen = reduce(max, map(length ∘ string, keys(stack)))
    for key in keys(stack)
        layer = stack[key]
        pkey = rpad(key, maxlen)
        printstyled(io, "  :$pkey", color=:yellow)
        print(io, string(" ", eltype(layer)))
        field_dims = DD.dims(layer)
        n_dims = length(field_dims)
        printstyled(io, " dims: "; color=:light_black)
        if n_dims > 0
            for (d, dim) in enumerate(field_dims)
                Dimensions.print_dimname(io, dim)
                d != length(field_dims) && print(io, ", ")
            end
            print(io, " (")
            for (d, dim) in enumerate(field_dims)
                print(io, "$(length(dim))")
                d != length(field_dims) && print(io, '×')
            end
            print(io, ')')
        end
        print(io, '\n')
    end

    md = metadata(stack)
    if !(md isa NoMetadata)
        n_metadata = length(md)
        if n_metadata > 0
            printstyled(io, "\nwith metadata "; color=:light_black)
            show(io, mime, md)
        end
    end

    # Show anything else subtypes want to append
    show_after(io, mime, stack)

    return nothing
end

show_after(io, mime, stack::DimStack) = nothing


text:
function _default(mesh::TOrSignal{M}, s::Style, data::Dict) where M <: GLNormalAttributeMesh
    @gen_defaults! data begin
        main = mesh
        shading = true
        color = nothing
        shader = GLVisualizeShader(
            "fragment_output.frag", "util.vert", "attribute_mesh.vert", "standard.frag",
            view = Dict("light_calc" => light_calc(shading))
        )
    end
end

function _default(mesh::TOrSignal{M}, s::Style, data::Dict) where M <: GLNormalMesh
    @gen_defaults! data begin
        shading = true
        main = mesh
        color = default(RGBA{Float32}, s)
        shader = GLVisualizeShader(
            "fragment_output.frag", "util.vert", "standard.vert", "standard.frag",
            view = Dict("light_calc" => light_calc(shading))
        )
    end
end
function _default(mesh::TOrSignal{M}, s::Style, data::Dict) where M <: GLNormalUVMesh
    @gen_defaults! data begin
        shading = true
        main = mesh
        color = default(RGBA{Float32}, s) => Texture

        shader = GLVisualizeShader(
            "fragment_output.frag", "util.vert", "uv_normal.vert", "standard.frag",
            view = Dict("light_calc" => light_calc(shading))
        )
    end
end
function _default(mesh::TOrSignal{M}, s::Style, data::Dict) where M <: GLNormalVertexcolorMesh
    @gen_defaults! data begin
        shading = true
        main = mesh
        color = nothing
        shader = GLVisualizeShader(
            "fragment_output.frag", "util.vert", "vertexcolor.vert", "standard.frag",
            view = Dict("light_calc" => light_calc(shading))
        )
    end
end

function _default(mesh::GLNormalColorMesh, s::Style, data::Dict)
    data[:color] = decompose(RGBA{Float32}, mesh)
    _default(GLNormalMesh(mesh), s, data)
end

function _default(mesh::TOrSignal{M}, s::Style, data::Dict) where M <: GLPlainMesh
    @gen_defaults! data begin
        primitive::GLPlainMesh = mesh
        color = default(RGBA, s, 1)
        shader = GLVisualizeShader("fragment_output.frag", "plain.vert", "plain.frag")
    end
end


text:
# Configuration for running simple neutral copy error simulation
#=
Recommended command line to run:
> julia -p 4 -L NeutralEvolution.jl nrun.jl examples/example1
=#
export simtype
@everywhere simtype = 3
@everywhere const N = 5        # population size
const mutstddev = 0.04
const ngens = 6
const initial_value = 1.0
const num_trials=3
const record_interval = 2
const use_population=true
const save_populations=true
const conformist_probability=1.0
const neutral = true


text:
# Copyright (c) 2022 Dongdong Kong. All rights reserved.
# This work is licensed under the terms of the MIT license.
# For a copy, see <https://opensource.org/licenses/MIT>.

module Ipaper
# using Ipaper
# @reexport using Z: x, y

using Dates
# using Pipe
using LambdaFn
using DimensionalData
using Plots: plot!, savefig

using DataFrames
import CSV
# import Statistics: quantile

using Reexport
@reexport using NaNStatistics

using Printf
export @sprintf

# rename to @f
@eval const $(Symbol("@f")) = $(Symbol("@λ"))
export @λ, @lf, @f

include("Pipe.jl")
@reexport using .Pipe

include("missing.jl")
include("plyr.jl")
include("cmd.jl")
include("macro.jl")
include("dates.jl")
include("file_operation.jl")
include("par.jl")
include("stringr.jl")
include("tools.jl")
include("factor.jl")
include("data.frame.jl")
include("DimensionalData.jl")
include("statistics.jl")
include("con_parse.jl")

dim = size
# whos = varinfo

export dim

end