text:
# To fully work, needs GLVisualize sd/thaxis

module GLImshow

    using GLPlot, GLVisualize, GLAbstraction, Colors, GeometryTypes
    using Reactive, GLWindow, FileIO, FixedSizeArrays, AxisArrays, GLFW
    import GLVisualize: IRect, mm, toggle_button, button, slider
    import GLAbstraction: imagespace
    using NIfTI

    function IRect(xy::FixedVector, w, h)
        IRect(xy[1], xy[2], w, h)
    end
    function IRect(x, y, wh::FixedVector)
        IRect(x, y, wh[1], wh[2])
    end
    function IRect(xy::FixedVector, wh::FixedVector)
        IRect(xy[1], xy[2], wh[1], wh[2])
    end
    function FRect(x, y, w, h)
        SimpleRectangle{Float32}(x, y, w, h)
    end
    function FRect(r::SimpleRectangle)
        SimpleRectangle{Float32}(r.x, r.y, r.w, r.h)
    end
    function FRect(xy::FixedVector, w, h)
        SimpleRectangle{Float32}(xy[1], xy[2], w, h)
    end
    function FRect(x, y, wh::FixedVector)
        SimpleRectangle{Float32}(x, y, wh[1], wh[2])
    end
    function FRect(xy::FixedVector, wh::FixedVector)
        SimpleRectangle{Float32}(xy[1], xy[2], wh[1], wh[2])
    end

    global const iconsize = 5mm
    global const path_s = Signal("")
    global const loaded_image = Signal(Any, nothing)

    const screens = []
    screen() = (init(); screens[1])
    editscreen() = (init(); screens[2])

    function imshow(path::AbstractString)
        init()
        isfile(path) || error("no file found at $path")
        push!(path_s, path)
    end
    function imshow(image)
        init()
        push!(loaded_image, image)
    end

    function init()
        if isempty(screens) || !(isopen(first(screens)))
            global loaded_image
            global path_s
            push!(loaded_image, nothing)
            push!(path_s, "")
            empty!(screens)
            rootscreen = glscreen()
            @async GLWindow.waiting_renderloop(rootscreen)

            area1, area2 = y_partition_abs(rootscreen.area, 3iconsize + 6mm)
            edit_screen = Screen(rootscreen, area = area1, stroke = (1, RGBA(0.9f0, 0.9f0, 0.9f0, 1f0)))
            screen = Screen(rootscreen, area = area2)
            push!(screens, screen, edit_screen)
            area = Signal(FRect(value(screen.inputs[:window_area])))
            cam = DummyCamera(area, Signal(eye(Mat4f0)), Signal(eye(Mat4f0)), Signal(eye(Mat4f0)))
            @materialize mouseposition, mouse_buttons_pressed, buttons_pressed, scroll = screen.inputs
            mouseposition = map(Vec2f0, mouseposition)
            left_pressed = const_lift(GLAbstraction.pressed, mouse_buttons_pressed, GLFW.MOUSE_BUTTON_LEFT)
            pan = const_lift(==, buttons_pressed, Set([GLFW.KEY_SPACE]))
            mousepan = GLAbstraction.dragged_diff(mouseposition, left_pressed, pan)
            proportion_v, preserveratio_s = toggle_button(
                "●", "⬬",
                edit_screen, relative_scale = iconsize
            )
            preserveratio = map(preserveratio_s) do preserveratio
                if value(preserveratio_s)
                    a = value(area)
                    w1 = Vec2f0(widths(a))
                    w2 = Vec2f0(widths(screen))
                    ratio = w2 ./ w1
                    w1 = if ratio[1] > ratio[2]
                        s = w2[1] ./ w2[2]
                        Vec2f0(s * w1[2], w1[2])
                    else
                        s = w2[2] ./ w2[1]
                        Vec2f0(w1[1], s * w1[1])
                    end
                    update_cam!(cam, FRect(a.x, a.y, w1))
                end
                nothing
            end
            preserve(preserveratio)
            rect = selection_rect(screen)

            rect_camspace = map(rect) do rect
                mini = minimum(rect)
                maxi = maximum(rect)
                _mini = Vec2f0(min(mini[1], maxi[1]), min(mini[2], maxi[2]))
                _maxi = Vec2f0(max(mini[1], maxi[1]), max(mini[2], maxi[2]))
                rect = FRect(_mini, _maxi - _mini)
                oldarea = value(area)
                screenarea = value(screen.area)
                iscale = wscale(screenarea, oldarea)
                whold = widths(oldarea)
                xy = (minimum(rect) .* iscale) .+ minimum(oldarea)
                w1 = widths(rect) .* iscale
                if value(preserveratio_s)
                    w2 = Vec2f0(widths(screen))
                    ratio = w2 ./ w1
                    w1 = if ratio[1] > ratio[2]
                        s = w2[1] ./ w2[2]
                        Vec2f0(s * w1[2], w1[2])
                    else
                        s = w2[2] ./ w2[1]
                        Vec2f0(w1[1], s * w1[1])
                    end
                end
                update_cam!(cam, FRect(xy, w1))
                nothing
            end
            preserve(rect_camspace)
            translate_s = map(mousepan) do t
                a = value(area)
                st = t .* wscale(value(screen.area), a)
                update_cam!(cam, FRect(minimum(a) .+ st, widths(a)))
                nothing
            end
            preserve(translate_s)
            zoom_s = map(scroll) do x
                zoom = Float32(x[2])
                if zoom != 0
                    a = value(area)
                    z = 1 + (zoom * 0.10)
                    mp = value(mouseposition)
                    mp = (mp .* wscale(value(screen.area), a)) + minimum(a)
                    p1, p2 = minimum(a), maximum(a)
                    p1, p2 = p1 - mp, p2 - mp # translate to mouse position
                    p1, p2 = z * p1, z * p2
                    p1, p2 = p1 + mp, p2 + mp
                    update_cam!(cam, FRect(p1, p2 - p1))
                    z
                end
                0f0
            end
            preserve(zoom_s)
            reset_v, reset_s = button("⛶", edit_screen, relative_scale = iconsize)
            # obviously doesn't work with multiple images!
            preserve(map(screen.inputs[:dropped_files]) do x
                if !isempty(x)
                    push!(path_s, first(x))
                    yield()
                end
            end)

            path_load_s = map(path_s) do path
                if isfile(path)
                    try
                        f, ext = splitext(path)
                        im = if ext == ".nii" # hack for nii not being part of FileIO yet
                            x = niread(path).raw
                            a, b = extrema(x)
                            x .= (x .- a) ./ (b -a)
                            Gray.(x)
                        else
                            load(path)
                        end
                        push!(loaded_image, im)
                    catch e
                        warn(e)
                    end
                end
                nothing
            end
            preserve(path_load_s)

            img_s = foldp(value(loaded_image), loaded_image, typ = Any) do v0, im
                if im != nothing
                    if v0 != nothing
                        delete!(screen, v0[2].children[])
                        for comp in v0[3], elem in comp.children # TODO define a delete for Composables
                            delete!(edit_screen, elem)
                        end
                    end
                    slideraxis = if ndims(im) <= 2
                    elseif isa(im, AxisArray)
                        axisnames(im)[3:end]
                    elseif ndims(im) == 3
                        ["z"]
                    elseif ndims(im) == 4
                        ["z", "time"]
                    end
                    slider_list = GLAbstraction.Composable[]
                    slider_signals = []
                    for i = 1:(ndims(im) - 2)
                        label = slideraxis[i]
                        slider_v, slider_s = slider(1:size(im, 2+i), edit_screen, icon_size = iconsize, knob_scale = 3mm)
                        label_v = visualize(
                            map(z-> @sprintf("%s: %5d ", label, z), slider_s),
                            color = RGBA(0f0, 0f0, 0f0, 1f0), relative_scale = iconsize
                        )
                        push!(slider_signals, slider_s)
                        push!(slider_list, label_v, slider_v)
                    end
                    img_s = map(Signal(im), slider_signals...) do img, idx...
                        if isempty(idx)
                            img
                        else
                            img[:, :, idx...]
                        end
                    end
                    if !isempty(slider_list)
                        gui_list = visualize(
                            slider_list,
                            gap = 3mm, lastposition = Vec3f0(1mm, 1mm + iconsize, 0),
                            direction = 1
                        )
                        _view(gui_list, edit_screen, camera = :fixed_pixel)
                    end
                    imvis = visualize(img_s)
                    _view(imvis, screen, camera = cam)
                    reset_to_img!(imvis, cam, preserveratio_s)
                    return img_s, imvis, slider_list
                end
                return v0
            end
            preserve(img_s)
            current_value = map(mouseposition, img_s) do mp, imgvis
                if imgvis != nothing
                    a = value(area)
                    mp = mp - 0.5
                    mp = (mp .* wscale(value(screen.area), a)) + minimum(a)
                    bb = value(boundingbox(imgvis[2]))
                    img = value(imgvis[1])
                    w1 = Vec2f0(widths(bb))
                    j, i = round(Int, (mp ./ w1) .* Vec2f0(size(img, 2), size(img, 1)))
                    i = size(img, 1) - i
                    if checkbounds(Bool, img, i, j) && value(screen.inputs[:mouseinside])
                        color = img[i, j]
                        return sprint() do io
                            print(io, "value at ")
                            print(io, "$i $j : ")
                            showcompact(io, color)
                            # img[i, j] = RGB(1, 0, 0)
                            # push!(imgvis[1], img)
                        end, RGBA{Float32}(color)
                    end
                end
                " ", RGBA{Float32}(1,1,1,0)
            end
            preserve(current_value)
            current_valuestr_vis = visualize(
                map(first, current_value), color = RGBA(0f0, 0f0, 0f0, 1f0),
                relative_scale = iconsize
            )
            current_value_vis = visualize(
                (ROUNDED_RECTANGLE, [Point2f0(0)]),
                color = map(last, current_value),
                scale = Vec2f0(iconsize),
                offset = Vec2f0(0)
            )

            list = GLAbstraction.Composable[
                proportion_v, reset_v,
                current_valuestr_vis, current_value_vis
            ]

            gui_list1 = visualize(
                list,
                gap = 2mm, lastposition = Vec3f0(1mm, 1mm, 0),
                direction = 1
            )
            _view(gui_list1, edit_screen, camera = :fixed_pixel)

            resetcam = map(reset_s, img_s) do reset, img_vis
                if reset && img_vis != nothing
                    reset_to_img!(img_vis[2], cam, preserveratio_s)
                end
                nothing
            end
            preserve(resetcam)
        end
    end

    function reset_to_img!(imrobj, cam, preserveratio_s)
        bb = value(boundingbox(imrobj))
        w1 = Vec2f0(widths(bb))
        if value(preserveratio_s)
            w2 = Vec2f0(widths(screen()))
            ratio = w2 ./ w1
            w1 = if ratio[1] > ratio[2]
                s = w2[1] ./ w2[2]
                Vec2f0(s * w1[2], w1[2])
            else
                s = w2[2] ./ w2[1]
                Vec2f0(w1[1], s * w1[1])
            end
        end
        p = minimum(w1) .* 0.001 # 2mm padding
        update_cam!(cam, FRect(-p, -p, w1 .+ 2p))
        nothing
    end

    function selection_rect(
            screen,
            key = GLFW.MOUSE_BUTTON_LEFT,
            button = Set([GLFW.KEY_LEFT_CONTROL, GLFW.KEY_SPACE])
        )
        @materialize mouseposition, mouse_buttons_pressed, buttons_pressed = screen.inputs
        is_dragging = false
        rect = IRect(0,0,0,0)

        dragged_rect = foldp(
                (is_dragging, rect),
                mouse_buttons_pressed, mouseposition, buttons_pressed
            ) do v0, m_pressed, m_pos, bpressed

            was_dragging, rect = v0
            keypressed = (length(m_pressed) == 1) && (key in m_pressed) && button == bpressed
            p = Vec2f0(m_pos)
            if was_dragging
                min = minimum(rect)
                wh = p - min
                rect = IRect(min, wh)
                if keypressed # was dragging and still dragging
                    return true, rect
                else
                    return false, rect # anything else will stop the dragging
                end
            elseif keypressed # was not dragging, but now key is pressed
                return true, IRect(p, 0, 0)
            end
            return v0
        end
        lw = 2f0
        rect = map(last, dragged_rect)
        visible = map(first, dragged_rect)
        prim = map(rect) do r
            x = AABB{Float32}(r)
            AABB(minimum(x) .+ Vec3f0(0,0,1), widths(x))
         end
        rect_vis = visualize(
            prim, :lines,
            visible = visible,
            pattern = [0.0, lw, 2lw, 3lw, 4lw],
            thickness = lw,
            color = RGBA(0.7f0, 0.7f0, 0.7f0, 0.9f0)
        )
        _view(rect_vis, screen, camera = :fixed_pixel)
        released = foldp((false, false), visible) do v0, v
            v, v0[1] && !v
        end
        filterwhen(map(last, released), value(screen.area), rect)
    end

    function update_cam!(cam, area)
        x, y = minimum(area)
        w, h = widths(area) ./ 2f0
        cam.window_size.value = FRect(area)
        cam.projection.value = orthographicprojection(-w, w, -h, h, -10_000f0, 10_000f0)
        cam.view.value = translationmatrix(Vec3f0(-x - w, -y - h, 0))
    end

    wscale(screenrect, viewrect) = widths(viewrect) ./ widths(screenrect)

end

using .GLImshow: imshow
using Colors
GLImshow.imshow(rand(RGBA{Float32}, 10, 10, 10))

# or try drag and drop!


text:
module FESpacesWithLinearConstraintsTests

using Gridap.Algebra
using Gridap.Arrays
using Gridap.Fields
using Gridap.Geometry
using Gridap.FESpaces
using Test
using LinearAlgebra
using Gridap.CellData
using Gridap.ReferenceFEs

domain = (0,1,0,1)
partition = (2,2)
model = CartesianDiscreteModel(domain,partition)

labels = get_face_labeling(model)
add_tag_from_tags!(labels,"dirichlet",[1,2,5])
add_tag_from_tags!(labels,"neumann",[6,7,8])

V = FESpace(
  model,ReferenceFE(lagrangian,Float64,1), conformity=:H1, dirichlet_tags="dirichlet")
test_single_field_fe_space(V)

fdof_to_val = collect(Float64,1:num_free_dofs(V))
ddof_to_val = -collect(Float64,1:num_dirichlet_dofs(V))
vh = FEFunction(V,fdof_to_val,ddof_to_val)

sDOF_to_dof = [1,5,-2]
sDOF_to_dofs = Table([[-1,4],[4,6],[-1,-3]])
sDOF_to_coeffs = Table([[0.5,0.5],[0.5,0.5],[0.5,0.5]])

Vc = FESpaceWithLinearConstraints(
  sDOF_to_dof,
  sDOF_to_dofs,
  sDOF_to_coeffs,
  V)

test_single_field_fe_space(Vc)
@test has_constraints(Vc)

scellids = SkeletonPair([1,2,1,3],[2,4,3,4])
@test isa(get_cell_constraints(Vc,scellids)[1],ArrayBlock)

@test Vc.n_fdofs == 6
@test Vc.n_fmdofs == 4

fmdof_to_val = collect(Float64,1:num_free_dofs(Vc))
dmdof_to_val = -collect(Float64,1:num_dirichlet_dofs(Vc))
vch = FEFunction(Vc,fmdof_to_val,dmdof_to_val)
r = [[-1.0, -1.5, 1.0, 1.0], [-1.5, -2.0, 1.0, 2.0], [1.0, 1.0, 3.0, 3.5], [1.0, 2.0, 3.5, 4.0]]
@test get_cell_dof_values(vch) ≈ r

v(x) = sin(4*x[1]+0.4)*cos(5*x[2]+0.7)
vch = interpolate(v,Vc)

Ω = Triangulation(model)
Γ = BoundaryTriangulation(model,tags="neumann")
Λ = SkeletonTriangulation(model)
dΩ = Measure(Ω,2)
dΓ = Measure(Γ,2)
dΛ = Measure(Λ,2)

#using Gridap.Visualization
#writevtk(Ω,"trian",nsubcells=10,cellfields=["vh"=>vh,"vch"=>vch])

u(x) = x[1] + 2*x[2]
f(x) = -Δ(u)(x)
Uc = TrialFESpace(Vc,u)
@test has_constraints(Uc)
uch = interpolate(u,Uc)

n_Γ = get_normal_vector(Γ)

a(u,v) = ∫( ∇(v)⋅∇(u) )*dΩ + ∫( jump(u)*jump(v) )*dΛ
l(v) = ∫( v*f )*dΩ + ∫( v*(n_Γ⋅∇(u)) )*dΓ

op = AffineFEOperator(a,l,Uc,Vc)
uch = solve(op)

#using Gridap.Visualization
#writevtk(trian,"trian",nsubcells=10,cellfields=["uch"=>uch])

e = u - uch

e_l2 = sqrt(sum(∫( e*e )*dΩ))
e_h1 = sqrt(sum(∫( e*e + ∇(e)⋅∇(e) )*dΩ))

tol = 1.e-9
@test e_l2 < tol
@test e_h1 < tol

end # module

ext: jl


text:
# tests for src/event_handler.jl
using MonteCarloX
using StatsBase
using Random

function test_event_handler_rate(event_handler_type::String; verbose = false)
    pass = true

    # test construction
    N = 1000
    rate0 = 0.1
    list_rate    = ones(N) * rate0
    list_event = [i for i = 1:N]
    if event_handler_type == "ListEventRateSimple"
        event_handler =    ListEventRateSimple{Int}(list_event, list_rate, 0.0, 0)
    elseif event_handler_type == "ListEventRateActiveMask"
        event_handler = ListEventRateActiveMask{Int}(list_event, list_rate, 0.0, 0)
    else
        throw(UndefVarError(:event_handler_type))
    end
    if verbose
        println("... construction")
        println("... ... rate[1]: $(event_handler.list_rate[1]) == $(rate0)")
        println("... ... rate[N]: $(event_handler.list_rate[N]) == $(rate0)")
    end
    pass &= event_handler.list_rate[1] == rate0
    pass &= event_handler.list_rate[N] == rate0

    # test length
    if verbose
        println("... length: $(length(event_handler)) = $(N)")
    end
    pass &= length(event_handler) == N

    # test setindex! - e.g. sum_rates remains correct (random changes and keep sum of changes)
    for i = 1:N
        event_handler[i] = 0.0
    end
    if verbose
        println("... set all rates to 0.0")
        println("... ... sum(rates): $(sum(event_handler.list_rate)) !> 1e-10")
        println("... ... length: $(length(event_handler)) == 0")
    end
    pass &= !(sum(event_handler.list_rate) > 1e-10)
    pass &= length(event_handler) == 0

    # test setindex! and getindex
    rng = MersenneTwister(1000)
    sum_before = sum(event_handler.list_rate)
    sum_changes = 0.0
    for i = 1:N
        value = rand(rng)
        sum_changes += value - event_handler[i]
        event_handler[i] = value
    end
    sum_expected = sum_before + sum_changes
    if verbose
        println("... set all rates random")
        println("... ... expected sum(rates): $(sum(event_handler.list_rate)) == $(sum_expected)")
        println("... ... diff: $(abs(sum(event_handler.list_rate) - sum_expected))  < 1e-10")
    end
    pass &= abs(sum(event_handler.list_rate) - sum_expected) < 1e-10

    # test changes in rate effecting the automatic update of sum(rates)
    if verbose
        println("... automatic update of sum(rates)")
    end
    for i = 1:10
        valid_sum = true
        for j = 1:1e7
            event_handler[rand(rng, 1:N)] = rand(rng)
        end
        sum_rates = 0.0
        for n=1:N
            sum_rates += event_handler[n]
        end
        if abs(sum(event_handler.list_rate) - sum_rates) < 1e-11
            valid_sum = true
        else
            valid_sum = false
        end
        if verbose
            if valid_sum
                println("... ... correct sum(rates): $(sum(event_handler.list_rate)) == $(sum_rates)")
            else
                println("... ... incorrect sum(rates): $(sum(event_handler.list_rate)) == $(sum_rates)")
            end
        end
        pass &= valid_sum
    end

    return pass
end


text:
# An irrational decimal fraction is created by concatenating the positive
# integers:
#
# 0.123456789101112131415161718192021...
#
# It can be seen that the 12th digit of the fractional part is 1.
#
# If dn represents the nth digit of the fractional part, find the value of the
# following expression.
#
# d1 × d10 × d100 × d1000 × d10000 × d100000 × d1000000

using ProjectEulerSolutions

# Estimate the number of digits of the positive integer that n lies in, then
# calculate the positive integer that n lies in, then calculate what digit of
# that number n indexes into.
function get_nth_digit(n::Integer=10)::Integer

    # Note the following patterns for numbers ndig long:
    #
    # ndig  len(seq)  start    end
    #  1     9         1        9
    #  2     90        10       99
    #  3     900       100      999
    #  4     9000      1000     9999
    #  5     90000     10000    99999

    # Find out the number of digits long the positive integers that n lies in.
    if n < 9
        return n
    end
    k = n
    ndig = 1
    while k > ndig * 9 * 10^(ndig - 1)
        k -= (ndig * 9 * 10^(ndig - 1))
        ndig += 1
    end

    startnum = 10^(ndig-1)
    innum = startnum + fld(k, ndig)
    digitsin = mod(k, ndig)
    return digitindex(innum, mod(k, ndig))
end

function p040solution(n::Integer=3)::Integer

    return prod(map(get_nth_digit, 10 .^ (0:n)))
end

p040 = Problems.Problem(p040solution)

Problems.benchmark(p040, 6)

max_stars_repo_name: gnujosh/julia-euler-project

max_issues_repo_name: gnujosh/julia-euler-project

max_forks_repo_name: gnujosh/julia-euler-project


text:
# This file is a part of JuliaFEM.
# License is MIT: see https://github.com/JuliaFEM/Materials.jl/blob/master/LICENSE

using Materials, Tensors, FEMMaterials, FEMBase, Test

analysis, problem, element, bc_elements, ip = get_one_element_material_analysis(:(Materials.IdealPlastic))
update!(element, "youngs_modulus", 200.0e3)
update!(element, "poissons_ratio", 0.3)
update!(element, "yield_stress", 100.0)

times = [0.0, 1.0, 2.0, 3.0]
loads = [0.0, 1.0e-3, -1.0e-3, 1.0e-3]
loading = AxialStrainLoading(times, loads)
update_bc_elements!(bc_elements, loading)
analysis.properties.t1 = maximum(times)

run!(analysis)
s33 = [tovoigt(ip("stress", t))[3] for t in times]
s33_expected = [0.0, 100.0, -100.0, 100.0]
@test isapprox(s33, s33_expected; rtol=1.0e-2)


text:
#
# Author: https://github.com/Clemapfel/
#

"""
logging utilities, safe in concurrent environments

# Basic Usage

There are 4 types of log message levels:

### Log / Info

To send a simple log message, similar to `Base.@info`, use `Log.@log` called with any number
of strings. These will be concatenated, similar to `Base.println`.

### Warning

To send a warning, use `Log.@warning`. The message will be displayed in yellow and should be
reserved to non-critical issues raised during execution.

### Errors

To send a critical error message, use `Log.@error`. This message will be displayed in red
and contains a stacktrace. It does not raise an actual exception, users are encouraged to
manually do so immediately proceeding the `Log.@error` call.

### Debug

To send debug messages, use `Log.@debug`. These message will not be displayed or logged,
unless `Log.set_debug_enabled(true)` was called before.

# Logging To Files

You can tell `Log` to write all its messages to a file (instead of `stdout`) by calling

```julia
Log.init("/path/to/file.log")
```

Where `"path/to/file.log"` is the log file. If it does not exist yet, it will be created. If the
file already contains text, it will be cleared and overridden.

By default, the output is in human readable form. To switch to csv (comma separated values),
instead call `Log.init("/path/to/file.log", CSV)`.

At the end of execution, call `Log.quit()` to safely close the logging environment. If the application
crashes or otherwise quits unexpectedly, all already logged message will still be in the file.
"""
module Log

    """
    enum of formatting options, decides additional log contents

    ## Values
    - `LABEL`: addes type of log message (`LOG`, `WARNING`, `EXCEPTION`, `ERROR`) as label
    - `TIMESTAMP`: adds a timestamp of the form "<hour>:<minute>:<second>"
    - `DATESTAMP`: adds a date of the from "<day>/<month>"
    - `THREADID`: native handle of current thread
    """
    @enum FormattingOptions begin
        LABEL      # print label
        TIMESTAMP  # print current time
        DATESTAMP  # print current date
        THREADID   # print id of thread write was called from
    end
    export FormattingOptions
    export LABEL
    export TIMESTAMP
    export DATESTAMP
    export THREADID

    """
    enum of formatting modes, decides the general structue of log message strings

    ## Values
    - `PRETTY`: human readable output, colored if writing to stdout
    - `CSV`: format output as CSV
    """
    @enum FormattingMode begin
        PRETTY
        CSV
    end
    export FormattingMode
    export PRETTY
    export CSV

    """
    enum of message types, if in PRETTY mode, type influences color of the message

    ## Values
    - `LOG`: grey text with `[LOG]` prefix
    - `WARNING`: yellow text with `[WARNING]` prefix
    - `EXCEPTION`: red text with `[EXCEPTION]` prefix
    - `ERROR`: blinking red text with `[ERROR]` prefix
    """
    @enum MessageType begin
        LOG
        WARNING
        EXCEPTION
        DEBUG
    end
    export MessageType
    export LOG
    export WARNING
    export EXCEPTION
    export DEBUG

    """
    internal implementation details, end-users should not interact with anything in this module
    """
    #module detail

        using Dates
        using Test
        using DataStructures

        const _init_lock = Base.ReentrantLock()
        _mode = Log.PRETTY
        _options = Log.FormattingOptions[LABEL, TIMESTAMP]

        _debug_enabled = false

        const _task_storage = Queue{Task}()
        const _task_storage_lock = Base.ReentrantLock()

        _stream = stdout
        const _stream_lock = Base.ReentrantLock()

        const _csv_delimiter = ","
        _csv_header = ""
        const _initialization_message = "Logging initialized"
        const _shutdown_message = "Logging shutdown"

        const _log_label = "LOG"
        const _warning_label = "WARNING"
        const _exception_label = "FATAL"
        const _debug_label = "DEBUG"

        const _log_color = :cyan
        const _warning_color = :light_yellow
        const _exception_color = :light_red
        const _debug_color = :magenta
        const _other_color = :light_black

        """
        `append(type::MessageType, message::String) -> Nothing`

        append a message to the log stream

        ## Arguments
        + `type`: Message Type
        + `message`: raw string
        """
        function append(type::MessageType, message::String) ::Nothing

            if type == DEBUG && !_debug_enabled
                return
            end

            lock(_task_storage_lock)

            # cleanup finished tasks
            while !isempty(_task_storage) && istaskdone(first(_task_storage))
                dequeue!(_task_storage)
            end

            enqueue!(_task_storage, Task(() -> begin

                out::String = ""
                m = deepcopy(message)
                now = Dates.now()

                function add_zero(num) ::String
                    out = ""
                    if num < 10 out *= "0" end
                    return out * string(num)
                end

                if _mode == CSV

                    # type
                    if LABEL in _options
                        out *= string(type) * _csv_delimiter
                    end

                    # day, month
                    if DATESTAMP in _options
                        out *= string(Dates.day(now)) * _csv_delimiter
                        out *= string(Dates.month(now)) * _csv_delimiter
                    end

                    # time
                    if TIMESTAMP in _options
                        out *= string(Dates.format(Dates.now(), DateFormat("H:M:S.MS"))) * _csv_delimiter
                    end

                    # thread_id
                    if THREADID in _options
                        out *= string(Threads.threadid()) * _csv_delimiter
                    end

                    # message
                    out *= message * "\n"

                    @lock _stream_lock begin
                        Base.write(_stream, out)
                        flush(_stream)
                    end

                elseif _mode == PRETTY

                    if LABEL in _options

                        if !(_stream isa IOBuffer)

                            if type == LOG
                                printstyled(_stream, "[" * _log_label * "]", color=_log_color)
                            elseif type == WARNING
                                printstyled(_stream, "[" * _warning_label * "]", color=_warning_color)
                            elseif type == EXCEPTION
                                printstyled(_stream, "[" * _exception_label * "]", color=_exception_color)
                            elseif type == DEBUG
                                printstyled(_stream, "[" * _debug_label * "]", color=_debug_color)
                            end
                        else

                            if type == LOG
                                out *= "[" * _log_label * "]"
                            elseif type == WARNING
                                out *= "[" * _warning_label * "]"
                            elseif type == EXCEPTION
                                out *= "[" * _exception_label * "]"
                            elseif type == DEBUG
                                out *= "[" * _debug_label * "]"
                            end
                        end
                    end

                    if TIMESTAMP in _options || DATESTAMP in _options

                        out *= "["

                        if DATESTAMP in _options
                            out *= add_zero(Dates.day(now)) * "."
                            out *= add_zero(Dates.month(now)) * "-"
                        end

                        if DATESTAMP in _options && TIMESTAMP in _options
                           out *= "|"
                        end

                        if TIMESTAMP in _options
                           out *= add_zero(Dates.hour(now)) * ":"
                            out *= add_zero(Dates.minute(now)) * ":"
                            out *= add_zero(Dates.second(now))
                        end

                        out *= "]"
                    end

                    if THREADID in _options
                        out *= "[" * Threads.threadid() * "]"
                    end

                    if length(_options) >= 1 # more than one char left of the message
                        out *= " "
                    end

                    printstyled(_stream, out, color=_other_color)
                    print(_stream, m * "\n")
                    flush(_stream)
                end
            end))

            # when running non-concurrently, immediately evaluate in main
            if Threads.nthreads() == 1
                schedule(last(_task_storage))
                wait(last(_task_storage))
            else
                last(_task_storage).sticky = false
                schedule(last(_task_storage))
            end

            unlock(_task_storage_lock)
            return nothing
        end
        # no export

        """
        `test() -> Nothing`

        testset of module `Log`
        """
        function test() ::Nothing

            Test.@testset "Logging" begin

                try

                Log.init(Base.Filesystem.pwd() * "/_.log", CSV, [Log.TIMESTAMP, Log.DATESTAMP, Log.THREADID])

                Test.@test Base.Filesystem.isfile(Log._stream)
                Test.@test isopen(Log._stream)

                Log.write("test line")
                Log.quit()
                Test.@test !isopen(Log._stream)

                file = open(Base.Filesystem.pwd() * "/_.log", read=true)

                Test.@test occursin(_csv_header, readline(file, keep=true))
                Test.@test occursin(Log._initialization_message, readline(file))
                Test.@test occursin("test line", readline(file))

                finally Base.Filesystem.rm(Base.Filesystem.pwd() * "/_.log") end
            end
            return nothing
        end
        # no export
    #end

    """
    `write(xs::Any...; [message_type::MessageType]) -> Nothing`

    write to the log stream. If julia was initialized with more than 1 thread,
    writing is concurrent and does not pause the main thread.

    ## Arguments
    + `xs`: any number of objects, will be converted to strings, similar to Base.print
    + `message_type`: [optional] one of `LOG`, `WARNING`, `EXCEPTION`, `ERROR`
    """
    function write(xs...; type::MessageType = LOG)

        if length(xs) == 1 && string(getindex(xs, 1)) == ""
            return nothing
        end

        append(type, prod(string.([xs...])))
        yield()
    end
    export write

    """
    `initialize([path::String], [mode::FormattingMode], [options::Vector{FormattingOptions}]) -> Bool`

    initialize the logging environment

    ## Arguments
    + `path`: [optional] path of the log output file, or `""` if the log should write to stdout instead
    + `mode`: [optional] `PRETTY` for human-readable output, `CSV` for csv output with delimiter `,`
    + `options`: [optional] vector of FormattingOptions. Vector may contain:
        - `LABEL` for type of message, such as `[LOG]`, `[WARNING]`, etc.
        - `TIMESTAMP` time in `Y:M:S` format if in `PRETTY` mode, `Y:M:S.MS` if in `CSV` mode
        - `DATESTAMP` current day and month
        - `THREADID` native handle of the thread `Log.write` is called from

    ## Returns
    `true` if initialization was successful, `false` otherwise
    """
    function init(
        path::String = "",
        mode::FormattingMode = PRETTY,
        options::Vector{FormattingOptions} = (path == "" ? [LABEL] : [LABEL, DATESTAMP, TIMESTAMP])
    ) ::Bool

        @lock _init_lock begin

            if path != ""
                eval(:(_stream = open($path, append=true, truncate=true)))
            else
                eval(:(_stream = stdout))
            end

            eval(:(_mode = $mode))
            eval(:(_options = $options))

            if mode == CSV

                csv_header = ""

                if LABEL in options
                    csv_header *= "type" * _csv_delimiter
                end

                if DATESTAMP in options
                   csv_header *= "day" * _csv_delimiter
                   csv_header *= "month" * _csv_delimiter
                end

                if TIMESTAMP in options
                    csv_header *= "time" * _csv_delimiter
                end

                if THREADID in options
                    csv_header *= "thread_id" * _csv_delimiter
                end

                csv_header *= "message" * "\n"

                eval(:(_csv_header = $csv_header))
            end
        end

        out = isopen(_stream)

        if !out
           Log.write("in Log.init(" * path * ") : initialization failed.")
        else
            if mode == CSV
                Base.write(_stream, _csv_header)
            end
            Log.write(_initialization_message)
        end
        return out
    end
    export init

    """
    `quit() -> Bool`

    safely exist the logging environment

    ## Returns
    `true` if shutdown was successful, false otherwise
    """
    function quit() ::Bool

        for task in _task_storage
            wait(task)
        end
        Log.write(_shutdown_message)

        try
            lock(_task_storage_lock)
            lock(_init_lock)

            for task in _task_storage
                wait(task)
            end

            empty!(_task_storage)

            if _stream isa IOStream
                close(_stream)
            end

            return true
        catch (_)
            return false
        end
    end

    """
    `set_debug_enabled(::Bool) -> Nothing`

    enabled debug mode, unless specifically enabled, all
    logging with type=DEBUG will not be printed or appended to the log file
    """
    function set_debug_enabled(value::Bool)

        lock(_init_lock)
        if value
            Log.write("Debug logging enabled", type=LOG)
        else
            Log.write("Debug loggin disabled", type=LOG)
        end
        eval(:(global _debug_enabled = $value))
        unlock(_init_lock)
        return nothing
    end

    """
    `log(::Expr) -> Nothing`

    convert any arguments to strings, then print as log message
    """
    macro log(xs)
        :(write($(esc(xs))))
    end
    export log

    """
    `warning(::Expr) -> Nothing`

    convert any arguments to strings, then print as warning message
    """
    macro warning(xs)
        :(write($(esc(xs)), type = WARNING))
    end
    export warning

    """
    `debug(::Expr) -> Nothing`

    convert any arguments to strings, then print as debug message
    if `Log.set_debug_enabled(true)` was called before
    """
    macro debug(xs)
        :(write($(esc(xs)), type = DEBUG))
    end
    export debug

    """
    `error(::Expr) -> Nothing`

    write to the log and print stacktrace, does not actually raise an exception
    """
    macro error(xs)
        :(write($(esc(xs)), type = EXCEPTION))
    end
end


text:
using Test, Infiltrator, REPL

foo = 3
function f(x)
    x = 2
    y = [1, 2, 3]
    @infiltrate
    return x .+ y
end

function g(x)
    x *= 12
    @infiltrate x > 12
    return x
end

h(x) = [f(x) for x in x]

function i(x)
    y = [1.0 for _ in 1:x]
    @infiltrate
    return y
end

function j(x)
    xxxxx = 4
    @infiltrate
    return x*xxxxx
end

@testset "infiltration tests" begin
    if Sys.isunix() && VERSION >= v"1.1.0"
        using TerminalRegressionTests

        function run_terminal_test(func, result, commands, validation)
            TerminalRegressionTests.automated_test(joinpath(@__DIR__, validation), commands) do emuterm
            # TerminalRegressionTests.create_automated_test(joinpath(@__DIR__, validation), commands) do emuterm
                Infiltrator.end_session!()
                repl = REPL.LineEditREPL(emuterm, true)
                repl.interface = REPL.setup_interface(repl)
                repl.specialdisplay = REPL.REPLDisplay(repl)

                Infiltrator.TEST_TERMINAL_REF[] = repl.t
                Infiltrator.TEST_NOSTACK[] = true
                Infiltrator.TEST_REPL_REF[] = repl
                @test func() == result
                Infiltrator.TEST_TERMINAL_REF[] = nothing
                Infiltrator.TEST_NOSTACK[] = false
                Infiltrator.TEST_REPL_REF[] = nothing
            end
        end

        run_terminal_test(() -> f(3), [3, 4, 5],
                        ["?\n", "@trace\n", "@locals\n", "x.*y\n", "3+\n4\n", "foo\n", "0//0\n", "@toggle\n", "@toggle\n", "@toggle\n", "\x4"],
                        "Julia_f_$(VERSION.major).$(VERSION.minor).multiout")

        @test f(3) == [3, 4, 5] # `@toggle`d `@infiltrate` should not open a prompt

        Infiltrator.clear_disabled!()

        run_terminal_test(() -> f(3), [3, 4, 5],
                        ["@locals\n", "\x4"],
                        "Julia_f2_$(VERSION.major).$(VERSION.minor).multiout")

        @test g(1) == 12 # conditional @infiltrate should not open a prompt

        run_terminal_test(() -> g(2), 24,
                        ["?\n", "@trace\n", "@locals\n", "x\n", "\x4"],
                        "Julia_g_$(VERSION.major).$(VERSION.minor).multiout")

        run_terminal_test(() -> h([1,2,3]), [[3,4,5], [3,4,5], [3,4,5]],
                        ["\x4", "@locals\n", "@exit\n"],
                        "Julia_h_$(VERSION.major).$(VERSION.minor).multiout")

        run_terminal_test(() -> i(1000), i(1000),
                        ["2+2\n", "@locals\n", "\x4"],
                        "Julia_i_$(VERSION.major).$(VERSION.minor).multiout")

        # scratch pad test
        run_terminal_test(() -> g(2), 24,
                        ["@locals\n", "xxxxx = 12\n", "foo(x) = x\n", "function bar(x); 2x; end\n", "x = 2\n", "\x4"],
                        "Julia_exfil_$(VERSION.major).$(VERSION.minor).multiout")

        @test Infiltrator.store.xxxxx == 12
        @test Infiltrator.store.foo(3) == 3
        @test Infiltrator.store.bar(3) == 6
        @test !isdefined(getfield(Infiltrator.store, :store), :x)

        # proper scoping of scratch pad
        run_terminal_test(() -> j(2), 8,
                        ["@locals\n", "@exfiltrate\n", "\x4"],
                        "Julia_scoping_$(VERSION.major).$(VERSION.minor).multiout")

        @test Infiltrator.store.xxxxx == 4

        # persistent history
        run_terminal_test(() -> h([1,2,3]), [[3,4,5], [3,4,5], [3,4,5]],
                        ["y\n", "\e[A\n", "\x4", "\e[A\n", "@exit\n"],
                        "Julia_hist_$(VERSION.major).$(VERSION.minor).multiout")
    else
        @warn "Skipping UI tests on non unix systems"
    end
end

@testset "exfiltration tests" begin
    Infiltrator.clear_store!()
    function foo_ex(x)
        y = 3
        foo = :asd
        store = 33
        bar = function (yy) yy end
        @exfiltrate
    end
    foo_ex(55)

    @test Infiltrator.store.y == 3
    @test Infiltrator.store.foo == :asd
    @test Infiltrator.store.store == 33
    @test Infiltrator.store.bar(3) == 3
    @test_throws UndefVarError Infiltrator.store.asd

    # `@with` is basically for dynamic usage only
    @test 6 == Core.eval(@__MODULE__, :(Infiltrator.@withstore(2y)))
    @test "asd" == Core.eval(@__MODULE__, :(Infiltrator.@withstore(string(foo))))
end


text:
module FrostHelperTempLockblock

using ..Ahorn, Maple

@mapdef Entity "FrostHelper/TemporaryKeyDoor" TempLockBlock(x::Integer, y::Integer, sprite::String="wood", unlock_sfx::String="", stepMusicProgress::Bool=false)

sprites = Dict{String, String}(
    "wood" => "objects/door/lockdoor00",
    "temple_a" => "objects/door/lockdoorTempleA00",
    "temple_b" => "objects/door/lockdoorTempleB00",
    "moon" => "objects/door/moonDoor11"
)

const placements = Ahorn.PlacementDict(
    "Temporary Locked Door ($(Ahorn.humanizeVariableName(sprite)), Frost Helper)" => Ahorn.EntityPlacement(
        TempLockBlock,
        "point",
        Dict{String, Any}(
            "sprite" => sprite
        )
    ) for (sprite, texture) in sprites
)

Ahorn.editingOptions(entity::TempLockBlock) = Dict{String, Any}(
    "sprite" => sort(collect(keys(sprites)))
)

function Ahorn.selection(entity::TempLockBlock)
    x, y = Ahorn.position(entity)

    return Ahorn.Rectangle(x, y, 32, 32)
end

function Ahorn.render(ctx::Ahorn.Cairo.CairoContext, entity::TempLockBlock, room::Maple.Room)
    sprite = get(entity.data, "sprite", "wood")

    if haskey(sprites, sprite)
        Ahorn.drawSprite(ctx, sprites[sprite], 16, 16)
    end
end

end

max_stars_repo_name: JaThePlayer/FrostHelper

max_issues_repo_name: JaThePlayer/FrostHelper

max_forks_repo_name: JaThePlayer/FrostHelper


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

mutable struct IoK8sApiAuthorizationV1NonResourceRule <: SwaggerModel
    nonResourceURLs::Any # spec type: Union{ Nothing, Vector{String} } # spec name: nonResourceURLs
    verbs::Any # spec type: Union{ Nothing, Vector{String} } # spec name: verbs

    function IoK8sApiAuthorizationV1NonResourceRule(;nonResourceURLs=nothing, verbs=nothing)
        o = new()
        validate_property(IoK8sApiAuthorizationV1NonResourceRule, Symbol("nonResourceURLs"), nonResourceURLs)
        setfield!(o, Symbol("nonResourceURLs"), nonResourceURLs)
        validate_property(IoK8sApiAuthorizationV1NonResourceRule, Symbol("verbs"), verbs)
        setfield!(o, Symbol("verbs"), verbs)
        o
    end
end # type IoK8sApiAuthorizationV1NonResourceRule

const _property_map_IoK8sApiAuthorizationV1NonResourceRule = Dict{Symbol,Symbol}(Symbol("nonResourceURLs")=>Symbol("nonResourceURLs"), Symbol("verbs")=>Symbol("verbs"))
const _property_types_IoK8sApiAuthorizationV1NonResourceRule = Dict{Symbol,String}(Symbol("nonResourceURLs")=>"Vector{String}", Symbol("verbs")=>"Vector{String}")
Base.propertynames(::Type{ IoK8sApiAuthorizationV1NonResourceRule }) = collect(keys(_property_map_IoK8sApiAuthorizationV1NonResourceRule))
Swagger.property_type(::Type{ IoK8sApiAuthorizationV1NonResourceRule }, name::Symbol) = Union{Nothing,eval(Meta.parse(_property_types_IoK8sApiAuthorizationV1NonResourceRule[name]))}
Swagger.field_name(::Type{ IoK8sApiAuthorizationV1NonResourceRule }, property_name::Symbol) =  _property_map_IoK8sApiAuthorizationV1NonResourceRule[property_name]

function check_required(o::IoK8sApiAuthorizationV1NonResourceRule)
    (getproperty(o, Symbol("verbs")) === nothing) && (return false)
    true
end

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


text:
function setup_model(wordembeds)
    T = Float32
    x = Var()
    y = wordembeds(x)
    h = Linear(T,100,100)(y)
    d = Linear(T,100,100)(y)
    y = pairwise(d, h)
    y = reshape4d(y)
    y = Conv(T, (3,3,200,1), pads=(1,1))(y)
    y = pooling(:max, y, (3,3), pads=(1,1))
    y = y[:,:]
    compile(y, x)
end

max_stars_repo_name: hshindo/PairwiseMatrix

max_issues_repo_name: hshindo/PairwiseMatrix

max_forks_repo_name: hshindo/PairwiseMatrix


text:
module Vector

end

max_stars_repo_name: PseudoDevelopers/Physics-Simulations

max_issues_repo_name: PseudoDevelopers/Physics-Simulations

max_forks_repo_name: PseudoDevelopers/Physics-Simulations


text:
using Distributed
addprocs()

using Gadfly, DataFrames, Colors, RCall, Compose
@everywhere using Distributions, StatsBase, Distances, SharedArrays

function gen_colors(n)
    cs = distinguishable_colors(n,
        [colorant"#66c2a5", colorant"#fc8d62", colorant"#8da0cb", colorant"#e78ac3",
            colorant"#a6d854", colorant"#ffd92f", colorant"#e5c494", colorant"#b3b3b3"],
        lchoices=Float64[58, 45, 72.5, 90],
        transform=c->deuteranopic(c, 0.1),
        cchoices=Float64[20,40],
        hchoices=[75,51,35,120,180,210,270,310]
    )
    convert(Vector{Color}, cs)
end

@everywhere const n_agents = 50
@everywhere const n_steps = 50

@everywhere function bc_upd_rad(ϵ::Float64, r_opinion::Float64, n_radicals::Int64, averaging)
    rd = fill(r_opinion, n_radicals)
    bc_ar = Array{Float64,2}(undef, n_agents, n_steps + 1)
    bc_ar[:, 1] = rand(n_agents)
    @views @inbounds for j in 1:n_steps, i in 1:n_agents
        cc = vcat(bc_ar[:, j], rd)
        fa = findall(@. abs(cc - cc[i]) <= ϵ)
        bc_ar[i, j + 1] = averaging(cc[fa])
    end
    return bc_ar
end

@everywhere function bc_upd_rad(ϵ::Float64, α::Float64, τ::Float64, r_opinion::Float64, n_radicals::Int64, averaging)
    rd = fill(r_opinion, n_radicals)
    bc_ar = Array{Float64,2}(undef, n_agents, n_steps + 1)
    bc_ar[:, 1] = rand(n_agents)
    @views @inbounds for j in 1:n_steps, i in 1:n_agents
        cc = vcat(bc_ar[:, j], rd)
        fa = findall(@. abs(cc - cc[i]) <= ϵ)
        bc_ar[i, j + 1] = α*averaging(cc[fa]) + (1 - α)*τ
    end
    return bc_ar
end

function cost_sim(ϵ::Float64, α::Float64, τ::Float64, r_opinion::Float64, n_radicals::Int64, averaging, n_sim::Int64)
    v= SharedArray{Float64,1}(n_sim)
    @inbounds @sync @distributed for i in 1:n_sim
        res_rad = bc_upd_rad(ϵ, α, τ, r_opinion, n_radicals, averaging)
        v[i] = sum(map(i->(i-τ)^2, res_rad))
    end
    return v
end

τ = .1
ϵ = .2
α = .5
ρ1 = .3
ρ2 = .5
ρ3 = .7
nsim = 1000
without = cost_sim(ϵ, α, τ, ρ1, 0, mean, nsim)
withNarrow = cost_sim(ϵ, α, τ, ρ1, 25, mean, nsim)
withModerate = cost_sim(ϵ, α, τ, ρ2, 25, mean, nsim)
withWide = cost_sim(ϵ, α, τ, ρ3, 25, mean, nsim);

mns = DataFrame(WO = without[:], WN = withNarrow[:], WM = withModerate[:], WW = withWide[:]);

plot(mns, x=Col.index, y=Col.value,
    Geom.boxplot,
    Scale.x_discrete(levels=names(mns)),
    Guide.xlabel("Condition"),
    Guide.ylabel("SSE"),
    Guide.title("τ = $τ, ρ = $ρ1/$ρ2/$ρ3 (WN/WM/WW), ϵ = $ϵ, α = $α"),
    Theme(default_color=colorant"#66c2a5", panel_fill="white"))

mean(without), mean(withNarrow), mean(withModerate), mean(withWide)

std(without), std(withNarrow), std(withModerate), std(withWide)

@rput df_aov

R"""
m <- aov(data ~ groups, data=df_aov)
summary(m)
"""

R"TukeyHSD(m)"

R"library(lsr)"

R"etaSquared(m)"

@everywhere function bc_upd_ri(ϵ::Float64,
                               α::Float64,
                               τ::Float64,
                               r_opinion::Float64,
                               n_truthseekers::Int64,
                               n_indifs::Int64,
                               n_radicals::Int64,
                               averaging)
    n_agents = n_truthseekers + n_indifs
    rd = fill(r_opinion, n_radicals)
    bc_ar = Array{Float64,2}(undef, n_agents, n_steps + 1)
    bc_ar[:, 1] = rand(n_agents)
    @views @inbounds for j in 1:n_steps, i in 1:n_agents
        cc = vcat(bc_ar[:, j], rd)
        fa = findall(@. abs(cc - cc[i]) <= ϵ)
        bc_ar[i, j + 1] = i <= n_truthseekers ? α*averaging(cc[fa]) + (1 - α)*τ : averaging(cc[fa])
    end
    return bc_ar
end

function cost_sim_ri(ϵ::Float64,
                     α::Float64,
                     τ::Float64,
                     r_opinion::Float64,
                     n_truthseekers::Int64,
                     n_indifs::Int64,
                     n_radicals::Int64,
                     averaging,
                     n_sim::Int64)
    v= SharedArray{Float64,1}(n_sim)
    @inbounds @sync @distributed for i in 1:n_sim
        res_rad = bc_upd_ri(ϵ, α, τ, r_opinion, n_truthseekers, n_indifs, n_radicals, averaging)
        v[i] = sum(map(i->(i-τ)^2, res_rad[1:n_truthseekers, :]))
    end
    return v
end

τ = .1
ϵ = .2
α = .5
ρ1 = .3
ρ2 = .5
ρ3 = .7
nsim = 1000
without = cost_sim_ri(ϵ, α, τ, ρ1, 50, 25, 0, mean, nsim)
withNarrow = cost_sim_ri(ϵ, α, τ, ρ1, 50, 25, 25, mean, nsim)
withModerate = cost_sim_ri(ϵ, α, τ, ρ2, 50, 25, 25, mean, nsim)
withWide = cost_sim_ri(ϵ, α, τ, ρ3, 50, 25, 25, mean, nsim);

mns = DataFrame(WO = without[:], WN = withNarrow[:], WM = withModerate[:], WW = withWide[:]);

plot(mns, x=Col.index, y=Col.value,
    Geom.boxplot,
    Scale.x_discrete(levels=names(mns)),
    Guide.xlabel("Condition"),
    Guide.ylabel("SSE"),
    Guide.title("τ = $τ, ρ = $ρ1/$ρ2/$ρ3 (WN/WM/WW), ϵ = $ϵ, α = $α"),
    Theme(default_color=colorant"#66c2a5", panel_fill="white"))

τ = .1
ϵ = .3
α = .75
ρ = .3
nsim = 1000
without = cost_sim_ri(ϵ, α, τ, ρ, 50, 0, 15, mean, nsim)
with10 = cost_sim_ri(ϵ, α, τ, ρ, 50, 10, 15, mean, nsim)
with25 = cost_sim_ri(ϵ, α, τ, ρ, 50, 25, 15, mean, nsim)
with50 = cost_sim_ri(ϵ, α, τ, ρ, 50, 50, 15, mean, nsim);

mns = DataFrame(X = without[:], Y = with10[:], Z = with25[:], W = with50[:])

rename!(mns, :X => Symbol("0"), :Y => Symbol("10"), :Z => Symbol("25"), :W => Symbol("50"))

plot(mns, x=Col.index, y=Col.value,
    Geom.boxplot,
    Scale.x_discrete(levels=names(mns)),
    Guide.xlabel("Free riders"),
    Guide.ylabel("SSE"),
    Guide.title("τ = $τ, ρ = $ρ, ϵ = $ϵ, α = $α"),
    Theme(default_color=colorant"#66c2a5", panel_fill="white"))

@rput df_aov

R"""
m <- aov(data ~ groups, data=df_aov)
summary(m)
"""

R"TukeyHSD(m)"

R"etaSquared(m)"

mean(without), mean(with10), mean(with25), mean(with50)

std(without), std(with10), std(with25), std(with50)

max_stars_repo_name: IgorDouven/Misinformation

max_issues_repo_name: IgorDouven/Misinformation

max_forks_repo_name: IgorDouven/Misinformation


text:
using Sims
using NineML
using Winston

al = NineML.parse_ComponentClass("IzhikevichFS_AL.xml")
uls = NineML.parse_Components("IzhikevichFS_UL.xml")

tf = 100.0
dt = 0.025

for ul in uls

    NineML.eval_Dynamics(al.dynamics, ul.name, ul.parameterValues, ul.initialValues, al.parameters, al.states, al.ports)
    modelname = ul.name

    izhfs = eval(quote $modelname () end)
    izhfs_s = create_sim(izhfs)
    izhfs_ptr = setup_sunsim(izhfs_s)

    izhfs_yout = sunsim(izhfs_ptr, tf, int(tf/dt))
    f = figure()
    pl = plot (izhfs_yout.y[:,1], izhfs_yout.y[:,2])
    display(pl)
end


text:
abstract type AbstractHydroModel end

function show(io::IO, ::MIME"text/plain", hydromodel::AbstractHydroModel)
    show(io,hydromodel)
end

function modelname(hydromodel::M) where M <: AbstractHydroModel
    typename = string(M)
    chompname = match(r"(?:[^{]*\.)*([A-Za-z]+)(?:{.*})*",typename)
    modelname = split(chompname.captures[1],"Model")[1]
    return join(split(modelname,r"(?<!^)(?=[A-Z])")," ")
end

horizon(hydromodel::AbstractHydroModel) = hydromodel.horizon

function status(hydromodel::AbstractHydroModel)
    # Maybe internalModelLoaded here? check JuMP
    return hydromodel.status
end

function plan!(hydromodel::AbstractHydroModel; optimsolver = GLPKSolverLP())
    setsolver(hydromodel.internalmodel, optimsolver)
    solvestatus = solve(hydromodel.internalmodel)
    if solvestatus == :Optimal
        hydromodel.status = :Planned
    else
        hydromodel.status = :Failed
    end
    return hydromodel
end

function production(hydromodel::AbstractHydroModel)
    status(hydromodel) == :Planned || error("Hydro model has not been planned yet")

    return HydroProductionPlan(hydromodel)
end

# struct DeterministicHydroModel <: AbstractHydroModel

# end

# function show(io::IO, hydromodel::DeterministicHydroModel)
#     if get(io, :multiline, false)
#         print(io,string("Deterministic Hydro Power Model : ", modelname(hydromodel), ", including ", length(plants(hydromodel.indices)), " power stations, over a ", nhours(hydromodel.horizon), " hour horizon ", horizonstring(hydromodel.horizon)))
#     else
#         println(io,string("Deterministic Hydro Power Model : ", modelname(hydromodel)))
#         println(io,string("    including ", length(plants(hydromodel.indices)), " power stations"))
#         println(io,string("    over a ", nhours(hydromodel.horizon), " hour horizon ", horizonstring(hydromodel.horizon)))
#         println(io,"")
#         if status(hydromodel) == :Unplanned
#             print(io,"Not yet planned")
#         elseif status(hydromodel) == :Planned
#             print(io,"Optimally planned")
#         elseif status(hydromodel) == :Failed
#             print(io,"Could not be planned")
#         else
#             error(string(hydromodel.status, " is not a valid model status"))
#         end
#     end
# end

# function define_problem!(hydromodel::DeterministicHydroModel)
#     model = Model()
#     hydromodel.generator(model,hydromodel.horizon,hydromodel.data,hydromodel.indices)
#     hydromodel.internalmodel = model
#     hydromodel.status = :Unplanned
#     nothing
# end

# function reload!(hydromodel::DeterministicHydroModel, data::AbstractModelData, args...)
#     hydromodel.data = data
#     reinitialize!(hydromodel,args...)
#     return hydromodel
# end

# function reinitialize!(hydromodel::DeterministicHydroModel, horizon::Horizon, args...)
#     hydromodel.horizon = horizon
#     hydromodel.indices = modelindices(hydromodel.data, horizon, args...)
#     define_problem!(hydromodel)
#     return hydromodel
# end

mutable struct StochasticHydroModel{D <: AbstractModelData,
                                    I <: AbstractModelIndices,
                                    SM <: StochasticModel,
                                    SP <: StochasticProgram} <: AbstractHydroModel
    name::String
    horizon::Horizon
    data::D
    indices::I
    stochasticmodel::SM
    internalmodel::SP
    status::Dict{Symbol,Symbol}

    function StochasticHydroModel(name::String,
                                  horizon::Horizon,
                                  data::AbstractModelData,
                                  modelgenerator::Function,
                                  scenarios::Vector{<:AbstractScenario}; kw...)
        D = typeof(data)
        indices = modelindices(data, horizon; kw...)
        I = typeof(indices)
        stochasticmodel = modelgenerator(horizon, data, indices)
        SM = typeof(stochasticmodel)
        sp = instantiate(stochasticmodel, scenarios; horizon = horizon, indices = indices, data = data)
        SP = typeof(sp)
        hydromodel = new{D,I,SM,SP}(name, horizon, data, indices, stochasticmodel, sp, Dict(:rp=>:Unplanned,:evp=>:Unplanned))
        return hydromodel
    end

    function StochasticHydroModel(name::String,
                                  horizon::Horizon,
                                  data::AbstractModelData,
                                  modelgenerator::Function,
                                  sampler::AbstractSampler{S},
                                  n::Integer; kw...) where S <: AbstractScenario
        D = typeof(data)
        indices = modelindices(data, horizon; kw...)
        I = typeof(indices)
        stochasticmodel = modelgenerator(horizon, data, indices)
        SM = typeof(stochasticmodel)
        sp = instantiate(stochasticmodel, sampler, n)
        SP = typeof(sp)
        hydromodel = new{D,I,SM,SP}(name, horizon, data, indices, stochasticmodel, sp, Dict(:rp=>:Unplanned,:evp=>:Unplanned))
        return hydromodel
    end
end

function show(io::IO, hydromodel::StochasticHydroModel)
    if get(io, :multiline, false)
        print(io,string("Stochastic Hydro Power Model : ", modelname(hydromodel), ", including ", length(plants(hydromodel.indices)), " power stations, over a ", num_hours(hydromodel.horizon), " hour horizon ", horizonstring(hydromodel.horizon)), " featuring ", num_scenarios(hydromodel.internalmodel), " scenarios")
    else
        println(io,string("Stochastic Hydro Power Model : ", modelname(hydromodel)))
        println(io,string("    including ", length(plants(hydromodel.indices)), " power stations"))
        println(io,string("    over a ", num_hours(hydromodel.horizon), " hour horizon ", horizonstring(hydromodel.horizon)))
        println(io,string("    featuring ", num_scenarios(hydromodel.internalmodel), " scenarios"))
        println(io,"")
        showstatus(io,hydromodel)
    end
end

function modelname(hydromodel::StochasticHydroModel)
    return hydromodel.name
end

showstatus(hydromodel::StochasticHydroModel) = showstatus(Base.STDOUT,hydromodel)
function showstatus(io::IO,hydromodel::StochasticHydroModel)
    statstrs = Dict(:Unplanned=>"Not yet planned",:Planned=>"Optimally planned",:Failed=>"Could not be planned")
    println(io,string("Recourse Problem: ", statstrs[status(hydromodel;variant=:rp)]))
    print(io,string("Expected Value Problem: ", statstrs[status(hydromodel;variant=:evp)]))
end

function status(hydromodel::StochasticHydroModel; variant = :rp)
    return hydromodel.status[variant]
end

function reload!(hydromodel::StochasticHydroModel, horizon::Horizon, data::AbstractModelData, scenarios::Vector{<:AbstractScenario}, args...)
    StochasticPrograms.remove_subproblems!(hydromodel.internalmodel)
    add_scenarios!(hydromodel.internalmodel, scenarios)
    hydromodel.data = data
    reinitialize!(hydromodel, horizon, args...)
    return hydromodel
end

function reload!(hydromodel::StochasticHydroModel, horizon::Horizon, data::AbstractModelData, sampler::AbstractSampler, n::Integer; kw...)
    hydromodel.data = data
    reinitialize!(hydromodel, horizon, sampler, n; kw...)
    return hydromodel
end

function reinitialize!(hydromodel::StochasticHydroModel, horizon::Horizon; kw...)
    hydromodel.horizon = horizon
    hydromodel.indices = modelindices(hydromodel.data, horizon; kw...)
    scenariodata = scenarios(hydromodel.internalmodel)
    hydromodel.internalmodel = instantiate(hydromodel.stochasticmodel,
                                           scenariodata;
                                           horizon = hydromodel.horizon,
                                           indices = hydromodel.indices,
                                           data = hydromodel.data)
    hydromodel.status[:rp] = :Unplanned
    hydromodel.status[:evp] = :Unplanned
    return hydromodel
end

function reinitialize!(hydromodel::StochasticHydroModel, horizon::Horizon, sampler::AbstractSampler, n::Integer; kw...)
    hydromodel.horizon = horizon
    hydromodel.indices = modelindices(hydromodel.data, horizon; kw...)
    hydromodel.internalmodel = instantiate(hydromodel.stochasticmodel,
                                           sampler,
                                           n;
                                           horizon = hydromodel.horizon,
                                           indices = hydromodel.indices,
                                           data = hydromodel.data)
    hydromodel.status[:rp] = :Unplanned
    hydromodel.status[:evp] = :Unplanned
    return hydromodel
end

function plan!(hydromodel::StochasticHydroModel; variant = :rp, optimsolver = GLPKSolverLP())
    if variant == :rp
        StochasticPrograms.optimize!(hydromodel.internalmodel)
    elseif variant == :evp
        evp = EVP(hydromodel.internalmodel, solver = optimsolver)
        solve(evp)
    else
        error("Unknown variant: ",variant)
    end

    if termination_status(hydromodel.internalmodel) == MOI.OPTIMAL
        hydromodel.status[variant] = :Planned
    else
        hydromodel.status[variant] = :Failed
    end
    return hydromodel
end
plan_rp!(hydromodel::StochasticHydroModel) = plan!(hydromodel,:rp)
plan_evp!(hydromodel::StochasticHydroModel) = plan!(hydromodel,:evp)

# macro hydromodel(variant,def)
#     @capture(def,name_Symbol = modeldef_) || error("Invalid syntax. Expected modelname = begin JuMPdef end")
#     modelname = Symbol(name,:Model)
#     # Fix horizon if applicable
#     fixhorizondef = Expr(:block)
#     modeldef = postwalk(modeldef) do x
#         @capture(x, @fixhorizon horizon_) || return x
#         fixhorizondef = @q begin
#             function $(esc(modelname))(data::AbstractModelData, args...; kw...)
#                 return $(esc(modelname))($horizon, data, args...; kw...)
#             end
#             function reload!(hydromodel::$(esc(modelname)), args...; kw...)
#                 reload!(hydromodel, $horizon, args...; kw...)
#                 return hydromodel
#             end
#             function reinitialize!(hydromodel::$(esc(modelname)), args...; kw...)
#                 reinitialize!(hydromodel, $horizon, args...; kw...)
#                 return hydromodel
#             end
#         end
#         return :()
#     end
#     # Define new deterministic/stochastic model type
#     code = if variant == :Deterministic
#         code = @q begin
#             mutable struct $(esc(modelname)){$(esc(:D)) <: AbstractModelData,
#                                              $(esc(:I)) <: AbstractModelIndices} <: DeterministicHydroModel
#                 horizon::Horizon
#                 data::$(esc(:D))
#                 indices::$(esc(:I))
#                 generator::Function
#                 status::Symbol
#                 internalmodel::JuMP.Model

#                 function $(esc(modelname))(horizon::Horizon, data::AbstractModelData; args...)
#                     D = typeof(data)
#                     generator = ($(esc(:model)), $(esc(:horizon)), $(esc(:data)), $(esc(:indices))) -> begin
#                         $(esc(modeldef))
#                     end
#                     indices = modelindices(data, horizon; kw...)
#                     I = typeof(indices)
#                     hydromodel = new{D,I}(horizon, data, indices, generator, :Unplanned)
#                     define_problem!(hydromodel)
#                     return hydromodel
#                 end
#             end
#             $fixhorizondef
#         end
#         code
#     elseif variant == :Stochastic
#         modeldef = @q begin
#             @stochastic_model begin
#                 $modeldef
#             end
#         end
#         code = @q begin
#             mutable struct $(esc(modelname)){$(esc(:D)) <: AbstractModelData,
#                                              $(esc(:I)) <: AbstractModelIndices,
#                                              $(esc(:SM)) <: StochasticModel,
#                                              $(esc(:SP)) <: StochasticProgram} <: StochasticHydroModel
#                 horizon::Horizon
#                 data::$(esc(:D))
#                 indices::$(esc(:I))
#                 stochasticmodel::$(esc(:SM))
#                 internalmodel::$(esc(:SP))
#                 status::Dict{Symbol,Symbol}

#                 function $(esc(modelname))(horizon::Horizon,
#                                            data::AbstractModelData,
#                                            scenarios::Vector{<:AbstractScenario}; kw...)
#                     D = typeof(data)
#                     indices = modelindices(data, horizon; kw...)
#                     I = typeof(indices)
#                     stochasticmodel = $(esc(modeldef))
#                     SM = typeof(stochasticmodel)
#                     sp = instantiate(stochasticmodel, scenarios; horizon = horizon, indices = indices, data = data)
#                     SP = typeof(sp)
#                     hydromodel = new{D,I,SM,SP}(horizon, data, indices, stochasticmodel, sp, Dict(:rp=>:Unplanned,:evp=>:Unplanned))
#                     return hydromodel
#                 end

#                 function $(esc(modelname))(horizon::Horizon,
#                                            data::AbstractModelData,
#                                            sampler::AbstractSampler{S},
#                                            n::Integer; kw...) where S <: AbstractScenario
#                     D = typeof(data)
#                     indices = modelindices(data, horizon; kw...)
#                     I = typeof(indices)
#                     stochasticmodel = $(esc(modeldef))
#                     SM = typeof(stochasticmodel)
#                     sp = instantiate(stochasticmodel, sampler, n; horizon = horizon, indices = indices, data = data)
#                     SP = typeof(sp)
#                     hydromodel = new{D,I,SM,SP}(horizon, data, indices, stochasticmodel, sp, Dict(:rp=>:Unplanned,:evp=>:Unplanned))
#                     return hydromodel
#                 end
#             end
#             $fixhorizondef
#         end
#         code
#     else
#         error("Invalid model variant. Specify Deterministic for deterministic models and Stochastic for stochastic models.")
#     end

#     return prettify(code)
# end
# macro deterministic(def)
#     return :(@hydromodel Deterministic $def)
# end
# macro stochastic(def)
#     return :(@hydromodel Stochastic $def)
# end


text:
using LinearAlgebra

# one-body matrix, nearest neighbour, PBC
function kinetic_matrix(self::Lattice)
    K_matrix = zeros(self.nsites, self.nsites)
    for i =  1 : self.nsites
        for j = 1 : self.nsites
            if abs(i - j) == 1 || abs(i - j) == self.nsites - 1
                K_matrix[i, j] = -self.t
            end
        end
    end
    return K_matrix
end

# σ-dependent generator
function auxiliary_field_matrix_stepwise(σ::Array{Int64,1}, γ::Float64, Δτ::Float64, U::Float64)
    AF_matrix_SpinUp = diagm(0 => exp.(2 * γ * σ .- Δτ * U / 2))
    AF_matrix_SpinDn = diagm(0 => exp.(-2 * γ * σ .- Δτ * U / 2))
    return AF_matrix_SpinUp, AF_matrix_SpinDn
end

function matrix_product_stepwise(σlist::Array{Int64,2}, lattice::Lattice, qmc::QMC)
    MatProdUp = Matrix{Float64}(I, lattice.nsites, lattice.nsites)
    MatProdDn = Matrix{Float64}(I, lattice.nsites, lattice.nsites)
    for i = 1 : qmc.L
        σ = σlist[:, i]
        AF_matrix_SpinUp, AF_matrix_SpinDn = auxiliary_field_matrix_stepwise(σ, qmc.γ, qmc.Δτ, lattice.U)
        MatProdUp = Symmetric(qmc.Kmatrix * AF_matrix_SpinUp * qmc.Kmatrix) * MatProdUp
        MatProdDn = Symmetric(qmc.Kmatrix * AF_matrix_SpinDn * qmc.Kmatrix) * MatProdDn
    end
    EigensUp = eigen(MatProdUp)
    EigensDn = eigen(MatProdDn)
    return MatProdUp, MatProdDn, EigensUp, EigensDn
end

# Use QR decomposition to stablize the propogation
function matrix_product_QR(σlist::Array{Int64,2}, lattice::Lattice, qmc::QMC, n_stab_interval::Int64)
    # Initialize QR matrices
    QRUp_Q = Matrix{Float64}(I, lattice.nsites, lattice.nsites)
    QRUp_R = Matrix{Float64}(I, lattice.nsites, lattice.nsites)
    QRDn_Q = Matrix{Float64}(I, lattice.nsites, lattice.nsites)
    QRDn_R = Matrix{Float64}(I, lattice.nsites, lattice.nsites)
    # Final Product Matrix
    MatProdUp = Matrix{Float64}(I, lattice.nsites, lattice.nsites)
    MatProdDn = Matrix{Float64}(I, lattice.nsites, lattice.nsites)
    for i = 1 : div(qmc.L, n_stab_interval)
        matprodUp = Matrix{Float64}(I, lattice.nsites, lattice.nsites)
        matprodDn = Matrix{Float64}(I, lattice.nsites, lattice.nsites)
        for j = 1 : n_stab_interval
            σ = σlist[:, (i - 1) * n_stab_interval + j]
            AF_matrix_SpinUp, AF_matrix_SpinDn = auxiliary_field_matrix_stepwise(σ, qmc.γ, qmc.Δτ, lattice.U)
            matprodUp = Symmetric(qmc.Kmatrix * AF_matrix_SpinUp * qmc.Kmatrix) * matprodUp
            matprodDn = Symmetric(qmc.Kmatrix * AF_matrix_SpinDn * qmc.Kmatrix) * matprodDn
        end
        # QR decomposition of the matrix product
        # leave here to see if can be replaced with rmul!
        QRUp_Q = matprodUp * QRUp_Q
        DecompUp = qr(QRUp_Q)
        QRDn_Q = matprodDn * QRDn_Q
        DecompDn = qr(QRDn_Q)
        # Remaining R_i goes to multiply R_1
        QRUp_Q = DecompUp.Q
        QRUp_R = DecompUp.R * QRUp_R
        QRDn_Q = DecompDn.Q
        QRDn_R = DecompDn.R * QRDn_R
    end
    mul!(MatProdUp, QRUp_Q, QRUp_R)
    mul!(MatProdDn, QRDn_Q, QRDn_R)
    EigensUp = eigen(MatProdUp)
    EigensDn = eigen(MatProdDn)
    return MatProdUp, MatProdDn, EigensUp, EigensDn
end

# generate overlap "tensor" / column major
function overlap_coefficient(nsites::Int64, Uup::Array{T1,2}, Udn::Array{T2,2}) where {T1<:FloatType, T2<:FloatType}
    Uup_inv, Udn_inv = inv(Uup), inv(Udn)
    Uup_array = complex(zeros(nsites, nsites, nsites))
    Udn_array = complex(zeros(nsites, nsites, nsites))
    for i = 1 : nsites
        for j = 1 : nsites
            for k = 1 : nsites
                Uup_array[k ,i, j] = Uup_inv[k, i] * Uup[j, k]
                Udn_array[k, i, j] = Udn_inv[k, i] * Udn[j, k]
            end
        end
    end
    real(Uup_array), real(Udn_array)
end

max_stars_repo_name: TongSericus/CanonicalAFQMC

max_issues_repo_name: TongSericus/CanonicalAFQMC

max_forks_repo_name: TongSericus/CanonicalAFQMC


text:
module TestCSets
using Test

using Catlab: @present
using Catlab.Theories: FreeCategory
using Catlab.CategoricalAlgebra.CSets

# Discrete dynamical systems
############################

@present TheoryDDS(FreeCategory) begin
  X::Ob
  Φ::Hom(X,X)
end

const AbstractDDS = AbstractCSetType(TheoryDDS)
const DDS = CSetType(TheoryDDS, index=[:Φ])
@test AbstractDDS == AbstractCSet{(:X,),(:Φ,),(1,),(1,)}
@test DDS <: AbstractDDS
@test DDS <: CSet

dds = DDS()
@test keys(dds.indices) == (:Φ,)
@test nparts(dds, :X) == 0
@test add_part!(dds, :X) == 1
@test nparts(dds, :X) == 1
@test incident(dds, 1, :Φ) == []

set_subpart!(dds, 1, :Φ, 1)
@test subpart(dds, 1, :Φ) == 1
@test incident(dds, 1, :Φ) == [1]

@test add_part!(dds, :X, Φ=1) == 2
@test add_part!(dds, :X, Φ=1) == 3
@test subpart(dds, :Φ) == [1,1,1]
@test subpart(dds, [2,3], :Φ) == [1,1]
@test incident(dds, 1, :Φ) == [1,2,3]

@test has_part(dds, :X)
@test !has_part(dds, :nonpart)
@test has_part(dds, :X, 3)
@test !has_part(dds, :X, 4)
@test has_part(dds, :X, 1:5) == [true, true, true, false, false]

@test has_subpart(dds, :Φ)
@test !has_subpart(dds, :nonsubpart)
@test_throws KeyError subpart(dds, 1, :nonsubpart)
@test_throws KeyError set_subpart!(dds, 1, :nonsubpart, 1)

# Error handling
@test_throws AssertionError add_part!(dds, :X, Φ=5)
@test subpart(dds, :Φ) == [1,1,1,0]
@test incident(dds, 4, :Φ) == []

# Dendrograms
#############

# Strictly speaking, this data structure is not a single dendrogram but a forest
# of dendrograms (whose roots are the elements fixed under the `parent` map) and
# in order to be valid dendrograms, the `height` map must satisfy
# `compose(parent, height) ≥ height` pointwise.

@present TheoryDendrogram(FreeCategory) begin
  X::Ob
  R::Ob
  parent::Hom(X,X)
  height::Hom(X,R)
end

const AbstractDendrogram = AbstractCSetType(TheoryDendrogram, data=[:R])
const Dendrogram = CSetType(TheoryDendrogram, data=[:R], index=[:parent])
@test AbstractDendrogram ==
  AbstractCSet{(:X,),(:parent,),(1,),(1,),(:height,),(1,)}

d = Dendrogram(height=Float64)
add_parts!(d, :X, 3, height=0)
add_parts!(d, :X, 2, height=[10,20])
set_subpart!(d, 1:3, :parent, 4)
set_subpart!(d, [4,5], :parent, 5)

@test nparts(d, :X) == 5
@test subpart(d, [1,2,3], :parent) == [4,4,4]
@test subpart(d, 4, :parent) == 5
@test subpart(d, :, :parent) == [4,4,4,5,5]
@test incident(d, 4, :parent) == [1,2,3]
@test has_subpart(d, :height)
@test subpart(d, [1,2,3], :height) == [0,0,0]
@test subpart(d, 4, :height) == 10
@test subpart(d, :, :height) == [0,0,0,10,20]

d2 = empty(d)
copy_parts!(d2, d, :X, [4,5])
@test nparts(d2, :X) == 2
@test subpart(d2, [1,2], :parent) == [2,2]
@test subpart(d2, [1,2], :height) == [10,20]

# Labeled sets
##############

# The simplest example of a C-set with a data attribute, to test data indexing.

@present TheoryLabeledSet(FreeCategory) begin
  X::Ob
  Label::Ob
  label::Hom(X,Label)
end

const IndexedLabeledSet = CSetType(
  TheoryLabeledSet, data=[:Label], index=[:label])

lset = IndexedLabeledSet(label=Symbol)
@test keys(lset.data_indices) == (:label,)
add_parts!(lset, :X, 2, label=[:foo, :bar])
@test subpart(lset, :, :label) == [:foo, :bar]
@test incident(lset, :foo, :label) == [1]
@test isempty(incident(lset, :nonkey, :label))

add_part!(lset, :X, label=:foo)
@test incident(lset, :foo, :label) == [1,3]
set_subpart!(lset, 1, :label, :baz)
@test subpart(lset, 1, :label) == :baz
@test incident(lset, [:foo,:baz], :label) == [[3],[1]]

const UniqueIndexedLabeledSet = CSetType(
  TheoryLabeledSet, data=[:Label], unique_index=[:label])

lset = UniqueIndexedLabeledSet(label=Symbol)
@test keys(lset.data_indices) == (:label,)
add_parts!(lset, :X, 2, label=[:foo, :bar])
@test subpart(lset, :, :label) == [:foo, :bar]
@test incident(lset, :foo, :label) == 1
@test incident(lset, [:foo,:bar], :label) == [1,2]
@test incident(lset, :nonkey, :label) == nothing

set_subpart!(lset, 1, :label, :baz)
@test subpart(lset, 1, :label) == :baz
@test incident(lset, :baz, :label) == 1
@test_throws ErrorException set_subpart!(lset, 1, :label, :bar)

end


text:
module PandorasBoxLaserMirror

using ..Ahorn, Maple

@mapdef Entity "pandorasBox/laserMirror" LaserMirror(x::Integer, y::Integer, opening::String="LeftUp")

const openingScales = Dict{String, Tuple{Integer, Integer}}(
    "LeftUp" => (1, 1),
    "UpRight" => (-1, 1),
    "RightDown" => (-1, -1),
    "DownLeft" => (1, -1)
)

const placements = Ahorn.PlacementDict(
    "Static Laser Mirror ($opening) (Pandora's Box)" => Ahorn.EntityPlacement(
        LaserMirror,
        "point",
        Dict{String, Any}(
            "opening" => opening
        )
    ) for (opening, rot) in openingScales
)

Ahorn.editingOptions(entity::LaserMirror) = Dict{String, Any}(
    "opening" => collect(keys(openingScales))
)

sprite = "objects/pandorasBox/laser/mirror/mirror_static"

function Ahorn.selection(entity::LaserMirror)
    x, y = Ahorn.position(entity)

    opening = get(entity, "opening", "LeftUp")
    scaleX, scaleY = get(openingScales, opening, (1, 1))

    return Ahorn.getSpriteRectangle(sprite, x, y, jx=0.5, jy=0.5, sx=scaleX, sy=scaleY)
end

function Ahorn.render(ctx::Ahorn.Cairo.CairoContext, entity::LaserMirror, room::Maple.Room)
    opening = get(entity, "opening", "LeftUp")
    scaleX, scaleY = get(openingScales, opening, (1, 1))

    Ahorn.drawSprite(ctx, sprite, 0, 0, jx=0.5, jy=0.5, sx=scaleX, sy=scaleY)
end

end

max_stars_repo_name: DemoJameson/PandorasBox

max_issues_repo_name: DemoJameson/PandorasBox

max_forks_repo_name: DemoJameson/PandorasBox


text:
export  JoinTable,
        setnojoincondition!,
        setusingcolumns!,
        setnaturaljoin!,
        setjoincondition!

"""
```
JoinTable(
    name::Union{Var, AbstractString, JoinTable},
    jname::Union{Var, AbstractString},
    jtype::Symbol=:inner;
    alias::Union{Var, AbstractString}="",
    jalias::Union{Var, AbstractString}="" )
```
This mutable struct represents a `JOIN` SQL statement where `name` is the name of the first table, `jname` is the name of the table to join into the first table, `jtype` is the type of join to perform, `alias` is the alias for the first table, and `jalias` is the alias for the second table.

Accepted values for the join type are `:cross`, `:inner`, `:left`, `:right`, and `:full`. Any other value will result in an error being thrown.

An alternative way of creating a `JoinTable` is
```
JoinTable(
    jname::Union{Var, AbstractString},
    jtype::Symbol=:inner;
    jalias::Union{Var, AbstractString}="" )
```
This construct creates a function that takes a `JoinTable` and returns a new `JoinTable` with the argument as the first table in the join. This allows the use of Julia's function chaining syntax.

Example:
```
JoinTable( "table1", "table2" ) |> JoinTable( "table3" )
```
This statement creates a `JoinTable` where `table2` is joined to `table1`, and `table3` is joined to the result of this.
"""
mutable struct JoinTable <: SQLStatement
    name::String
    alias::Var
    jtype::Symbol
    jname::Var
    jalias::Var
    jctype::Symbol
    jcols::Vector{Var}
    jcond::SQLCondition

    function JoinTable( name::Union{SVar, JoinTable}, jname::SVar, jtype::Symbol=:inner; alias::SVar="", jalias::SVar="" )
        jtype ∈ [:cross, :inner, :left, :right, :full] || @error("Unknown join type, must be :cross, :inner, :left, :right, or :full.")
        new( name |> string, alias |> Var, jtype, jname |> Var, jalias |> Var, :none, Var[], nocond )
    end
end

JoinTable( jname::SVar, jtype::Symbol=:inner; jalias::SVar="" ) =
    jc::JoinTable -> begin
        JoinTable( jc |> string, jname, jtype, jalias=jalias )
    end

function Base.show( io::IO, jc::JoinTable )
    print( io, "$(jc.name) " )
    isempty(jc.alias) || print( io, "$(jc.alias) " )
    jc.jctype === :natural && print( io, "NATURAL " )
    print( io, "$(string(jc.jtype) |> uppercase) JOIN $(jc.jname)" )
    isempty(jc.jalias) || print( io, " $(jc.jalias)" )

    if jc.jctype === :using
        print( io, " USING ($(join( string.(jc.jcols), ", " )))" )
    elseif jc.jctype === :on
        print( io, " ON $(jc.jcond)" )
    end
end

"""
```
setnojoincondition!( jc::JoinTable )
```
This function removes the join condition from `jc`, which will result in a table which is the standard Cartesian product between the two tables in `JoinTable`.
"""
function setnojoincondition!( jc::JoinTable )
    jc.jctype = :none
    jc
end

"""
```
setusingcolumns!( columns::Vector{Var} )
setusingcolumns!( columns::Vector{T} ) where T <: AbstractString
setusingcolumns!( columns::SVar... )
```
This function sets the join condition of `jc` to a `USING` join on the columns listed in `columns`. The resulting table suppresses duplicate columns for all the columns that are in the list and are present in both tables.
"""
setusingcolumns!( columns::Vector{Var} ) = jc::JoinTable -> begin
    isempty(columns) && return jc
    jc.jctype = :using
    jc.jcols = columns
    jc
end
setusingcolumns!( columns::Vector{T} ) where T <: AbstractString = Var.(columns) |> setusingcolumns!
setusingcolumns!( columns::SVar... ) = Var.( columns |> collect ) |> setusingcolumns!

"""
```
setnaturaljoin!( jc::JoinTable )
```
This function sets the join condition of `jc` to a `NATURAL` join. The resulting table suppresses duplicate columns for all the columns that have matching names in both tables.

This is a shorthand for `USING` with all matching columns listed.
"""
function setnaturaljoin!( jc::JoinTable )
    jc.jctype = :natural
    jc
end

"""
```
setjoincondition!( cond::SQLCondition )
```
This function sets the join condition of `jc` to a generic `ON` clause where the tables are joined on all the pairs of entries that match the condition `cond`.
"""
setjoincondition!( cond::SQLCondition ) = jc::JoinTable -> begin
    if cond === nocond
        jc.jctype = :none
        return jc
    end

    jc.jctype = :on
    jc.jcond = cond
    jc
end


text:
struct Symplectic2ConstantCache{T,T2} <: OrdinaryDiffEqConstantCache
  a1::T
  a2::T
  b1::T
  b2::T
end

function PseudoVerletLeapfrogConstantCache(T,T2)
  a1 = T(1)
  a2 = T(0)
  b1 = T(1//2)
  b2 = T(1//2)
  Symplectic2ConstantCache{T,T2}(a1,a2,b1,b2)
end

function McAte2ConstantCache(T,T2)
  a2 = T(1 - (1/2)*sqrt(T(2)))
  a1 = T(1 - a2)
  b2 = T(1/(2*(1-a2)))
  b1 = T(1 - b2)
  Symplectic2ConstantCache{T,T2}(a1,a2,b1,b2)
end

function VerletLeapfrogConstantCache(T,T2)
  a1 = T(1//2)
  a2 = T(1//2)
  b1 = T(0)
  b2 = T(1)
  Symplectic2ConstantCache{T,T2}(a1,a2,b1,b2)
end

struct Symplectic3ConstantCache{T,T2} <: OrdinaryDiffEqConstantCache
  a1::T
  a2::T
  a3::T
  b1::T
  b2::T
  b3::T
end

function Ruth3ConstantCache(T,T2)
  a1 = T(2//3)
  a2 = T(-2//3)
  a3 = T(1)
  b1 = T(7//24)
  b2 = T(3//4)
  b3 = T(-1//24)
  Symplectic3ConstantCache{T,T2}(a1,a2,a3,b1,b2,b3)
end

function McAte3ConstantCache(T,T2)
  a1 = T(0.9196615230173999)
  a2 = T(0.25/a1 - a1/2)
  a3 = T(1 - a1 - a2)
  b1 = T(a3)
  b2 = T(a2)
  b3 = T(a1)
  Symplectic3ConstantCache{T,T2}(a1,a2,a3,b1,b2,b3)
end

struct Symplectic4ConstantCache{T,T2} <: OrdinaryDiffEqConstantCache
  a1::T
  a2::T
  a3::T
  a4::T
  b1::T
  b2::T
  b3::T
  b4::T
end

function CandyRoz4ConstantCache(T,T2)
  a1 = T((2 + T(2)^(1//3) + T(2)^(-1//3))/6)
  a2 = T((1 - T(2)^(1//3) - T(2)^(-1//3))/6)
  a3 = T(a2)
  a4 = T(a1)
  b1 = T(0)
  b2 = T((2 - T(2)^(1//3))^-1)
  b3 = T((1-T(2)^(2//3))^-1)
  b4 = T(b2)
  Symplectic4ConstantCache{T,T2}(a1,a2,a3,a4,b1,b2,b3,b4)
end

function McAte4ConstantCache(::Type{T},::Type{T2}) where {T<:CompiledFloats,T2<:CompiledFloats}
  a1 =T( 0.515352837431122936)
  a2 =T(-0.085782019412973646)
  a3 =T( 0.441583023616466524)
  a4 =T( 0.128846158365384185)
  b1 =T( 0.134496199277431089)
  b2 =T(-0.224819803079420806)
  b3 =T( 0.756320000515668291)
  b4 =T( 0.334003603286321425)
  Symplectic4ConstantCache{T,T2}(a1,a2,a3,a4,b1,b2,b3,b4)
end

function McAte4ConstantCache(T::Type,T2::Type)
  a1 =T(parse(BigFloat,"0.515352837431122936"))
  a2 =T(parse(BigFloat,"-0.085782019412973646"))
  a3 =T(parse(BigFloat," 0.441583023616466524"))
  a4 =T(parse(BigFloat," 0.128846158365384185"))
  b1 =T(parse(BigFloat," 0.134496199277431089"))
  b2 =T(parse(BigFloat,"-0.224819803079420806"))
  b3 =T(parse(BigFloat," 0.756320000515668291"))
  b4 =T(parse(BigFloat," 0.334003603286321425"))
  Symplectic4ConstantCache{T,T2}(a1,a2,a3,a4,b1,b2,b3,b4)
end

struct Symplectic45ConstantCache{T,T2} <: OrdinaryDiffEqConstantCache
  a1::T
  a2::T
  a3::T
  a4::T
  a5::T
  b1::T
  b2::T
  b3::T
  b4::T
  b5::T
end

function CalvoSanz4ConstantCache(T,T2)
  a1= T(0.205177661542290)
  a2= T(0.403021281604210)
  a3=-T(0.12092087633891)
  a4= T(0.512721933192410)
  a5= T(0.0)
  b1= T(0.061758858135626)
  b2= T(0.33897802655364)
  b3= T(0.61479130717558)
  b4=-T(0.14054801465937)
  b5= T(0.12501982279453)
  Symplectic45ConstantCache{T,T2}(a1,a2,a3,a4,a5,b1,b2,b3,b4,b5)
end

# Broken
# http://epubs.siam.org/doi/pdf/10.1137/0916010
# On the numerical integration of ordinary differential equations by symmetric composition methods
function McAte42ConstantCache(::Type{T},::Type{T2}) where {T<:CompiledFloats,T2<:CompiledFloats}
  a1 =T(0.40518861839525227722)
  a2 =T(-0.28714404081652408900)
  a3 = 1 - 2a1 - 2a2
  a4 = a2
  a5 = a1
  b1 = T(-3//73)
  b2 = T(17//59)
  b3 = 1 - 2b1 - 2b2
  b4 = b2
  b5 = b1
  Symplectic45ConstantCache{T,T2}(a1,a2,a3,a4,a5,b1,b2,b3,b4,b5)
end

function McAte42ConstantCache(T::Type,T2::Type)
  a1 =T(parse(BigFloat,"0.40518861839525227722"))
  a2 =T(parse(BigFloat,"-0.28714404081652408900"))
  a3 = 1 - 2a1 - 2a2
  a4 = a2
  a5 = a1
  b1 = T(-3//73)
  b2 = T(17//59)
  b3 = 1 - 2b1 - 2b2
  b4 = b2
  b5 = b1
  Symplectic45ConstantCache{T,T2}(a1,a2,a3,a4,a5,b1,b2,b3,b4,b5)
end

struct Symplectic5ConstantCache{T,T2} <: OrdinaryDiffEqConstantCache
  a1::T
  a2::T
  a3::T
  a4::T
  a5::T
  a6::T
  b1::T
  b2::T
  b3::T
  b4::T
  b5::T
  b6::T
end

function McAte5ConstantCache(::Type{T},::Type{T2}) where {T<:CompiledFloats,T2<:CompiledFloats}
  a1=T(0.339839625839110000)
  a2=T(-0.088601336903027329)
  a3=T(0.5858564768259621188)
  a4=T(-0.603039356536491888)
  a5=T(0.3235807965546976394)
  a6=T(0.4423637942197494587)
  b1=T(0.1193900292875672758)
  b2=T(0.6989273703824752308)
  b3=T(-0.1713123582716007754)
  b4=T(0.4012695022513534480)
  b5=T(0.0107050818482359840)
  b6=T(-0.0589796254980311632)
  Symplectic5ConstantCache{T,T2}(a1,a2,a3,a4,a5,a6,b1,b2,b3,b4,b5,b6)
end

function McAte5ConstantCache(T::Type,T2::Type)
  a1=T(parse(BigFloat,"0.339839625839110000"))
  a2=T(parse(BigFloat,"-0.088601336903027329"))
  a3=T(parse(BigFloat,"0.5858564768259621188"))
  a4=T(parse(BigFloat,"-0.603039356536491888"))
  a5=T(parse(BigFloat,"0.3235807965546976394"))
  a6=T(parse(BigFloat,"0.4423637942197494587"))
  b1=T(parse(BigFloat,"0.1193900292875672758"))
  b2=T(parse(BigFloat,"0.6989273703824752308"))
  b3=T(parse(BigFloat,"-0.1713123582716007754"))
  b4=T(parse(BigFloat,"0.4012695022513534480"))
  b5=T(parse(BigFloat,"0.0107050818482359840"))
  b6=T(parse(BigFloat,"-0.0589796254980311632"))
  Symplectic5ConstantCache{T,T2}(a1,a2,a3,a4,a5,a6,b1,b2,b3,b4,b5,b6)
end

struct Symplectic6ConstantCache{T,T2} <: OrdinaryDiffEqConstantCache
  a1::T
  a2::T
  a3::T
  a4::T
  a5::T
  a6::T
  a7::T
  a8::T
  b1::T
  b2::T
  b3::T
  b4::T
  b5::T
  b6::T
  b7::T
  b8::T
end

function Yoshida6ConstantCache(T,T2)
  a1=T( 0.78451361047756)
  a2=T( 0.23557321335936)
  a3=T(-1.1776799841789)
  a4=T( 1.3151863206839)
  a5=T( a3)
  a6=T( a2)
  a7=T( a1)
  a8=T( 0.0)
  b1= a1/2
  b2=T((a1+a2)/2)
  b3=T((a2+a3)/2)
  b4=T((a3+a4)/2)
  b5=T( b4)
  b6=T( b3)
  b7=T( b2)
  b8=T( b1)
  Symplectic6ConstantCache{T,T2}(a1,a2,a3,a4,a5,a6,a7,a8,b1,b2,b3,b4,b5,b6,b7,b8)
end

struct Symplectic62ConstantCache{T,T2} <: OrdinaryDiffEqConstantCache
  a1::T
  a2::T
  a3::T
  a4::T
  a5::T
  a6::T
  a7::T
  a8::T
  a9::T
  a10::T
  b1::T
  b2::T
  b3::T
  b4::T
  b5::T
  b6::T
  b7::T
  b8::T
  b9::T
  b10::T
end

function KahanLi6ConstantCache(::Type{T},::Type{T2}) where {T<:CompiledFloats,T2<:CompiledFloats}
  a1=T(0.39216144400731413927925056)
  a2=T(0.33259913678935943859974864)
  a3=T(-0.70624617255763935980996482)
  a4=T(0.08221359629355080023149045)
  a5=T(0.79854399093482996339895035)
  a6= a4
  a7= a3
  a8= a2
  a9= a1
  a10 = T(0)
  b1= T(a1/2)
  b2=T((a1+a2)/2)
  b3=T((a2+a3)/2)
  b4=T((a3+a4)/2)
  b5=T((a4+a5)/2)
  b6=b5
  b7=b4
  b8=b3
  b9=b2
  b10=b1
  Symplectic62ConstantCache{T,T2}(a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,b1,b2,b3,b4,b5,b6,b7,b8,b9,b10)
end

function KahanLi6ConstantCache(T::Type,T2::Type)
  a1=T(parse(BigFloat,"0.39216144400731413927925056"))
  a2=T(parse(BigFloat,"0.33259913678935943859974864"))
  a3=T(parse(BigFloat,"-0.70624617255763935980996482"))
  a4=T(parse(BigFloat,"0.08221359629355080023149045"))
  a5=T(parse(BigFloat,"0.79854399093482996339895035"))
  a6= a4
  a7= a3
  a8= a2
  a9= a1
  a10 = T(0)
  b1= T(a1/2)
  b2=T((a1+a2)/2)
  b3=T((a2+a3)/2)
  b4=T((a3+a4)/2)
  b5=T((a4+a5)/2)
  b6=b5
  b7=b4
  b8=b3
  b9=b2
  b10=b1
  Symplectic62ConstantCache{T,T2}(a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,b1,b2,b3,b4,b5,b6,b7,b8,b9,b10)
end

struct McAte8ConstantCache{T,T2} <: OrdinaryDiffEqConstantCache
  a1::T
  a2::T
  a3::T
  a4::T
  a5::T
  a6::T
  a7::T
  a8::T
  a9::T
  a10::T
  a11::T
  a12::T
  a13::T
  a14::T
  a15::T
  a16::T
  b1::T
  b2::T
  b3::T
  b4::T
  b5::T
  b6::T
  b7::T
  b8::T
  b9::T
  b10::T
  b11::T
  b12::T
  b13::T
  b14::T
  b15::T
  b16::T
end

function McAte8ConstantCache(::Type{T},::Type{T2}) where {T<:CompiledFloats,T2<:CompiledFloats}
  a1=T(0.74167036435061295344822780)
  a2=T(-0.40910082580003159399730010)
  a3=T(0.19075471029623837995387626)
  a4=T(-0.57386247111608226665638773)
  a5=T(0.29906418130365592384446354)
  a6=T(0.33462491824529818378495798)
  a7=T(0.31529309239676659663205666)
  a8=T(-0.79688793935291635401978884)
  a9=a7
  a10=a6
  a11=a5
  a12=a4
  a13=a3
  a14=a2
  a15=a1
  a16=T(0)
  b1= T(a1/2)
  b2=T((a1+a2)/2)
  b3=T((a2+a3)/2)
  b4=T((a3+a4)/2)
  b5=T((a4+a5)/2)
  b6=T((a5+a6)/2)
  b7=T((a6+a7)/2)
  b8=T((a7+a8)/2)
  b9=b8
  b10=b7
  b11=b6
  b12=b5
  b13=b4
  b14=b3
  b15=b2
  b16=b1
  McAte8ConstantCache{T,T2}(a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15,a16,
                            b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b14,b15,b16)
end

function McAte8ConstantCache(T::Type,T2::Type)
  a1=T(parse(BigFloat,"0.74167036435061295344822780"))
  a2=T(parse(BigFloat,"-0.40910082580003159399730010"))
  a3=T(parse(BigFloat,"0.19075471029623837995387626"))
  a4=T(parse(BigFloat,"-0.57386247111608226665638773"))
  a5=T(parse(BigFloat,"0.29906418130365592384446354"))
  a6=T(parse(BigFloat,"0.33462491824529818378495798"))
  a7=T(parse(BigFloat,"0.31529309239676659663205666"))
  a8=T(parse(BigFloat,"-0.79688793935291635401978884"))
  a9=a7
  a10=a6
  a11=a5
  a12=a4
  a13=a3
  a14=a2
  a15=a1
  a16=T(0)
  b1= T(a1/2)
  b2=T((a1+a2)/2)
  b3=T((a2+a3)/2)
  b4=T((a3+a4)/2)
  b5=T((a4+a5)/2)
  b6=T((a5+a6)/2)
  b7=T((a6+a7)/2)
  b8=T((a7+a8)/2)
  b9=b8
  b10=b7
  b11=b6
  b12=b5
  b13=b4
  b14=b3
  b15=b2
  b16=b1
  McAte8ConstantCache{T,T2}(a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15,a16,
                            b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b14,b15,b16)
end

struct KahanLi8ConstantCache{T,T2} <: OrdinaryDiffEqConstantCache
  a1::T
  a2::T
  a3::T
  a4::T
  a5::T
  a6::T
  a7::T
  a8::T
  a9::T
  a10::T
  a11::T
  a12::T
  a13::T
  a14::T
  a15::T
  a16::T
  a17::T
  a18::T
  b1::T
  b2::T
  b3::T
  b4::T
  b5::T
  b6::T
  b7::T
  b8::T
  b9::T
  b10::T
  b11::T
  b12::T
  b13::T
  b14::T
  b15::T
  b16::T
  b17::T
  b18::T
end

function KahanLi8ConstantCache(::Type{T},::Type{T2}) where {T<:CompiledFloats,T2<:CompiledFloats}
  a1=T(0.13020248308889008087881763)
  a2=T(0.56116298177510838456196441)
  a3=T(-0.38947496264484728640807860)
  a4=T(0.15884190655515560089621075)
  a5=T(-0.39590389413323757733623154)
  a6=T(0.18453964097831570709183254)
  a7=T(0.25837438768632204729397911)
  a8=T(0.29501172360931029887096624)
  a9=T(-0.60550853383003451169892108)
  a10=a8
  a11=a7
  a12=a6
  a13=a5
  a14=a4
  a15=a3
  a16=a2
  a17=a1
  a18=T(0)
  b1= T(a1/2)
  b2=T((a1+a2)/2)
  b3=T((a2+a3)/2)
  b4=T((a3+a4)/2)
  b5=T((a4+a5)/2)
  b6=T((a5+a6)/2)
  b7=T((a6+a7)/2)
  b8=T((a7+a8)/2)
  b9=T((a8+a9)/2)
  b10=b9
  b11=b8
  b12=b7
  b13=b6
  b14=b5
  b15=b4
  b16=b3
  b17=b2
  b18=b1
  KahanLi8ConstantCache{T,T2}(a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15,a16,a17,a18,
                              b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b14,b15,b16,b17,b18)
end

function KahanLi8ConstantCache(T::Type,T2::Type)
  a1=T(parse(BigFloat,"0.13020248308889008087881763"))
  a2=T(parse(BigFloat,"0.56116298177510838456196441"))
  a3=T(parse(BigFloat,"-0.38947496264484728640807860"))
  a4=T(parse(BigFloat,"0.15884190655515560089621075"))
  a5=T(parse(BigFloat,"-0.39590389413323757733623154"))
  a6=T(parse(BigFloat,"0.18453964097831570709183254"))
  a7=T(parse(BigFloat,"0.25837438768632204729397911"))
  a8=T(parse(BigFloat,"0.29501172360931029887096624"))
  a9=T(parse(BigFloat,"-0.60550853383003451169892108"))
  a10=a8
  a11=a7
  a12=a6
  a13=a5
  a14=a4
  a15=a3
  a16=a2
  a17=a1
  a18=T(0)
  b1= T(a1/2)
  b2=T((a1+a2)/2)
  b3=T((a2+a3)/2)
  b4=T((a3+a4)/2)
  b5=T((a4+a5)/2)
  b6=T((a5+a6)/2)
  b7=T((a6+a7)/2)
  b8=T((a7+a8)/2)
  b9=T((a8+a9)/2)
  b10=b9
  b11=b8
  b12=b7
  b13=b6
  b14=b5
  b15=b4
  b16=b3
  b17=b2
  b18=b1
  KahanLi8ConstantCache{T,T2}(a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15,a16,a17,a18,
                              b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b14,b15,b16,b17,b18)
end

struct SofSpa10ConstantCache{T,T2} <: OrdinaryDiffEqConstantCache
  a1::T
  a2::T
  a3::T
  a4::T
  a5::T
  a6::T
  a7::T
  a8::T
  a9::T
  a10::T
  a11::T
  a12::T
  a13::T
  a14::T
  a15::T
  a16::T
  a17::T
  a18::T
  a19::T
  a20::T
  a21::T
  a22::T
  a23::T
  a24::T
  a25::T
  a26::T
  a27::T
  a28::T
  a29::T
  a30::T
  a31::T
  a32::T
  a33::T
  a34::T
  a35::T
  a36::T
  b1::T
  b2::T
  b3::T
  b4::T
  b5::T
  b6::T
  b7::T
  b8::T
  b9::T
  b10::T
  b11::T
  b12::T
  b13::T
  b14::T
  b15::T
  b16::T
  b17::T
  b18::T
  b19::T
  b20::T
  b21::T
  b22::T
  b23::T
  b24::T
  b25::T
  b26::T
  b27::T
  b28::T
  b29::T
  b30::T
  b31::T
  b32::T
  b33::T
  b34::T
  b35::T
  b36::T
end

function SofSpa10ConstantCache(::Type{T},::Type{T2}) where {T<:CompiledFloats,T2<:CompiledFloats}
  a1=T(0.07879572252168641926390768)
  a2=T(0.31309610341510852776481247)
  a3=T(0.02791838323507806610952027)
  a4=T(-0.22959284159390709415121340)
  a5=T(0.13096206107716486317465686)
  a6=T(-0.26973340565451071434460973)
  a7=T(0.07497334315589143566613711)
  a8=T(0.11199342399981020488957508)
  a9=T(0.36613344954622675119314812)
  a10=T(-0.39910563013603589787862981)
  a11=T(0.10308739852747107731580277)
  a12=T(0.41143087395589023782070412)
  a13=T(-0.00486636058313526176219566)
  a14=T(-0.39203335370863990644808194)
  a15=T(0.05194250296244964703718290)
  a16=T(0.05066509075992449633587434)
  a17=T(0.04967437063972987905456880)
  a18=T(0.04931773575959453791768001)
  a19=a17
  a20=a16
  a21=a15
  a22=a14
  a23=a13
  a24=a12
  a25=a11
  a26=a10
  a27=a9
  a28=a8
  a29=a7
  a30=a6
  a31=a5
  a32=a4
  a33=a3
  a34=a2
  a35=a1
  a36=T(0)
  b1= T(a1/2)
  b2=T((a1+a2)/2)
  b3=T((a2+a3)/2)
  b4=T((a3+a4)/2)
  b5=T((a4+a5)/2)
  b6=T((a5+a6)/2)
  b7=T((a6+a7)/2)
  b8=T((a7+a8)/2)
  b9=T((a8+a9)/2)
  b10=T((a9+a10)/2)
  b11=T((a10+a11)/2)
  b12=T((a11+a12)/2)
  b13=T((a12+a13)/2)
  b14=T((a13+a14)/2)
  b15=T((a14+a15)/2)
  b16=T((a15+a16)/2)
  b17=T((a16+a17)/2)
  b18=T((a17+a18)/2)
  b19=b18
  b20=b17
  b21=b16
  b22=b15
  b23=b14
  b24=b13
  b25=b12
  b26=b11
  b27=b10
  b28=b9
  b29=b8
  b30=b7
  b31=b6
  b32=b5
  b33=b4
  b34=b3
  b35=b2
  b36=b1
  SofSpa10ConstantCache{T,T2}(a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15,a16,a17,a18,
                              a19,a20,a21,a22,a23,a24,a25,a26,a27,a28,a29,a30,a31,a32,a33,a34,
                              a35,a36,
                              b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b14,b15,b16,b17,b18,
                              b19,b20,b21,b22,b23,b24,b25,b26,b27,b28,b29,b30,b31,b32,b33,b34,
                              b35,b36)
end

function SofSpa10ConstantCache(T::Type,T2::Type)
  a1=T(parse(BigFloat,"0.07879572252168641926390768"))
  a2=T(parse(BigFloat,"0.31309610341510852776481247"))
  a3=T(parse(BigFloat,"0.02791838323507806610952027"))
  a4=T(parse(BigFloat,"-0.22959284159390709415121340"))
  a5=T(parse(BigFloat,"0.13096206107716486317465686"))
  a6=T(parse(BigFloat,"-0.26973340565451071434460973"))
  a7=T(parse(BigFloat,"0.07497334315589143566613711"))
  a8=T(parse(BigFloat,"0.11199342399981020488957508"))
  a9=T(parse(BigFloat,"0.36613344954622675119314812"))
  a10=T(parse(BigFloat,"-0.39910563013603589787862981"))
  a11=T(parse(BigFloat,"0.10308739852747107731580277"))
  a12=T(parse(BigFloat,"0.41143087395589023782070412"))
  a13=T(parse(BigFloat,"-0.00486636058313526176219566"))
  a14=T(parse(BigFloat,"-0.39203335370863990644808194"))
  a15=T(parse(BigFloat,"0.05194250296244964703718290"))
  a16=T(parse(BigFloat,"0.05066509075992449633587434"))
  a17=T(parse(BigFloat,"0.04967437063972987905456880"))
  a18=T(parse(BigFloat,"0.04931773575959453791768001"))
  a19=a17
  a20=a16
  a21=a15
  a22=a14
  a23=a13
  a24=a12
  a25=a11
  a26=a10
  a27=a9
  a28=a8
  a29=a7
  a30=a6
  a31=a5
  a32=a4
  a33=a3
  a34=a2
  a35=a1
  a36=T(0)
  b1= T(a1/2)
  b2=T((a1+a2)/2)
  b3=T((a2+a3)/2)
  b4=T((a3+a4)/2)
  b5=T((a4+a5)/2)
  b6=T((a5+a6)/2)
  b7=T((a6+a7)/2)
  b8=T((a7+a8)/2)
  b9=T((a8+a9)/2)
  b10=T((a9+a10)/2)
  b11=T((a10+a11)/2)
  b12=T((a11+a12)/2)
  b13=T((a12+a13)/2)
  b14=T((a13+a14)/2)
  b15=T((a14+a15)/2)
  b16=T((a15+a16)/2)
  b17=T((a16+a17)/2)
  b18=T((a17+a18)/2)
  b19=b18
  b20=b17
  b21=b16
  b22=b15
  b23=b14
  b24=b13
  b25=b12
  b26=b11
  b27=b10
  b28=b9
  b29=b8
  b30=b7
  b31=b6
  b32=b5
  b33=b4
  b34=b3
  b35=b2
  b36=b1
  SofSpa10ConstantCache{T,T2}(a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15,a16,a17,a18,
                              a19,a20,a21,a22,a23,a24,a25,a26,a27,a28,a29,a30,a31,a32,a33,a34,
                              a35,a36,
                              b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b14,b15,b16,b17,b18,
                              b19,b20,b21,b22,b23,b24,b25,b26,b27,b28,b29,b30,b31,b32,b33,b34,
                              b35,b36)
end


text:
# PROBABILISTIC CIRCUITS LIBRARY ROOT

module ProbabilisticCircuits

# USE EXTERNAL MODULES

using Reexport

using LogicCircuits
# only reexport selectively from LogicCircuits
export pos_literals, neg_literals, print_tree
# circuit queries
export issmooth, isdecomposable, isstruct_decomposable,
       isdeterministic, iscanonical
# circuit status
export num_nodes, num_edges, children, num_parameters, num_children
export zoo_vtree, zoo_vtree_file, VtreeFormat, vtree, respects_vtree
export linearize, isliteralgate, literal, fully_factorized_circuit
# datasets
export twenty_datasets

include("Utils/Utils.jl")
@reexport using .Utils

include("factor_graph/factor_graph.jl")
include("factor_graph/fg_compile.jl")

include("abstract_prob_nodes.jl")
include("shared_prob_nodes.jl")
include("plain_prob_nodes.jl")
include("structured_prob_nodes.jl")
include("parameter_learn/param_bit_circuit.jl")
include("parameter_learn/parameters.jl")
include("parameter_learn/gradient_based_learning.jl")

include("queries/likelihood.jl")
include("queries/marginal_flow.jl")
include("queries/map.jl")
include("queries/sample.jl")
include("queries/pr_constraint.jl")
include("queries/information.jl")

include("mixtures/em.jl")

include("structurelearner/chow_liu_tree.jl")
include("structurelearner/init.jl")
include("structurelearner/heuristics.jl")
include("structurelearner/learner.jl")
include("structurelearner/vtree_learner.jl")
include("structurelearner/sample_psdd.jl")
include("structurelearner/bdd.jl")
include("structurelearner/rat_spn.jl")
include("structurelearner/hclt.jl")

include("ensembles/ensembles.jl")
include("ensembles/bmc.jl")

include("io/io.jl")

using Requires

function __init__()
    # optional dependency
    @require BlossomV = "6c721016-9dae-5d90-abf6-67daaccb2332" include("structurelearner/vtree_learner_blossomv.jl")
end

end