text:
using LinearAlgebra, DiffEqOperators, Test, Parameters

# These tests are based on examples from SimpleDifferentialOperators.jl

#parameters
params = @with_kw (
    μ = -0.1, # constant negative drift
    σ = 0.1,
    ρ = 0.05,
    M = 3, # size of grid (interior points)
    x̄ = range(0.0, 1.0, length = (M+2)),
    x = x̄[2:end - 1],
    S = 3.0
)
p = params()

#----------------------------------
#Testing For Negative Drifts
#----------------------------------
# payoff function
pi_profit(x) = x^2
#=# SimpleDifferentialOperators setup
function SDO_negative_drift(pi_profit, params)
    bc = (Reflecting(), Reflecting())
    Lₓ = params.μ*L₁₋bc(params.x̄, bc) + params.σ^2 / 2 * L₂bc(params.x̄, bc)
    L_bc = I * params.ρ - Lₓ
    v = L_bc \ pi_profit.(params.x);
    return (v = v, L_bc = L_bc, Lₓ = Lₓ, L₁₋bc = L₁₋bc(params.x̄, bc), L₂bc = L₂bc(params.x̄, bc))
end=#
# DiffEqOperators Setup
function DEO_negative_drift(pi_profit, params)
    dx = params.x[2] - params.x[1]
    # discretize L = ρ - μ D_x - σ^2 / 2 D_xx
    # subject to reflecting barriers at 0 and 1
    L1 = UpwindDifference(1,1,dx,params.M,1.)
    L2 = CenteredDifference(2,2,dx,params.M)
    Q = Neumann0BC(dx, 1)
    L₁₋bc = -1. .* Array(UpwindDifference(1,1,dx,params.M,-1.) * Q)[1]
    # Here Array(A::GhostDerivativeOperator) will return a tuple of the linear part
    # and the affine part of the operator A, hence we index Array(µ*L1*Q).
    # The operators in this example are purely linear, so we don't worry about Array(µ*L1*Q)[2]
    Lₓ = Array(params.μ*L1*Q)[1] + Array(params.σ^2/2*L2*Q)[1] # when scalar coefficient is properly implemented
    # Lₓ = Array(L1*Q)[1] + Array(params.σ^2/2*L2*Q)[1] # when scalar coefficient is properly implemented
    L_bc = I * params.ρ - Lₓ

    # solve the value function
    v = L_bc \ pi_profit.(params.x);
    return (v = v, L_bc = L_bc, Lₓ = Lₓ, L₁₋bc = L₁₋bc, L₂bc = Array(L2*Q)[1] )
end

@testset "Constant Negative Drifts" begin
    @test DEO_negative_drift(pi_profit, p).v ≈ [1.9182649086005406, 2.3359304764758773, 3.1768804315253277] # SDO_negative_drift(pi_profit, p).v
    @test DEO_negative_drift(pi_profit, p).L_bc ≈   [0.13  -0.08   0.;  -0.48   0.61  -0.08; 0. -0.48   0.53] # SDO_negative_drift(pi_profit, p).L_bc
    @test DEO_negative_drift(pi_profit, p).Lₓ ≈ [-0.08 0.08 0.; .48 -.56 .08; 0. .48 -.48] # SDO_negative_drift(pi_profit, p).Lₓ
    @test DEO_negative_drift(pi_profit, p).L₁₋bc ≈ [0. 0. 0.; -4. 4. 0.; 0. -4. 4.] # SDO_negative_drift(pi_profit, p).L₁₋bc
    @test DEO_negative_drift(pi_profit, p).L₂bc ≈ [-16. 16. 0.; 16. -32. 16.; 0. 16. -16.] # SDO_negative_drift(pi_profit, p).L₂bc
end
p = params(μ = 0.1);
#----------------------------------
#Testing For Positive Drifts
#----------------------------------
# SimpleDifferentialOperators setup
#=function SDO_positive_drift(pi_profit, params)
    bc = (Reflecting(), Reflecting())
    Lₓ = params.μ*L₁₊bc(params.x̄, bc) + params.σ^2 / 2 * L₂bc(params.x̄, bc)
    L_bc = I * params.ρ - Lₓ
    v = L_bc \ pi_profit.(params.x);
    return (v = v, L_bc = L_bc, Lₓ = Lₓ, L₁₊bc = L₁₊bc(params.x̄, bc), L₂bc = L₂bc(params.x̄, bc))
end=#
# DiffEqOperators Setup
function DEO_positive_drift(pi_profit, params)
    dx = params.x[2] - params.x[1]
    # discretize L = ρ - μ D_x - σ^2 / 2 D_xx
    # subject to reflecting barriers at 0 and 1
    L1 = UpwindDifference(1,1,dx,params.M,1.0)
    L2 = CenteredDifference(2,2,dx,params.M)
    Q = Neumann0BC(dx, 1)
    # Here Array(A::GhostDerivativeOperator) will return a tuple of the linear part
    # and the affine part of the operator A, hence we index Array(µ*L1*Q).
    # The operators in this example are purely linear, so we don't worry about Array(µ*L1*Q)[2]
    Lₓ = Array(params.µ*L1*Q)[1] + Array(params.σ^2/2*L2*Q)[1]
    L_bc = I * params.ρ - Lₓ

    # solve the value function
    v = L_bc \ pi_profit.(params.x);
    return (v = v, L_bc = L_bc, Lₓ = Lₓ, L₁₊bc = Array(L1*Q)[1], L₂bc = Array(L2*Q)[1] )
end

@testset "Constant Positive Drifts" begin
    @test DEO_positive_drift(pi_profit, p).v ≈  [8.855633802816902, 9.647887323943664, 10.264084507042257] # SDO_positive_drift(pi_profit, p).v
    @test DEO_positive_drift(pi_profit, p).L_bc ≈  [0.53 -0.48 0.; -0.08  0.61 -0.48; 0. -0.08  0.13] # SDO_positive_drift(pi_profit, p).L_bc
    @test DEO_positive_drift(pi_profit, p).Lₓ ≈  [-0.48 0.48 0.; 0.08 -0.56 0.48; 0. 0.08  -0.08] # SDO_positive_drift(pi_profit, p).Lₓ
    @test DEO_positive_drift(pi_profit, p).L₁₊bc ≈ [-4. 4. 0.; 0. -4. 4.; 0. 0. 0.] # SDO_positive_drift(pi_profit, p).L₁₊bc
    @test DEO_positive_drift(pi_profit, p).L₂bc ≈ [-16. 16. 0.; 16. -32. 16.; 0. 16. -16.] # SDO_positive_drift(pi_profit, p).L₂bc
end

#----------------------------------
#Testing For State Dependent Drifts
#----------------------------------
μ(x) = -x
# SimpleDifferentialOperators setup
#=function SDO_state_dependent_drift(pi_profit, μ, params)
    bc = (Reflecting(), Reflecting())
    L₁ = Diagonal(min.(μ.(params.x), 0.0)) * L₁₋bc(params.x̄, bc) + Diagonal(max.(μ.(params.x), 0.0)) * L₁₊bc(params.x̄, bc)
    Lₓ = L₁ - params.σ^2 / 2 * L₂bc(params.x̄, bc)
    L_bc = I * params.ρ - Lₓ
    v = L_bc \ pi_profit.(params.x)
    return (v = v, L_bc = L_bc,  Lₓ = Lₓ, L₁ = L₁, L₂bc = L₂bc(params.x̄, bc))
end=#
# DiffEqOperators Setup
function DEO_state_dependent_drift(pi_profit, μ, params)
    dx = params.x[2] - params.x[1]
    # discretize L = ρ - μ D_x - σ^2 / 2 D_xx
    # subject to reflecting barriers at 0 and 1
    drift = μ.(params.x)
    L1 = UpwindDifference(1,1,dx,params.M,drift)
    L2 = CenteredDifference(2,2,dx,params.M)
    Q = Neumann0BC(dx, 1)
    # Here Array(A::GhostDerivativeOperator) will return a tuple of the linear part
    # and the affine part of the operator A, hence we index Array(µ*L1*Q).
    # The operators in this example are purely linear, so we don't worry about Array(µ*L1*Q)[2]
    L₁ = Array(L1*Q)[1]
    Lₓ = L₁ - Array(params.σ^2/2*L2*Q)[1]
    L_bc = I * params.ρ - Lₓ

    # solve the value function
    v = L_bc \ pi_profit.(params.x);
    return (v = v, L_bc = L_bc, Lₓ = Lₓ, L₁ = L₁, L₂bc = Array(L2*Q)[1] )
end

@testset "State Dependent Drifts" begin
    @test DEO_state_dependent_drift(pi_profit, μ, p).v ≈ [1.1027342984846056, 1.194775361931727, 1.3640552379934825] # SDO_state_dependent_drift(pi_profit, μ, p).v
    @test DEO_state_dependent_drift(pi_profit, μ, p).L_bc ≈ [-0.03 0.08 0. ;-1.92 1.89 0.08; 0. -2.92 2.97] # SDO_state_dependent_drift(pi_profit, μ, p).L_bc
    @test DEO_state_dependent_drift(pi_profit, μ, p).Lₓ ≈ [0.08 -0.08 0.; 1.92 -1.84 -0.08; 0. 2.92 -2.92]# SDO_state_dependent_drift(pi_profit, μ, p).Lₓ
    @test DEO_state_dependent_drift(pi_profit, μ, p).L₁ ≈ [0.0 0.0 0.; 2.0 -2.0 0.0; 0. 3.0 -3.0] # SDO_state_dependent_drift(pi_profit, μ, p).L₁
    @test DEO_state_dependent_drift(pi_profit, μ, p).L₂bc ≈ [-16. 16. 0.; 16. -32. 16.; 0. 16. -16.] # SDO_state_dependent_drift(pi_profit, μ, p).L₂bc
end

#----------------------------------
#Testing For Absorbing BC
#----------------------------------

# payoff function
pi_profit(x) = x^2
# SimpleDifferentialOperators setup
#=function SDO_absorbing_bc(pi_profit, params)
    bc = (NonhomogeneousAbsorbing(params.S), Reflecting())
    Lₓbc = params.μ*L₁₋bc(params.x̄, bc) + params.σ^2 / 2 * L₂bc(params.x̄ , bc)
    L_bc = I * params.ρ - Lₓbc

    # construct the RHS with affine boundary
    pi_profit_star = pi_profit.(params.x) + L₀affine(params.x̄, pi_profit.(params.x), bc)

    # solve the value function
    v = L_bc \ pi_profit_star

    return (v = v, L_bc = L_bc, Lₓbc = Lₓbc, L₁₋bc = L₁₋bc(params.x̄, bc), L₂bc = L₂bc(params.x̄, bc),
        pi_profit_star = pi_profit_star, pi_profit = pi_profit.(params.x))
end=#

# DiffEqOperators Setup
function DEO_absorbing_bc(pi_profit, params)
    dx = params.x[2] - params.x[1]

    L1 = UpwindDifference(1,1,dx,params.M,params.μ)
    L2 = CenteredDifference(2,2,dx,params.M)
    # RobinBC(l::NTuple{3,T}, r::NTuple{3,T}, dx::T, order = 1)
    # The variables in l are [αl, βl, γl], and correspond to a BC of the form αl*u(0) + βl*u'(0) = γl
    # imposed on the lower index boundary. The variables in r are [αr, βr, γr],
    # and correspond to an analagous boundary on the higher index end.
    l = (1.0, 0.0, p.S)
    r = (0.0, 1.0, 0.0)
    Q = RobinBC(l, r, dx, 1)

    Lₓbc = Array(L1*Q)[1] + Array(params.σ^2/2*L2*Q)[1]
    L_bc = I * params.ρ - Lₓbc

    # solve the value function
    v = L_bc \ pi_profit.(params.x)
    return (v = v, L_bc = L_bc, Lₓbc = Lₓbc, L₁₋bc = Array(L1*Q)[1] ./ params.μ, L₂bc = Array(L2*Q)[1],
        pi_profit_star = pi_profit.(params.x), pi_profit = pi_profit.(params.x))
end

p = params(x̄ = range(0.0, 1.0, length = (p.M+2)))

@testset "Absorbing BC" begin
    @test DEO_absorbing_bc(pi_profit, p).v ≈  [0.2085953844248779, 0.8092898062396943, 1.7942624660284021] # SDO_absorbing_bc(pi_profit, p).v
    @test DEO_absorbing_bc(pi_profit, p).L_bc ≈   [0.61  -0.08    0.; -0.48   0.61  -0.08; 0.    -0.48   0.53] # SDO_absorbing_bc(pi_profit, p).L_bc
    @test DEO_absorbing_bc(pi_profit, p).Lₓbc ≈  [-0.56   0.08  0.;  0.48  -0.56   0.08; 0.     0.48  -0.48] # SDO_absorbing_bc(pi_profit, p).Lₓbc
    @test DEO_absorbing_bc(pi_profit, p).L₁₋bc ≈ [4.0   0.0   0.; -4.0   4.0  0.0; 0.   -4.0  4.0] # SDO_absorbing_bc(pi_profit, p).L₁₋bc
    @test DEO_absorbing_bc(pi_profit, p).L₂bc ≈ [-32.0   16.0     0.;  16.0  -32.0   16.0;  0.    16.0  -16.0] # SDO_absorbing_bc(pi_profit, p).L₂bc
    @test DEO_absorbing_bc(pi_profit, p).pi_profit_star ≈ [.0625, .25, .5625] # SDO_absorbing_bc(pi_profit, p).pi_profit_star
    @test DEO_absorbing_bc(pi_profit, p).pi_profit ≈ [.0625, .25, .5625] # SDO_absorbing_bc(pi_profit, p).pi_profit
end

#----------------------------------
#Testing For Solving KFE
#----------------------------------

#=function SDO_Solve_KFE(params)
    # ξ values for mixed boundary conditions
    ξ_lb = ξ_ub = -2 * params.μ / params.σ^2
    # define the corresponding mixed boundary conditions
    # note that the direction on the lower bound is backward (default is forward)
    # as the drift μ is negative.
    bc = (Mixed(ξ = ξ_lb, direction = :backward), Mixed(ξ = ξ_ub))

    # use SimpleDifferentialOperators.jl to construct the operator on the interior
    L_KFE_with_drift = Array(-params.μ*L₁₊bc(params.x̄, bc) + params.σ^2 / 2 * L₂bc(params.x̄, bc))
    L_KFE_without = params.σ^2 / 2 * L₂bc(params.x̄, bc)
    return (L_KFE_with_drift = L_KFE_with_drift, L_KFE_without = L_KFE_without)
end=#

#=function SDO_Solve_KFE_forward(params)
    # ξ values for mixed boundary conditions
    ξ_lb = ξ_ub = -2 * params.μ / params.σ^2
    # define the corresponding mixed boundary conditions
    # but with forward finite difference derivatives at boundaries
    bc = (Mixed(ξ = ξ_lb, direction = :forward), Mixed(ξ = ξ_ub))

    # use SimpleDifferentialOperators.jl to construct the operator on the interior
    L_KFE_with_drift = Array(-params.μ*L₁₊bc(params.x̄, bc) + params.σ^2 / 2 * L₂bc(params.x̄, bc))
    L_KFE_without = params.σ^2 / 2 * L₂bc(params.x̄, bc)
    return (L_KFE_with_drift = L_KFE_with_drift, L_KFE_without = L_KFE_without)
end=#

function DEO_Solve_KFE(params)
    dx = params.x[2] - params.x[1]

    L1 = UpwindDifference(1,1,dx,params.M,-params.μ)
    # L2l = UpwindDifference(2,2,dx,params.M,
    #                          vcat(-1.,zeros(params.M-1)))
    # L2r = UpwindDifference(2,2,dx,params.M,
    #                          vcat(zeros(params.M-1),1.))
    L2 = CenteredDifference(2,2,dx,params.M)

    ξ_lb = ξ_ub = -2 * params.μ / params.σ^2

    l = (ξ_lb, 1., 0.)
    r = (ξ_ub, 1., 0.)
    Q = RobinBC(l, r, dx, 1)

    # use SimpleDifferentialOperators.jl to construct the operator on the interior
    # Only difference is handling of L2, we may need to upwind for boundary
    L_KFE_with_drift = Array(L1*Q)[1] + Array(params.σ^2/2 *L2*Q)[1]
    L_KFE_without = (params.σ^2 / 2) .* Array(L2 * Q)[1]
    # L_KFE_without = (params.σ^2 / 2) .* ([0., 1., 0.] .* Array(L2 * Q)[1] +
    #     -(Array(L2l * Q)) + Array(L2r * Q))

    return (L_KFE_with_drift = L_KFE_with_drift, L_KFE_without = L_KFE_without)
end

p = params(x̄ = range(0.0, 1.0, length = (p.M+2)))
@testset "Solving KFE" begin
    # @test_broken DEO_Solve_KFE(p).L_KFE_with_drift ≈ SDO_Solve_KFE(p).L_KFE_with_drift # concretization of Robin conditions appears broken
    # @test_broken DEO_Solve_KFE(p).L_KFE_without ≈ SDO_Solve_KFE(p).L_KFE_without # Hard to check what's wrong since KFE uses forward/backward at boundaries rather than central differences when w/mixed bcs
    @test DEO_Solve_KFE(p).L_KFE_with_drift ≈ [-0.58   0.48   0.0;  0.08  -0.56   0.48;  0.0    0.08  -0.48] # SDO_Solve_KFE_forward(p).L_KFE_with_drift
    @test DEO_Solve_KFE(p).L_KFE_without ≈ [-0.18   0.08 0.;  0.08  -0.16   0.08; 0.  0.08  -0.1466666666666667] # SDO_Solve_KFE_forward(p).L_KFE_without
end

nothing


text:
module BackgroundSubtraction
using LinearAlgebra
using LinearAlgebraExtensions
using LinearAlgebraExtensions: LowRank, pals!, projection, grid, AbstractMatOrFac
using KroneckerProducts: kronecker
using CovarianceFunctions
using Statistics

export mcbl
export kronecker_mcbl

include("background.jl")

end

ext: jl


text:
# module EPInference

using Compat
using ExpFamily

const Float = Float64

# export
#     impsampling

include("samplers.jl")
include("epalgorithms.jl")

#end # module


text:
module NaNMathGlue
using ChainRulesCore
using NaNMath

@scalar_rule(NaNMath.sin(x), NaNMath.cos(x))
@scalar_rule(NaNMath.cos(x), -NaNMath.sin(x))
@scalar_rule(NaNMath.asin(x), inv(NaNMath.sqrt(1 - NaNMath.pow(x, 2))))
@scalar_rule(NaNMath.acos(x), -inv(NaNMath.sqrt(1 - NaNMath.pow(x, 2))))
@scalar_rule(NaNMath.acosh(x), inv(NaNMath.sqrt(NaNMath.pow(x, 2) - 1)))
@scalar_rule(NaNMath.atanh(x), inv(1 - NaNMath.pow(x, 2)))
@scalar_rule(NaNMath.log(x), inv(x))
@scalar_rule(NaNMath.log2(x), inv(x) / NaNMath.log(oftype(x, 2)))
@scalar_rule(NaNMath.log10(x), inv(x) / NaNMath.log(oftype(x, 10)))
@scalar_rule(NaNMath.log1p(x), inv(x + 1))
@scalar_rule(NaNMath.lgamma(x), SpecialFunctions.digamma(x))
@scalar_rule(NaNMath.sqrt(x), inv(2 * Ω))
@scalar_rule(NaNMath.pow(x, y), (y * NaNMath.pow(x, y - 1), Ω * NaNMath.log(x)))

end #module


text:
# Required packages
using Distances,
      Pathogen,
      Random,
      Plots,
      Plots.PlotMeasures; # Plots.PlotMeasures is used for advanced formatting control for figure output

Random.seed!(42);

n = 100
risks = DataFrame(x = rand(Uniform(0, 15), n),
                  y = rand(Uniform(0, 30), n),
                  riskfactor1 = rand(Gamma(), n))

# Precalculate distances
dists = [euclidean([risks[i, :x];
                    risks[i, :y]],
                   [risks[j, :x];
                    risks[j, :y]]) for i = 1:n, j = 1:n]

pop = Population(risks, dists)

println(pop)

# Define risk functions/TN-ILM structure
function _constant(θ::Vector{Float64}, pop::Population, i::Int64)
    return θ[1]
end

function _one(θ::Vector{Float64}, pop::Population, i::Int64)
    return 1.0
end

function _linear(θ::Vector{Float64}, pop::Population, i::Int64)
    return θ[1] * pop.risks[i, :riskfactor1]
end

function _powerlaw(θ::Vector{Float64}, pop::Population, i::Int64, k::Int64)
    d = pop.distances[k, i]
    return d^(-θ[1])
end

rf = RiskFunctions{SIR}(_constant, # sparks function
                          _one, # susceptibility function
                          _powerlaw, # infectivity function
                          _one, # transmissability function
                          _linear) # removal function

  # Parametrize risk functions for simulation
rparams = RiskParameters{SIR}([0.0001], # sparks function parameter(s)
                                Float64[], # susceptibility function parameter(s)
                                [4.0], # infectivity function parameter(s)
                                Float64[], # transmissibility function parameter(s)
                                [0.1]) # removal function parameter(s)

# Set starting states in population
# Set first individual as infectious, others as susceptible to start
starting_states = [State_I; fill(State_S, n - 1)]

# Initialize Simulation
sim = Simulation(pop, starting_states, rf, rparams)

# Simulate!
simulate!(sim, tmax = 200.0)

gr(dpi = 200) # GR backend with DPI = 200

# Epidemic Curve
p1 = plot(sim.events, 0.0, 200.0, legendfont = font(6), xaxis = font(10), bottom_margin = 30px)

# Population/TransmissionNetwork plots
p2 = plot(sim.transmission_network, sim.population, sim.events, 0.0, title = "Time = 0", titlefontsize = 8)
p3 = plot(sim.transmission_network, sim.population, sim.events, 10.0, title = "Time = 10", titlefontsize = 8)
p4 = plot(sim.transmission_network, sim.population, sim.events, 20.0, title = "Time = 20", titlefontsize = 8)
p5 = plot(sim.transmission_network, sim.population, sim.events, 30.0, title = "Time = 30", titlefontsize = 8)
p6 = plot(sim.transmission_network, sim.population, sim.events, 50.0, title = "Time = 50", titlefontsize = 8)

l = @layout [a
             grid(1, 5)]
combinedplots1 = plot(p1, p2, p3, p4, p5, p6, layout = l)
png(combinedplots1, joinpath(@__DIR__, "epiplot.png"))

# Transmission animation
anim = @animate for simtime = range(0.0, 200.0, step = 1.0)
    p1 = plot(sim.transmission_network, sim.population, sim.events, simtime, markersize = 4, legend = :none, xlim = (-2, 17))
    p2 = plot([simtime], [1.0], seriestype = :scatter, markercolor = :black, markersize = 4, marker = :dtriangle, legend = :none, xlabel = "Time", framestyle = :origin, grid = :none, tick_direction = :out, yaxis = false, xticks = 0:25:200, aspect_ratio = 4, ylim = (-1, 1), xlim = (-10, 210), xaxis = font(8))
    l = @layout [a{0.975h}; b]
    plot(p1, p2, layout = l)
end
gif(anim, joinpath(@__DIR__, "epianimation.gif"), fps = 20);

max_issues_repo_name: MLH-Fellowship/CodeVidLive


text:
module SLab

using Cbc
using CSV
using DataFrames
using Dates
using JuMP
using Plots
using Plots.PlotMeasures
using Serialization

include("types.jl")
include("load.jl")
include("schedule.jl")
include("plot.jl")

function main(case_name::String, case_path::String)
    machines, batches, plot_range = load_case(case_path)

    # misc parameters
    current_time = DateTime(2021, 1, 1, 9, 0, 0)
    order_time = current_time + Hour(1)
    beta = 1 * 60
    scheduled_jobs = Vector{Job}()

    # run scheduling
    execution_time = 0
    for batch in batches
        execution_time = schedule(batch, scheduled_jobs, machines, order_time, beta, threads = 12)
    end
    print("Jobs will be completed in $(execution_time / 60) minutes.\n")

    # save and plot scheduling result
    serialize(joinpath(case_path, "$(case_name)_result"), (scheduled_jobs, machines, current_time))

    plot_schedule(
        scheduled_jobs,
        machines,
        xlims = (
            Dates.value.(current_time + Minute(50)),
            Dates.value.(current_time + Hour(plot_range)),
        ),
        size = (800, 600),
    )
    savefig(joinpath(case_path, "$(case_name)_result.pdf"))
end

end


text:
# ---
# title: 416. Partition Equal Subset Sum
# id: problem416
# author: Tian Jun
# date: 2020-10-31
# difficulty: Medium
# categories: Dynamic Programming
# link: <https://leetcode.com/problems/partition-equal-subset-sum/description/>
# hidden: true
# ---
#
# Given a **non-empty** array `nums` containing **only positive integers** ,
# find if the array can be partitioned into two subsets such that the sum of
# elements in both subsets is equal.
#
#
#
# **Example 1:**
#
#
#
#     Input: nums = [1,5,11,5]
#     Output: true
#     Explanation: The array can be partitioned as [1, 5, 5] and [11].
#
#
# **Example 2:**
#
#
#
#     Input: nums = [1,2,3,5]
#     Output: false
#     Explanation: The array cannot be partitioned into equal sum subsets.
#
#
#
#
# **Constraints:**
#
#   * `1 <= nums.length <= 200`
#   * `1 <= nums[i] <= 100`
#
#
## @lc code=start
using LeetCode

## add your code here:
## @lc code=end


text:
using Xkcd221, Test, Random

@testset begin

    rng = Xkcd221RNG()

    @test rng.seed == 4
    c = copy(rng)
    @test c.seed == 4
    copy!(c, rng)
    @test c.seed == 4
    @test c !== rng
    @test c == rng
    @test hash(c) == hash(rng)
    @test hash(c) == hash(rng)
    @test hash(c, UInt(123)) == hash(rng, UInt(123))

    @testset for T in Base.BitInteger_types
        @test rand(rng, T) == 4
    end

    @testset for T in Base.BitInteger_types
        @test rand(rng, T(0):T(10)) == 4
        @test rand(rng, T(3):T(10)) == 7
        @test rand(rng, T(0):T(3)) == 1
        @test rand(rng, T(1):T(2)) == 1
        @test rand(rng, T(10):-1:T(1)) == 6
        @test rand(rng, T(21):-3:T(4)) == 9
        @test rand(rng, T(21):-3:T(14)) == 21
        @test rand(rng, T(21):-3:T(12)) == 18
    end
    @test rand(rng, 0:0) == 0
    @test rand(rng, 12.0:-3:2.0) == 9.0

    a = [1:10;]
    shuffle!(rng, a)
    @test a == [4,3,1,2,6,7,8,9,10,5]

end


text:
export SolitaryWaveSerreGreenNaghdi, SolitarySGN

"""
    SolitaryWaveSerreGreenNaghdi(param; x₀=0)

Compute the Serre-Green-Naghdi solitary wave with prescribed velocity.

# Arguments
- `param :: NamedTuple`: parameters of the problem containing velocity `c` \
and dimensionless parameters `ϵ` and `μ`, \
and mesh size `L` and number of collocation points `N`;
- `x₀ :: Real`: (keyword, optional, default = 0) center of solitary wave.

# Return values
`(η,u,v,mesh)` with
- `η :: Vector{Float64}`: surface deformation;
- `u :: Vector{Float64}`: layer-averaged velocity;
- `v :: Vector{Float64}`: derivative of the trace of the velocity potential at the surface;
- `mesh :: Mesh`: mesh collocation points.

"""
function SolitaryWaveSerreGreenNaghdi(
                param :: NamedTuple;
                x₀ = 0 :: Real
                        )

        c = param.c
        ϵ = param.ϵ
        μ = param.μ
		if abs(c)<1
			@error("The velocity must be greater than 1 (in absolute value).")
		end

        mesh = Mesh(param)

        η = (c^2-1)/ϵ*sech.(sqrt(3*(c^2-1)/(c^2)/μ)/2*(mesh.x.-x₀)).^2

        h = 1 .+ ϵ*η
        u = c*η./h

		k = mesh.k
        Dx       =  1im * k

        DxF(v) = real.(ifft(Dx .* fft(v)))
		v = u - μ/3 ./h .* (DxF(h.^3 .*DxF(u)))

        return (η,u,v,mesh)

end

"""
    SolitarySGN(param; x₀=0)

Build the initial data associated with `SolitaryWaveSerreGreenNaghdi(param; x₀=0)`, of type `InitialData`,
to be used in initial-value problems `Problem(model, initial::InitialData, param)`.

---
	SolitarySGN(c; ϵ=1,μ=1,x₀=0,N=2^12)

Build the initial data with velocity `c`, center `x₀`, dimensionless parameters `ϵ` and `μ`, and number of collocation points `N`.
"""
struct SolitarySGN <: InitialData

	η
	v
	label :: String
	info  :: String

	function SolitarySGN(param::NamedTuple; x₀=0::Real)
		(η,u,v,mesh)=SolitaryWaveSerreGreenNaghdi(param; x₀)
		init = Init(mesh,η,v)
		label = "Green-Naghdi solitary wave"
		info = "Solitary travelling wave for the Serre-Green-Naghdi model.\n\
		├─velocity c = $(param.c)\n\
		└─maximum h₀ = $((param.c^2-1)/param.ϵ) (from rest state)."

		new( init.η,init.v,label,info  )
	end

	function SolitarySGN(c::Real; ϵ=1::Real,μ=1::Real,x₀=0::Real,N=2^12::Int)
		L=200/sqrt(3*(c^2-1)/(c^2)/μ)/2
		xmin,xmax = x₀-L,x₀+L;
		param=(ϵ=ϵ,μ=μ,c=c,L=L,xmin=xmin,xmax=xmax,N=N)
		sol=SolitarySGN(param;x₀=x₀)
		new( sol.η,sol.v,sol.label,sol.info  )
	end

end


text:
const PatternX = Union{Pattern, Regex, Integer, Symbol}

## Patterns

### And

struct And <: Pattern
    xs::Vector{PatternX}
end

And() = And(PatternX[])
and(xs...) = And(PatternX[make_pattern(x) for x in xs])

==(a::And, b::And) = a.xs == b.xs

### Or

struct Or <: Pattern
    xs::AbstractArray{<:PatternX}
end

Or() = Or(PatternX[])
or(xs...) = Or(PatternX[make_pattern(x) for x in xs])

==(a::Or, b::Or) = a.xs == b.xs

### Not

struct Not <: Pattern
    x::PatternX
end

==(a::Not, b::Not) = a.x == b.x

### Reachable

struct Reachable <: Pattern
    x::PatternX
end

==(a::Reachable, b::Reachable) = a.x == b.x

### depth

struct Depth <: Pattern
    d::Int
end

### Interpolated

struct Interpolated <: Pattern end

### pass/fail

struct Pass <: Pattern end
const pass = Pass()

struct Fail <: Pattern end
const fail = Fail()

### iter

struct Iter <: Pattern
    i::Int
end

## alwaysmatches

alwaysmatches(pat::And, d) = all(p -> alwaysmatches(p, d), pat.xs)

alwaysmatches(pat::Or, d) =
    if pat.xs isa AbstractArray{<:Integer}
        false # special case for huge unit ranges; locally, this optimization seems
              # unnecessary, i.e. alwaysmatches(Or(1:10...0)) is constant time anyway,
              # but on CI, the any(...) below takes tooooo long
    else
        any(p -> alwaysmatches(p, d), pat.xs)
    end

alwaysmatches(::Not, _) = false
alwaysmatches(::Interpolated, _) = false
alwaysmatches(rx::Regex, _) = isempty(rx.pattern)
alwaysmatches(id::Integer, _) = false
alwaysmatches(label::Symbol, _) = false
alwaysmatches(pat::Reachable, d) = alwaysmatches(pat.x, d)
alwaysmatches(dep::Depth, d) = dep.d == d
alwaysmatches(::Pass, _) = false
alwaysmatches(::Fail, _) = false
alwaysmatches(::Iter, _) = false

## matches

matches(pat::And, x, ts) = all(p -> matches(p, x, ts), pat.xs)

matches(pat::Or, x, ts) =
    if pat.xs isa AbstractUnitRange{<:Integer} && minimum(pat.xs) >= 0
        ts.id ∈ pat.xs # this is optimised, i.e. it's not O(n)
    else
        any(p -> matches(p, x, ts), pat.xs)
    end

matches(pat::Not, x, ts) = !matches(pat.x, x, ts)
matches(::Interpolated, x::Union{Missing,AbstractString}, ts) = x !== missing
matches(rx::Regex, x, _) = occursin(rx, x)
matches(rx::Regex, ::Missing, ts) = alwaysmatches(rx, tsdepth(ts)) | missing
matches(pat::Integer, _, ts) =
    @inbounds pat >= 0 ?
        pat == ts.id :
        pat != -ts.id

matches(label::Symbol, subj::AbstractString, ts) = hasmark(ts.marks, subj, label)
matches(label::Symbol, subj::Missing, ts) = missing
# TODO: optimize by recording possible labels for missing, to allow returning false
# in some cases

function matches(pat::Reachable, desc, ts)
    if desc !== missing
        desc = SubString(desc)
    end
    m = false
    while true
        m |= matches(pat.x, desc, ts)
        m === true && return true
        ts.parent === nothing && break
        ts = ts.parent
        if desc !== missing
            desc = SubString(desc, 1, findlast('/', desc)-1)
        end
    end
    m
end

matches(d::Depth, _, ts) = d.d == tsdepth(ts)

matches(::Pass, subj::AbstractString, ts) = something(pastresult(ts.marks, subj), false)
matches(::Fail, subj::AbstractString, ts) = !something(pastresult(ts.marks, subj), true)
# TODO: test method below
# instead of `isempty(ts.marks.soft)`, a tighter test would be to check that no value in marks
# contains the pass/fail marks; but this would be a bit more expensive, as values have to be
# iterated over
matches(::Union{Pass,Fail}, ::Missing, ts) =
    isempty(ts.marks.soft) ? false : missing

matches(i::Iter, subj, ts) =
    if ts.iter isa Int
        i.i == ts.iter
    else
        i.i ∈ ts.iter
    end

## has

# has(pat, T) checks whether pat recursively "contains" something of type T
has(pat, T::Type)  = pat isa T
has(pat::Union{And,Or}, T::Type) = pat isa T || any(p -> has(p, T), pat.xs)
has(pat::Union{Not,Reachable}, T::Type) = pat isa T || has(pat.x, T)

## make_pattern

make_pattern(x::PatternX) = x

function make_pattern(str::AbstractString)
    neg = false
    if startswith(str, '-')
        str = chop(str, head=1, tail=0)
        if !startswith(str, '-')
            neg = true
        end
    end

    rx =
        if isempty(str)
            r"" # in order to know to match unconditionally
        elseif VERSION >= v"1.3"
            r""i * str
        else
            Regex(str, "i")
        end
    neg ? not(rx) : rx
end

make_pattern(pat::AbstractArray) = Or(PatternX[make_pattern(p) for p in pat])
# special case for optimizing unit-ranges:
make_pattern(pat::AbstractArray{<:Integer}) = Or(pat)
make_pattern(@nospecialize(pat::Tuple)) = And(PatternX[make_pattern(p) for p in pat])

## exported pattern functions & singletons

"""
    not(pattern)

Create an object suitable for filtering testsets (in the [`retest`](@ref) function),
which "negates" the meaning of `pattern`: a testset matches `not(pattern)`
if and only if it doesn't match `pattern`.

For example `not("a")` matches any testset whose subject doesn't contain `"a"`,
and `not(1:3)` matches all the testsets but the first three of a module.

If `pattern` is an integer or a `ReTest` object (i.e. not a `AbstractString`,
`Regex`, `Tuple` or `AbstractArray`), `not(pattern)` can be expressed as `-pattern`.

`String` patterns can also be negated by prepending `'-'`, see [`retest`](@ref)
for details.
"""
not(x) = Not(make_pattern(x))

Base.:-(x::Pattern) = not(x)

"""
    interpolated

Singleton pattern which matches any testset whose subject can be interpolated
"statically", i.e. at filtering time before testset are actually run.
Non-inferrable subjects include those constructed from descriptions
containing interpolated values which can't be known until run time.
This pattern has an effect closely related to that of the `static` keyword
of [`retest`](@ref), discussed below, which is probably more generally useful.

# Examples

Given these testset:
```julia
@testset "outer" verbose=true begin
    @test true
    inner = "inner"
    @testset "\$inner" begin
        @test true
    end
end
@testset "other" begin
    @test true
end
```
We get:
```julia
julia> retest("other", dry=true)
Main
1| outer
2|   "\$(inner)"
3| other

julia> retest("other", dry=false)
            Pass
outer   |      1
other   |      1
Main    |      2

julia> retest("other", dry=true, interpolated)
Main
3| other
```

Without `interpolated`, `retest` can't decide at filtering time whether the "inner"
testset will run, so must mark the "outer" testset as having to run. At run
time, "inner" is not run because it doesn't match the pattern, but "outer"
still had to run to determine this. With the `interpolated` pattern, "inner" is
filtered out and `retest` selects only testsets which are statically known to
have to run.

So again, `interpolated` doesn't have the same effect at filtering time (like when
`dry=true`) and at run time.
For example, one can see the list of non-interpolated subjects as follows with
`dry=true`, but not run them (because everything is interpolated at run time):

```julia
julia> retest(not(interpolated), dry=true)
1| outer
2|   "\$(inner)"

julia> retest(not(interpolated), dry=false)
            Pass
Main:
  outer |      1
```

### `static` keyword

Unlike `interpolated`, the `static` keyword of `retest`, when `true`,
filters out only testsets which can't be proven to have to run at filtering time,
let's call them "undecidable".
It can have sometimes the same effect as when using `interpolated`,
e.g. `retest("other", dry=true, static=true)` and
`retest("other", dry=true, interpolated)` give the same result.

But in some cases we might want to filter out noisy testsets whose
subjects can't be interpolated, but still include those which are
relevant. For example, assume we want to run testsets `1` and `2`,
while excluding other testsets with uninterpolated subjects:
```julia
julia> retest(1:2, dry=true, interpolated)
Main
1| outer

julia> retest(1:2, dry=true, static=true)
Main
1| outer
2|   "\$(inner)"
```
The solution with `interpolated` is not what we want, as we specifically
want testset `2` to run. Given the filtering specifications (`1:2` here),
the filtering algorithm can determine that `2` should run even though
its subject is unknown at this point.

Given a filtering specification, there are three kind of testsets:
* "undecidable" (see above)
* "match": they are known statically to have to run
* "nomatch": they are known statically to not have to run

The default value of the `static` keyword is `nothing`, which means
to run testsets which are not known with certainty to not match,
i.e. "match" and "undecidable" testsets.
As seen above, when `static == true`, only "match" testsets are run.
When `static == false`, the behavior is the opposite: only "undecidable"
testsets are run.
Of course, other combinations involving "nomatch" testsets can be had
by reversing the filtering pattern via [`not`](@ref).

For example, to get the equivalent to the `not(interpolated)` example above,
but with an effect which persists at run time (`dry = false`),
you can use `static = false` together with the match-all regex pattern `r".*"`,
which will mark the `"inner"` testset as "undecidable"
(the algorithm inspects slightly patterns just to recognize the simple
match-all patterns `""` and `r""`, but won't detect that `r".*"` would
match `"\$(inner)"`):
```julia
julia> retest(r".*", static=false, dry=true)
Main
1| outer
2|   "\$(inner)"

julia> retest(r".*", static=false, dry=false)
               Pass
Main:
  outer    |      2
    inner  |      1
```

One example of a rare case where a given testset is not in a single of the
above three categories is as follows:

```julia
@testset "a" begin
    x = 2
    @testset "b\$(i==1 ? 1 : x)" for i=1:2
        @testset "c" begin
            # subject is "match" at first iteration and
            # "undecidable" at second iteration
            @test true
        end
    end
end
```

One thing to understand is that the "identity" of a testset is determined
by a given occurrence of the `@testset` macro. In the example above,
for either the patterns "b" or "c", the two inner testsets are both
"match" and "undecidable". In this case, the filtering algorithm
selects a testset to run if at least one iteration would lead to
this decision. Here, if `static=true` the first iteration
would run, and if `static=false` the second iteration would run.
This results in the same selection whatever the value of `static` is.
"""
const interpolated = Interpolated()

"""
    reachable(pattern)

Create a filtering pattern which matches any testset matching `pattern`
or whose parent testset, if any, matches `reachable(pattern)`.
In other words, if a testset matches `pattern`, all its recursive
nested testsets will also match.

When `pattern::String`, `reachable(pattern)` has the same effect as
`pattern`, because the subject of a testset is contained in the
subjects of all its nested testsets. So `reachable` is typically
useful when `pattern` is an integer.

# Examples
```julia
julia> module T
       using ReTest
       @testset "a" verbose=true begin
           @test true
           @testset "b" begin
               @test true
           end
       end
       @testset "c" begin
           @test true
       end
       end;

julia> retest(T, reachable(1), dry=true)
1| a
2|   b

julia> retest(T, not(reachable(1)), dry=true)
3| c
```

Note that the algorithm for `reachable` is currently not optimized, i.e.
it will match `pattern` against all parents of a testset until success,
even when this match was already performed earlier (i.e. the result
of matching against `pattern` is not cached).

Also, in the current implementation, the subject of a parent testset is
inferred from the subject of a testset, by chopping off the last component,
determined by the last occurrence of `'/'`. This has two consequences. It will
produce incorrect results if the description of a testset contains `'/'`, and
also, with [`interpolated`](@ref) when the subject is "unknown" due to
un-interpolated descriptions. Consider the following example:

```julia
julia> module Fail
       using ReTest
       @testset "a" begin
           x = 1
           @testset "b\$x" begin
               @testset "c" begin end
           end
       end
       end;

julia> retest(Fail, reachable(1), verbose=9, dry=true)
1| a
2|   "b\$(x)"
3|     c

julia> retest(Fail, reachable(interpolated), verbose=9, dry=true)
1| a
```

Here, both testsets with id `2` and `3` have an unknown subject (at
filtering time), which prevents the algorithm to detect that one of their
parents (testset `1`) actually has an "interpolated" description.

On the other hand, even with these unknown subjects, something like
`reachable("a")` would work as expected:

```julia
julia> retest(Fail, reachable("a"), verbose=9, dry=true)
1| a
2|   "b\$(x)"
3|     c

julia> retest(Fail, reachable("a"), verbose=9, dry=true, static=true)
1| a
```

!!! compat "Julia 1.3"
    This function requires at least Julia 1.3.
"""
function reachable end

if VERSION >= v"1.3"
    reachable(x) = Reachable(make_pattern(x))
end

"""
    depth(d::Integer)

Create a pattern which matches testsets at "depth" `d`.
Toplevel testsets have depth `1`, their direct children
(nested testsets) depth `2`, and so on.

# Examples

```julia
julia> module Depth
       using ReTest
       @testset "1" begin
           @testset "2" begin
               @testset "3" begin end
           end
           @testset "4" begin end
       end
       end;

julia> Depth.runtests(dry=true, verbose=3, depth(2))
1| 1
2|   2
4|   4

julia> Depth.runtests(dry=true, verbose=3, depth(3))
1| 1
2|   2
3|     3

julia> Depth.runtests(dry=true, verbose=3, reachable(depth(2)))
1| 1
2|   2
3|     3
4|   4

julia> Depth.runtests(dry=true, verbose=3, depth.(2:3))
1| 1
2|   2
3|     3
4|   4
```
"""
depth(x::Integer) = Depth(Int(x))

"""
    pass
    fail

Filtering patterns which match any testset which already ran,
succesfully for `pass` or with at least one error for `fail`.
The pattern `[pass, fail]` therefore matches any testset
which already ran.
"""
pass, fail

"""
    iter(i::Integer)

Filtering pattern which matches only the `i`-th iteration of a testset-for.
A non-for testset is considered to have a unique iteration.

!!! warning

    This is very experimental, not tested, and likely to be removed in a future version.
"""
iter(i::Integer) = Iter(Int(i))

max_issues_repo_name: rfourquet/InlineTest

max_forks_repo_name: rfourquet/InlineTest


text:
module TestExamples3DMHD

using Test
using Trixi

include("test_trixi.jl")

# pathof(Trixi) returns /path/to/Trixi/src/Trixi.jl, dirname gives the parent directory
EXAMPLES_DIR = joinpath(pathof(Trixi) |> dirname |> dirname, "examples", "3d")

@testset "MHD" begin
  @trixi_testset "elixir_mhd_ec.jl" begin
    @test_trixi_include(joinpath(EXAMPLES_DIR, "elixir_mhd_ec.jl"),
      l2   = [0.017590099293094203, 0.017695875823827714, 0.017695875823827686, 0.017698038279620777, 0.07495006099352074, 0.010391801950005755, 0.010391801950005759, 0.010393502246627087, 2.524766553484067e-16],
      linf = [0.28173002819718196, 0.3297583616136297, 0.32975836161363004, 0.356862935505337, 1.2893514981209626, 0.10950981489747313, 0.10950981489747136, 0.11517234329681891, 2.0816911067714202e-15])
  end

  @trixi_testset "elixir_mhd_ec.jl with initial_condition=initial_condition_constant" begin
    @test_trixi_include(joinpath(EXAMPLES_DIR, "elixir_mhd_ec.jl"),
      l2   = [4.270231310667203e-16, 2.4381208042014784e-15, 5.345107673575357e-15, 3.00313882171883e-15, 1.7772703118758417e-14, 1.0340110783830874e-15, 1.1779095371939702e-15, 9.961878521814573e-16, 8.1201730630719145e-16],
      linf = [2.4424906541753444e-15, 2.881028748902281e-14, 2.4646951146678475e-14, 2.3092638912203256e-14, 2.3447910280083306e-13, 1.7763568394002505e-14, 1.0436096431476471e-14, 2.042810365310288e-14, 7.057203733035201e-15],
      atol = 1000*eps(),
      initial_condition=initial_condition_constant)
  end

  @trixi_testset "elixir_mhd_alfven_wave.jl" begin
    @test_trixi_include(joinpath(EXAMPLES_DIR, "elixir_mhd_alfven_wave.jl"),
      l2   = [0.003872168982949962, 0.009234032031394519, 0.004166855440339939, 0.01160194799648245, 0.006989139550604536, 0.009258319391439123, 0.004972194549900642, 0.011701012705405973, 0.003796916988492686],
      linf = [0.012897588621946787, 0.03317614952204696, 0.011594778657069232, 0.04437495747712844, 0.025695368105128846, 0.03336443221122043, 0.01000776455308272, 0.044820519469304224, 0.01606741448289395])
  end

  @trixi_testset "elixir_mhd_alfven_wave_mortar.jl" begin
    @test_trixi_include(joinpath(EXAMPLES_DIR, "elixir_mhd_alfven_wave_mortar.jl"),
      l2   = [0.0021525855794505733, 0.006723734997085876, 0.0030402457081513405, 0.008711037977296627, 0.005507951439477701, 0.007204815741889562, 0.0029726037822043116, 0.008823488862283192, 0.003551010115322961],
      linf = [0.013133814395385413, 0.05541886629871225, 0.020708270215062375, 0.05932492264609865, 0.03448645356854563, 0.05319127664438378, 0.01770393941703363, 0.060904784306590354, 0.020639279160633826],
      tspan = (0.0, 0.25))
  end

  @trixi_testset "elixir_mhd_alfven_wave.jl with Orszag-Tang setup + flux_hll" begin
    # OBS! This setup does not make much sense and is only used to exercise all components of the
    # flux_hll implementation
    @test_trixi_include(joinpath(EXAMPLES_DIR, "elixir_mhd_alfven_wave.jl"),
      l2   = [0.004391160574957181, 0.041447356654791025, 0.0415012997738177, 0.04150353610875128, 0.036931198261162486, 0.021125598921156254, 0.03295606813944825, 0.032962356174273615, 6.036824268879037e-6],
      linf = [0.017893840542084788, 0.08486753617328145, 0.08910603135148028, 0.08491878976510482, 0.10444599411185623, 0.05381959529402853, 0.08847807738420276, 0.07784629959770338, 7.694931670095901e-5],
      initial_condition = initial_condition_orszag_tang,
      surface_flux = flux_hll,
      volume_flux  = flux_central,
      coordinates_min = (0, 0, 0),
      coordinates_max = (1, 1, 1),
      initial_refinement_level=3,
      cfl = 1.1,
      tspan = (0.0, 0.06))
  end
end

end # module


text:
using PandocFilters: walk!, Plain, Null, Code, Str, Space
using Test, JSON, BenchmarkTools
import PandocFilters

PandocFilters.walk!(x,y) = walk!(x, y, "", Dict{String,Any}())
PandocFilters.walk!(x) = walk!(x, (t,c,m,f) -> nothing)

@testset "Manual roundtrip" begin
 manual_str = open("MANUAL.JSON", "r") do f
    read(f, String)
  end;
  j_manual = JSON.parse(manual_str);

  doc_out = walk!(j_manual, (t,c,m,f) -> nothing)

  @test doc_out == j_manual == JSON.parse(manual_str)

end

@testset "Paragraph" begin
  para = JSON.parse(raw"""{"c":[{"c":"Brief","t":"Str"},{"t":"Space"},{"c":"mathematical","t":"Str"}],"t":"Para"}""")
  j_para = JSON.json(para)
  p_in = copy(para)
  j_test_no_change = JSON.json(walk!(para, (t,c,f,m) -> nothing))

  # Test the json was unchanged
  @test j_para == j_test_no_change
  out = walk!(para, (t,c,f,m) -> t == "Space" ? [] : nothing)
  j_test_no_space = JSON.json(out)

  @test j_test_no_space == raw"""{"c":[{"c":"Brief","t":"Str"},{"c":"mathematical","t":"Str"}],"t":"Para"}"""

  # Check para was mutated
  @test para != p_in
  @test para == out

  # Try doubling the spaces
  j_test_double_space = JSON.json(walk!(p_in, (t,c,f,m) -> t == "Space" ? [Space(), Space()] : nothing))
  @test j_test_double_space == raw"""{"c":[{"c":"Brief","t":"Str"},{"t":"Space"},{"t":"Space"},{"c":"mathematical","t":"Str"}],"t":"Para"}"""

end

@testset "Testing walk with (t,c)->1" begin
    action(t, c, format, meta) = 1
    @test walk!(1,action) == 1
    @test walk!(["string1","string2"],action) == ["string1","string2"]
    @test walk!([1,2,3],action) == [1,2,3]
    @test walk!(Dict("x"=>2,"y"=>3),action) == Dict("x"=>2,"y"=>3)
    @test walk!([Dict("t"=>2,"c"=>3)],action) == [1]
end

@testset "Testing walk with t=>x -> t=>y" begin
    action(t, c, format, meta) = (t=="x") ? Dict("t"=>"y","c"=>c) : nothing
    dict_x = Dict("t"=>"x","c"=>"z")
    dict_y = Dict("t"=>"y","c"=>"z")
    dict_z = Dict("t"=>"z","c"=>"w")
    @test walk!([dict_x],action, "", Dict()) == [dict_y]
    @test walk!([dict_x,dict_y,dict_z],action) == [dict_y,dict_y,dict_z]
    @test walk!(Dict("t"=>"w","c"=>[dict_x]),action) == Dict("t"=>"w","c"=>[dict_y])
    @test walk!([dict_z,Dict("t"=>"w","c"=>[dict_x])],action) == [dict_z,Dict("t"=>"w","c"=>[dict_y])]
end

@testset "Testing Pandoc elements" begin
  @test Plain("Plain text") == Dict("t"=>"Plain","c"=>"Plain text")
  @test Null() == Dict("t"=>"Null")
  @test Code(["fun";Any[[],[]]],"1+1") ==  Dict("t"=>"Code","c"=>Any[["fun"; Any[[],[]]],"1+1"])
end

@testset "Testing walk with string replacement" begin
  action(t, c, format, meta) = (t=="Str") ? Dict("t"=>"Str","c"=>"This string was $c") : nothing
  @test walk!([Str("abc"),Code("xy", "ab")], action) == [Str("This string was abc"), Code("xy", "ab")]
end


text:
module JSON

__init__() = println("Haha, gotcha!")

end

max_stars_repo_name: StefanKarpinski/Nefarious

max_issues_repo_name: StefanKarpinski/Nefarious

max_forks_repo_name: StefanKarpinski/Nefarious


text:
using Weave

nkwds = (out_path = "notebooks/", jupyter_path = "$(homedir())/.julia/conda/3/bin/jupyter", nbconvert_options = "--allow-errors")
skwds = (out_path = "sheets/", jupyter_path = "$(homedir())/.julia/conda/3/bin/jupyter", nbconvert_options = "--allow-errors")

##
# notes
##

notebook("src/Julia.jmd"; nkwds...)
notebook("src/Asymptotics.jmd"; nkwds...)
notebook("src/SpectralTheorem.jmd"; nkwds...)

notebook("src/Numbers.jmd"; nkwds...)
notebook("src/Differentiation.jmd"; nkwds...)

notebook("src/StructuredMatrices.jmd"; nkwds...)
notebook("src/Decompositions.jmd"; nkwds...)
notebook("src/SingularValues.jmd"; nkwds...)
notebook("src/DifferentialEquations.jmd"; nkwds...)

notebook("src/Fourier.jmd"; nkwds...)
notebook("src/OrthogonalPolynomials.jmd"; nkwds...)
notebook("src/Quadrature.jmd"; nkwds...)
notebook("src/Applications.jmd"; nkwds...)

##
# problem sheets
##

notebook("src/week1.jmd"; skwds...)
notebook("src/week2.jmd"; skwds...)
notebook("src/week4.jmd"; skwds...)
notebook("src/week5.jmd"; skwds...)
notebook("src/advanced1.jmd"; skwds...)
notebook("src/advanced2.jmd"; skwds...)
notebook("src/advanced3.jmd"; skwds...)

##
# solutions
###

notebook("src/week1s.jmd"; skwds...)
notebook("src/week2s.jmd"; skwds...)
notebook("src/week3s.jmd"; skwds...)
notebook("src/week4s.jmd"; skwds...)
notebook("src/week5s.jmd"; skwds...)
notebook("src/week6s.jmd"; skwds...)
notebook("src/week7s.jmd"; skwds...)
notebook("src/week8s.jmd"; skwds...)

##
# exams
##

notebook("src/practice.jmd"; skwds...)
notebook("src/practices.jmd"; skwds...)

##
# extras
##

notebook("src/juliasheet.jmd"; skwds...)


text:
function smoothing_factor(t_e::R, cutoff::R) where R <: Real
    r = 2 * π * cutoff * t_e
    r / (r + 1)
end

function exponential_smoothing(a::R, x::R, x_prev::R) where R <: Real
    a * x + (1 - a) * x_prev
end

function one_euro_filter(t, x, t_prev, x_prev, dx_prev, min_cutoff, beta, d_cutoff)
    # Time difference
    t_e = t - t_prev

    # The filtered derivative of the signal.
    a_d = smoothing_factor(t_e, d_cutoff)
    dx = @. (x - x_prev) / t_e
    dx_hat = exponential_smoothing.(a_d, dx, dx_prev)

    # The filtered signal.
    cutoff = @. min_cutoff + beta * abs(dx_hat)
    a = smoothing_factor.(t_e, cutoff)
    x_hat = exponential_smoothing.(a, x, x_prev)

    return t, x_hat, dx_hat
end

function one_euro_filter(t::R, x::R, t_prev::R, x_prev::R, dx_prev::R; min_cutoff::R = R(1), beta::R = R(0), d_cutoff::R = R(1)) where R <: Real
    one_euro_filter(t, x, t_prev, x_prev, dx_prev, min_cutoff, beta, d_cutoff)
end

function one_euro_filter(t::R, x::R, t_prev::R, x_prev::R; min_cutoff::R = R(1), beta::R = R(0), d_cutoff::R = R(1)) where R <: Real
    one_euro_filter(t, x, t_prev, x_prev, R(0), min_cutoff, beta, d_cutoff)
end

function one_euro_filter(t::R, x::A, t_prev::R, x_prev::A, dx_prev::A; min_cutoff::R = R(1), beta::R = R(0), d_cutoff::R = R(1)) where A <: AbstractVector{R} where R <: Real
    one_euro_filter(t, x, t_prev, x_prev, dx_prev, min_cutoff, beta, d_cutoff)
end

function one_euro_filter(t::R, x::A, t_prev::R, x_prev::A; min_cutoff::R = R(1), beta::R = R(0), d_cutoff::R = R(1)) where A <: AbstractVector{R} where R <: Real
    one_euro_filter(t, x, t_prev, x_prev, zeros(R, length(x)), min_cutoff, beta, d_cutoff)
end

max_stars_repo_name: jaantollander/OneEuroFilter

max_issues_repo_name: jaantollander/OneEuroFilter

max_forks_repo_name: jaantollander/OneEuroFilter


text:
"""
    TV[ elements ]
    TV{T}[ elements ]

Create `Values` literals using array construction syntax. The element type is
inferred by promoting `elements` to a common type or set to `T` when `T` is
provided explicitly.

# Examples:

* `TV[1.0, 2.0]` creates a length-2 `Values` of `Float64` elements.
* `TV{Float32}[1, 2]` creates a length-2 `Values` of `Float32` elements.

A couple of helpful type aliases are also provided:

* `TV_F64[1, 2]` creates a lenght-2 `Values` of `Float64` elements
* `TV_F32[1, 2]` creates a lenght-2 `Values` of `Float32` elements
"""
struct TV{T} ; end

const TV_F32 = TV{Float32}
const TV_F64 = TV{Float64}

@inline similar_type(::Type{TV}, ::Val{S}) where {S} = Values{S}
@inline similar_type(::Type{TV{T}}, ::Val{S}) where {T,S} = Values{S,T}

# These definitions are duplicated to avoid matching `sa === Union{}` in the
# neater-looking alternative `sa::Type{<:TV}`.
@inline Base.getindex(sa::Type{TV}, xs...)            = similar_type(sa, Val(length(xs)))(xs)
@inline Base.getindex(sa::Type{TV{T}}, xs...) where T = similar_type(sa, Val(length(xs)))(xs)

@inline Base.typed_vcat(sa::Type{TV}, xs::Number...)            = similar_type(sa, Val(length(xs)))(xs)
@inline Base.typed_vcat(sa::Type{TV{T}}, xs::Number...) where T = similar_type(sa, Val(length(xs)))(xs)

#=@inline Base.typed_hcat(sa::Type{TV}, xs::Number...)            = similar_type(sa, Val(length(xs)))(xs)
@inline Base.typed_hcat(sa::Type{TV{T}}, xs::Number...) where T = similar_type(sa, Val(length(xs)))(xs)

Base.@pure function _TV_hvcat_transposed_size(rows)
    M = rows[1]
    if any(r->r != M, rows)
        # @pure may not throw... probably. See
        # https://discourse.julialang.org/t/can-pure-functions-throw-an-error/18459
        return nothing
    end
    Val(length(rows))
end

@inline function _TV_typed_hvcat(sa, rows, xs)
    msize = _TV_hvcat_transposed_size(rows)
    if msize === nothing
        throw(ArgumentError("TV[...] matrix rows of length $rows are inconsistent"))
    end
    # hvcat lowering is row major ordering, so we must transpose
    transpose(similar_type(sa, msize)(xs))
end

@inline Base.typed_hvcat(sa::Type{TV}, rows::Dims, xs::Number...)            = _TV_typed_hvcat(sa, rows, xs)
@inline Base.typed_hvcat(sa::Type{TV{T}}, rows::Dims, xs::Number...) where T = _TV_typed_hvcat(sa, rows, xs)
=#


text:
module pulse_defs

using DelimitedFiles:readdlm
export pulse, pi_pulse, pi_half_pulse, delay, optimal_pulse, PulseSequence, nmr_pulse,
array_pulse

# everything is a subttype of Pulse
abstract type pulse end

# struct containing the data for a pi pulse
struct pi_pulse{T<:AbstractFloat} <: pulse
	amplitude::T
	duration::T
	phase::T

	function pi_pulse(amp::T, ph::T) where T<: AbstractFloat
		new{T}(amp, pi/amp, deg2rad(ph))
	end
end

struct pi_half_pulse{T<:AbstractFloat} <: pulse
	amplitude::T
	duration::T
	phase::T

	function pi_half_pulse(amp::T, ph::T) where T<:AbstractFloat
		new{T}(amp, pi/amp/2, deg2rad(ph))
	end
end

struct delay{T<:AbstractFloat} <: pulse
	amplitude::T
	duration::T
	phase::T

	function delay(dur::T) where T<:AbstractFloat
		new{T}(0.0, dur, 0.0)
	end
end

struct nmr_pulse{T<:AbstractFloat} <: pulse
	amplitude::T
	duration::T
	phase::T
	function nmr_pulse(amp::T, dur::T, ph::T) where T <: AbstractFloat
		new{T}(amp, dur, ph)
	end
end

# object that stores the data for a shaped pulse
struct optimal_pulse{S<:String, T<:AbstractFloat} <: pulse
	filename::S
	amplitude::Array{T,1}
	duration::T
	phase::Array{T,1}
	time::Array{T,1} # we need time to be linear here

	function optimal_pulse(filename::String, duration::AbstractFloat)
		f = open(filename, "r")
		m = readdlm(f, ' ')
		fake_time = collect(range(0.0, 1.0, length=length(m[:,2]))) * duration
		new{String, AbstractFloat}(filename, m[:,2] * 2.0 * pi, duration, m[:,3], fake_time)
	end

end

# a pulse with an analytical formula for phase + amplitude (or just an array for each)
struct array_pulse{T <: AbstractFloat} <: pulse
	amplitude::Array{T, 1}
	duration::T
	phase::Array{T, 1}
	time::Array{T, 1}

	function array_pulse(amp_arr::Array{T, 1}, duration::T, ph_arr::Array{T, 1}) where T <: AbstractFloat
		new{AbstractFloat}(amp_arr, duration, ph_arr, collect(range(0, duration, length = length(amp_arr))))
	end

	function array_pulse(amp_func, duration, ph_func, res::Integer)
		fake_time = range(0, 1, length = res) # fake time will be converted to the duration of the pulse
		new{AbstractFloat}(amp_func.(fake_time), duration, ph_func.(fake_time), fake_time .* duration)
	end
end

# stores a list of pulses but hopefully in a convenient way that speeds up simulations
struct PulseSequence{T<:Float64, P<:pulse}
	sequence::Array{P}
	rabi::T
	pulse_timings::Array{T, 1}
	cumulative_timings::Array{T, 1}
	total_duration::T

	function PulseSequence(seq::Array{pulse}, rab::Float64)
		pt = _get_pulse_timings(seq)
		new{Float64, pulse}(seq, rab, pt, cumsum(pt), sum(pt))
	end

	function _get_pulse_timings(seq)
		pt = []
		for (i, pulse) in enumerate(seq)
			append!(pt, pulse.duration)
		end
		return pt
	end
end

# needs to be reworked
function _amp_ph_t(c::PulseSequence, t::AbstractFloat)::Tuple{AbstractFloat,AbstractFloat}
	# it might be faster to just accurately type the return type of the slice?
	# I think the issue is that we aren't specifying the dimension of the view so we get typed with Any
	ind = searchsortedfirst(c.cumulative_timings, t)
	if ind > length(c.cumulative_timings)
		ind = length(c.cumulative_timings)
	end
	if ind >= 2
		# we take time from the beginning of the pulse
		t = t - c.cumulative_timings[ind - 1]
	end
	return c.sequence[ind](t)
end

function _amp_ph_t(c::Union{optimal_pulse, array_pulse}, t::AbstractFloat)::Tuple{AbstractFloat, AbstractFloat}
	(find_val_in_array(c.amplitude, t, c.duration), find_val_in_array(c.phase, t, c.duration))
end

function _amp_ph_t(c::pulse, t::AbstractFloat)::Tuple{AbstractFloat, AbstractFloat}
	(c.amplitude, c.phase)
end

# needs to be reworked
function find_val_in_array(array, t, t_stop)
	i = find_index_in_array(array, t, t_stop)
	return array[i]
end

function find_index_in_array(array, t, t_stop)
	i = Integer(floor(t/t_stop * length(array)))
    if i > length(array)
        return length(array)
    elseif i == 0
        return 1
    end
	return i
end

# lord forgive me for the things I do
(c::PulseSequence)(b::Float64) = _amp_ph_t(c, b)
(c::pi_pulse)(b::Float64) = _amp_ph_t(c, b)
(c::pi_half_pulse)(b::Float64) = _amp_ph_t(c, b)
(c::optimal_pulse)(b::Float64) = _amp_ph_t(c, b)
(c::array_pulse)(b::Float64) = _amp_ph_t(c, b)
(c::delay)(b::Float64) = _amp_ph_t(c, b)

end


text:
# `julia build_tarballs.jl --help` to see a usage message.
using BinaryBuilder, Pkg

name = "startin"
version = v"0.5.2"

sources = [
    GitSource(
        "https://github.com/hugoledoux/startin.git",
        "88ad5557cbd954ec8996f99d9afb74fd1ec174ec"
    )
]

script = raw"""
cd $WORKSPACE/srcdir/startin/
cargo build --features c_api --release -j${nproc}
mkdir ${libdir}
if [[ "${target}" == *-w64-mingw32* ]]; then
    # Windows generates .dlls without the lib prefix
    cp target/${rust_target}/release/startin.dll ${libdir}/libstartin.dll
else
    cp target/${rust_target}/release/libstartin.${dlext} ${libdir}/libstartin.${dlext}
fi
"""

# musl platforms are failing, as is win32
platforms = supported_platforms(; experimental=true)
# `cdylib` apparently doesn't support musl
filter!(p -> libc(p) != "musl", platforms)
# Our Rust toolchain for i686 Windows is unusable
filter!(p -> !Sys.iswindows(p) || arch(p) != "i686", platforms)

products = [
    LibraryProduct("libstartin", :libstartin),
]

dependencies = Dependency[]

build_tarballs(ARGS, name, version, sources, script, platforms, products, dependencies; compilers=[:c, :rust], julia_compat="1.6")

max_stars_repo_name: giordano/Yggdrasil

max_issues_repo_name: giordano/Yggdrasil

max_forks_repo_name: giordano/Yggdrasil


text:
#using Gadfly
using PyPlot
f1 = open("time1")
f2 = open("time2")
f3 = open("time3")
f4 = open("time4")
a = Float64[]
b = Float64[]
c = Float64[]
d = Float64[]
for ln in eachline(f1)
    n = parse(Float64, ln)
    push!(a, n)
end
for ln in eachline(f2)
    n = parse(Float64, ln)
    push!(b, n)
end
for ln in eachline(f3)
    n = parse(Float64, ln)
    push!(c, n)
end
for ln in eachline(f4)
    n = parse(Float64, ln)
    push!(d, n)
end
#plot(a)
#plot(b)
plot(c)
plot(d)
show()

max_stars_repo_name: frostRed/Exercises

max_issues_repo_name: frostRed/Exercises

max_forks_repo_name: frostRed/Exercises


text:
module ElectronDisplay

export electrondisplay

using Electron, Base64, Markdown

import IteratorInterfaceExtensions, TableTraits, TableShowUtils

struct ElectronDisplayType <: Base.AbstractDisplay end

electron_showable(m, x) =
    m ∉ ("application/vnd.dataresource+json", "text/html", "text/markdown") &&
    showable(m, x)

mutable struct ElectronDisplayConfig
    showable
    single_window::Bool
    focus::Bool
end

"""
    ElectronDisplay.CONFIG

Configuration for ElectronDisplay.

* `showable`: A callable with signature `showable(mime::String,
  x::Any) :: Bool`.  This determines if object `x` is displayed by
  `ElectronDisplay`.  Default is to return `false` if `mime` is
  `"text/html"` or `"text/markdown"` and otherwise fallbacks to
  `Base.showable(mime, x)`.

* `single_window::Bool = false`: If `true`, reuse existing window for
  displaying a new content.  If `false` (default), create a new window
  for each display.

* `focus::Bool = true`: Focus the Electron window on `display` if `true`
  (default).
"""
const CONFIG = ElectronDisplayConfig(electron_showable, false, true)

const _window = Ref{Window}()

function _getglobalwindow()
    if !(isdefined(_window, 1) && _window[].exists)
        _window[] = Electron.Window(
            URI("about:blank"),
            options=Dict("webPreferences" => Dict("webSecurity" => false)))
    end
    return _window[]
end

function displayhtml(payload; options::Dict=Dict{String,Any}())
    if CONFIG.single_window
        w = _getglobalwindow()
        load(w, payload)
        showfun = get(options, "show", CONFIG.focus) ? "show" : "showInactive"
        run(w.app, "BrowserWindow.fromId($(w.id)).$showfun()")
        return w
    else
        options = Dict{String,Any}(options)
        get!(options, "show", CONFIG.focus)
        return Electron.Window(payload; options=options)
    end
end

displayhtmlbody(payload) =
    displayhtml(string(
        """
        <!doctype html>

        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="file:///$(asset("github-markdown-css", "github-markdown.css"))">

        """,
        payload,
        """

        """,
    ))

function Base.display(d::ElectronDisplayType, ::MIME{Symbol("text/html")}, x)
    html_page = repr("text/html", x)
    if occursin(r"<html\b"i, html_page)
        # Detect if object `x` rendered itself as a "standalone" HTML page.
        # If so, display it as-is:
        displayhtml(html_page)
    else
        # Otherwise, i.e., if `x` only produced an HTML fragment, apply
        # our default CSS to it:
        displayhtmlbody(html_page)
    end
end

Base.displayable(d::ElectronDisplayType, ::MIME{Symbol("text/html")}) = true

Base.display(d::ElectronDisplayType, ::MIME{Symbol("text/markdown")}, x) =
    displayhtmlbody(repr("text/html", asmarkdown(x)))

asmarkdown(x::Markdown.MD) = x
asmarkdown(x) = Markdown.parse(repr("text/markdown", x))

Base.displayable(d::ElectronDisplayType, ::MIME{Symbol("text/markdown")}) = true

function Base.display(d::ElectronDisplayType, ::MIME{Symbol("image/png")}, x)
    img = stringmime(MIME("image/png"), x)

    payload = string("")

    displayhtml(payload)
end

Base.displayable(d::ElectronDisplayType, ::MIME{Symbol("image/png")}) = true

function Base.display(d::ElectronDisplayType, ::MIME{Symbol("image/svg+xml")}, x)
    payload = stringmime(MIME("image/svg+xml"), x)

    displayhtml(payload)
end

Base.displayable(d::ElectronDisplayType, ::MIME{Symbol("image/svg+xml")}) = true

asset(url...) = replace(normpath(joinpath(@__DIR__, "..", "assets", url...)), "\\" => "/")

function Base.display(d::ElectronDisplayType, ::MIME{Symbol("application/vnd.vegalite.v2+json")}, x)
    payload = stringmime(MIME("application/vnd.vegalite.v2+json"), x)

    html_page = """

    """

    displayhtml(html_page, options=Dict("webPreferences" => Dict("webSecurity" => false)))
end

Base.displayable(d::ElectronDisplayType, ::MIME{Symbol("application/vnd.vegalite.v2+json")}) = true

function Base.display(d::ElectronDisplayType, ::MIME{Symbol("application/vnd.vega.v3+json")}, x)
    payload = stringmime(MIME("application/vnd.vega.v3+json"), x)

    html_page = """

    """

    displayhtml(html_page, options=Dict("webPreferences" => Dict("webSecurity" => false)))
end

Base.displayable(d::ElectronDisplayType, ::MIME{Symbol("application/vnd.vega.v3+json")}) = true

function Base.display(d::ElectronDisplayType, ::MIME{Symbol("application/vnd.plotly.v1+json")}, x)
    payload = stringmime(MIME("application/vnd.plotly.v1+json"), x)

    html_page = """

    """

    displayhtml(html_page, options=Dict("webPreferences" => Dict("webSecurity" => false)))
end

Base.displayable(d::ElectronDisplayType, ::MIME{Symbol("application/vnd.plotly.v1+json")}) = true

function Base.display(d::ElectronDisplayType, ::MIME{Symbol("application/vnd.dataresource+json")}, x)
    payload = stringmime(MIME("application/vnd.dataresource+json"), x)

    html_page = """

        <link rel="stylesheet" href="file://$(asset("ag-grid", "ag-grid.css"))">
        <link rel="stylesheet" href="file://$(asset("ag-grid", "ag-theme-balham.css"))">

    """

    displayhtml(html_page, options=Dict("webPreferences" => Dict("webSecurity" => false)))
end

Base.displayable(d::ElectronDisplayType, ::MIME{Symbol("application/vnd.dataresource+json")}) = true

function Base.display(d::ElectronDisplayType, x)
    _display(CONFIG.showable, x)
end

function _display(showable, x)
    d = ElectronDisplayType()
    if showable("application/vnd.vegalite.v2+json", x)
        display(d,MIME("application/vnd.vegalite.v2+json"), x)
    elseif showable("application/vnd.vega.v3+json", x)
            display(d,MIME("application/vnd.vega.v3+json"), x)
    elseif showable("application/vnd.plotly.v1+json", x)
            display(d,MIME("application/vnd.plotly.v1+json"), x)
    elseif showable("application/vnd.dataresource+json", x)
        display(d, "application/vnd.dataresource+json", x)
    elseif showable("image/svg+xml", x)
        display(d,"image/svg+xml", x)
    elseif showable("image/png", x)
        display(d,"image/png", x)
    elseif showable("text/html", x)
        display(d, "text/html", x)
    elseif showable("text/markdown", x)
        display(d, "text/markdown", x)
    else
        throw(MethodError(Base.display,(d,x)))
    end
end

"""
    electrondisplay([mime,] x)

Show `x` in Electron window.  Use MIME `mime` if specified.
"""
electrondisplay(mime, x) = display(ElectronDisplayType(), mime, x)

struct DataresourceTableTraitsWrapper{T}
    source::T
end

function Base.show(io::IO, ::MIME"application/vnd.dataresource+json", source::DataresourceTableTraitsWrapper)
    TableShowUtils.printdataresource(io, IteratorInterfaceExtensions.getiterator(source.source))
end

Base.showable(::MIME"application/vnd.dataresource+json", dt::DataresourceTableTraitsWrapper) = true

struct CachedDataResourceString
    content::String
end

Base.show(io::IO, ::MIME"application/vnd.dataresource+json", source::CachedDataResourceString) = print(io, source.content)

Base.showable(::MIME"application/vnd.dataresource+json", dt::CachedDataResourceString) = true

function electrondisplay(x)
    if TableTraits.isiterabletable(x)!==false
        if showable("application/vnd.dataresource+json", x)
            _display(showable, x)
        elseif TableTraits.isiterabletable(x)===true
            _display(showable, DataresourceTableTraitsWrapper(x))
        else
            try
                buffer = IOBuffer()
                TableShowUtils.printdataresource(buffer, IteratorInterfaceExtensions.getiterator(x))

                buffer_asstring = CachedDataResourceString(String(take!(buffer)))
                _display(showable, buffer_asstring)
            catch err
                _display(showable, x)
            end
        end
    else
        _display(showable, x)
    end
end

function __init__()
    Base.Multimedia.pushdisplay(ElectronDisplayType())
end

end # module


text:
export Ray

## Standard interval

# angle is (false==0) and π (true==1)
# or ranges from (-1,1].  We use 1 as 1==true.
#orientation true means oriented out
"""
    Ray{a}(c,o)

represents a ray at angle `a` starting at `c`, with orientation out to
infinity (`o = true`) or back from infinity (`o = false`).
"""
struct Ray{angle,T<:Number} <: SegmentDomain{T}
    center::T
    orientation::Bool
    Ray{angle,T}(c,o) where {angle,T} = new{angle,T}(c,o)
    Ray{angle,T}(c) where {angle,T} = new{angle,T}(c,true)
    Ray{angle,T}() where {angle,T} = new{angle,T}(zero(T),true)
    Ray{angle,T}(r::Ray{angle,T}) where {angle,T} = r
end

const RealRay{T} = Union{Ray{false,T},Ray{true,T}}

Ray{a}(c,o) where {a} = Ray{a,typeof(c)}(c,o)
Ray{a}(c::Number) where {a} = Ray{a,typeof(c)}(c)
Ray{a}() where {a} = Ray{a,Float64}()

angle(d::Ray{a}) where {a} = a*π

# ensure the angle is always in (-1,1]
Ray(c,a,o) = Ray{a==0 ? false : (abs(a)≈(1.0π) ? true : mod(a/π-1,-2)+1),typeof(c)}(c,o)
Ray(c,a) = Ray(c,a,true)

Ray() = Ray{false}()

##deal with vector

function convert(::Type{Ray}, d::AbstractInterval)
    a,b = endpoints(d)
    @assert abs(a)==Inf || abs(b)==Inf

    if abs(b)==Inf
        Ray(a,angle(b),true)
    else #abs(a)==Inf
        Ray(b,angle(a),false)
    end
end
Ray(d::AbstractInterval) = convert(Ray, d)

isambiguous(d::Ray)=isnan(d.center)
convert(::Type{Ray{a,T}},::AnyDomain) where {a,T<:Number} = Ray{a,T}(NaN,true)
convert(::Type{IT},::AnyDomain) where {IT<:Ray} = Ray(NaN,NaN)

isempty(::Ray) = false

## Map interval

function mobiuspars(d::Ray)
    s=(d.orientation ? 1 : -1)
    α=conj(cisangle(d))
    c=d.center
    s*α,-s*(1+α*c),α,1-α*c
end

for OP in (:mobius,:mobiusinv,:mobiusD,:mobiusinvD)
    @eval $OP(a::Ray,z) = $OP(mobiuspars(a)...,z)
end

ray_tocanonical(x) = isinf(x) ? one(x) : (x-1)/(1+x)
ray_tocanonicalD(x) = isinf(x) ? zero(x) : 2*(1/(1+x))^2
ray_fromcanonical(x) = (1+x)/(1-x)
ray_fromcanonicalD(x) = 2*(1/(x-1))^2
ray_invfromcanonicalD(x) = (x-1)^2/2

for op in (:ray_tocanonical,:ray_tocanonicalD)
    @eval $op(o,x)=(o ? 1 : -1)*$op(x)
end
ray_fromcanonical(o,x)=ray_fromcanonical((o ? 1 : -1)*x)
ray_fromcanonicalD(o,x)=(o ? 1 : -1)*ray_fromcanonicalD((o ? 1 : -1)*x)
ray_invfromcanonicalD(o,x)=(o ? 1 : -1)*ray_invfromcanonicalD((o ? 1 : -1)*x)

cisangle(::Ray{a}) where {a}=cis(a*π)
cisangle(::Ray{false})=1
cisangle(::Ray{true})=-1

tocanonical(d::Ray,x) =
    ray_tocanonical(d.orientation,conj(cisangle(d)).*(x-d.center))
tocanonicalD(d::Ray,x) =
    conj(cisangle(d)).*ray_tocanonicalD(d.orientation,conj(cisangle(d)).*(x-d.center))
fromcanonical(d::Ray,x) = cisangle(d)*ray_fromcanonical(d.orientation,x)+d.center
fromcanonical(d::Ray{false},x) = ray_fromcanonical(d.orientation,x)+d.center
fromcanonical(d::Ray{true},x) = -ray_fromcanonical(d.orientation,x)+d.center
fromcanonicalD(d::Ray,x) = cisangle(d)*ray_fromcanonicalD(d.orientation,x)
invfromcanonicalD(d::Ray,x) = conj(cisangle(d))*ray_invfromcanonicalD(d.orientation,x)

arclength(d::Ray) = Inf

==(d::Ray{a},m::Ray{a}) where {a} = d.center == m.center

mappoint(a::Ray{false}, b::Ray{false}, x::Number) =
    x - a.center + b.center

function mappoint(a::Ray, b::Ray, x::Number)
    d = x - a.center;
    k = d * exp((angle(b)-angle(d))*im)
    k + b.center
end


text:
"""
Run until a single particle has been accepted
"""
function find_particle(summaryStatistics::Any,
                                  threshold::G,
                                  sample_prior::Function,
                                  forward_model::Function,
                                  compute_distance::Function) where G <: Real
    sampled = 0
    while true
        sampled += 1

        #Draw sample and simulate data
        proposal = sample_prior()
        simulatedData = forward_model(proposal)
        proposalDistance = compute_distance(simulatedData, summaryStatistics)

        #Retain sample is distance is below threshold
        if proposalDistance < threshold
            return proposal, proposalDistance, sampled
        end
    end
end

function find_particle(summaryStatistics::Any,
                                  threshold::Array{G, 1},
                                  sample_prior::Function,
                                  forward_model::Function,
                                  compute_distance::Function) where G <: Real
    sampled = 0
    while true
        sampled += 1

        #Draw sample and simulate data
        proposal = sample_prior()
        simulatedData = forward_model(proposal)
        proposalDistance = compute_distance(simulatedData, summaryStatistics)

        #Retain sample is distance is below threshold
        if all(proposalDistance .< threshold)
            return proposal, proposalDistance, sampled
        end
    end
end

"""
Standard ABC algorithm for univariate parameter of interest
"""
function pabc_standard1D(T::Type, summaryStatistics::Any,
                                     N::Int64,
                                     threshold::G,
                                     sample_prior::Function,
                                     forward_model::Function,
                                     compute_distance::Function) where G <: Real
    #Allocate variables
    acceptedDraws = Array{T}(N)
    acceptedDistances = Array{G}(N)
    accepted = 1
    nsampled = zeros(Int64, N)

    #Repeat sampling until N particles accepted
    np = nprocs()
    @sync begin
        for proc = 1:np
            if proc != myid() || np == 1
                @async begin
                    while accepted < N
                        acceptedDraws[accepted], acceptedDistances[accepted], nsampled[accepted] = remotecall_fetch(find_particle, proc, summaryStatistics, threshold, sample_prior, forward_model, compute_distance)
                        accepted += 1
                    end
                end
            end
        end
    end

    #Return result
    return ABCResult(acceptedDraws, acceptedDistances, threshold, sum(nsampled))
end

function pabc_standard1D(T::Type, summaryStatistics::Any,
                                     N::Int64,
                                     threshold::Array{G, 1},
                                     sample_prior::Function,
                                     forward_model::Function,
                                     compute_distance::Function) where G <: Number

    #Allocate variables
    acceptedDraws = Array{T}(N)
    acceptedDistances = Array{G}(N, length(threshold))
    accepted = 0
    nsampled = zeros(Int64, N)

    #Repeat sampling until N particles accepted
    np = nprocs()
    @sync begin
        for proc = 1:np
            if proc != myid() || np == 1
                @async begin
                    while accepted < N
                        acceptedDraws[accepted], acceptedDistances[accepted, :], nsampled[accepted] = remotecall_fetch(find_particle, proc, summaryStatistics, threshold, sample_prior, forward_model, compute_distance)
                        accepted += 1
                    end
                end
            end
        end
    end
    #Return result
    return ABCResult(acceptedDraws, acceptedDistances, threshold, nsampled)
end

"""
Standard ABC algorithm for multivariate parameter of interest
"""
function pabc_standardMultiD(T::Type, summaryStatistics::Any,
                                         N::Int64,
                                         d::Int64,
                                         threshold::G,
                                         sample_prior::Function,
                                         forward_model::Function,
                                         compute_distance::Function) where G <: Number

    #Allocate variables
    acceptedDraws = Array{T}(N, d)
    acceptedDistances = Array{G}(N)
    accepted = 0
    nsampled = zeros(Int64, N)

    #Repeat sampling until N particles accepted
    np = nprocs()
    @sync begin
        for proc = 1:np
            if proc != myid() || np == 1
                @async begin
                    while accepted < N
                        acceptedDraws[accepted, :], acceptedDistances[accepted], nsampled[accepted] = remotecall_fetch(find_particle, proc, summaryStatistics, threshold, sample_prior, forward_model, compute_distance)
                        accepted += 1
                    end
                end
            end
        end
    end
    #Return result
    return ABCResult(acceptedDraws, acceptedDistances, threshold, nsampled)
end

function pabc_standardMultiD(T::Type, summaryStatistics::Any,
                                         N::Int64,
                                         d::Int64,
                                         threshold::Array{G, 1},
                                         sample_prior::Function,
                                         forward_model::Function,
                                         compute_distance::Function) where G <: Number
    acceptedDraws = Array{T}(N, d)
    acceptedDistances = Array{G}(N, length(threshold))
    accepted = 0
    nsampled = zeros(Int64, N)

    #Repeat sampling until N particles accepted
    np = nprocs()
    @sync begin
        for proc = 1:np
            if proc != myid() || np == 1
                @async begin
                    while accepted < N
                        acceptedDraws[accepted, :], acceptedDistances[accepted, :], nsampled[accepted] = remotecall_fetch(find_particle, proc, summaryStatistics, threshold, sample_prior, forward_model, compute_distance)
                        accepted += 1
                    end
                end
            end
        end
    end

    #Return result
    return ABCResult(acceptedDraws, acceptedDistances, threshold, nsampled)
end

"""
Standard ABC Algorithm, wrapper that determines dimention of algorithm to be called and runs appropriate version

# Arguments
* `summaryStatistics::Any` summary statistics of observed data used in
distance comparison.
* `N::Int64` Number of samples to accept before termination
* `threshold::Float64 or ::Array{Float64, 1}` acceptance threshold
* `sample_prior::Function` Function to draw a sample from the prior distribution from either a univariate or multivariate distribution called by `sample_prior()`.
* `forward_model::Function` Function to simulate data based on draw from parameter prior.  The call `forward_model(sample_prior())` should run.
* `compute_distance::Function` Function to compute distance between output of the `forward_model` and the provided `summaryStatistics`. The call `compute_distance(forward_model(sample_prior()), summaryStatistics)` should run.

# Value
Returns an object of type `ABCResult` containing the accepted particles, corresponding distances, acceptance threshold, and the number of samples drawn from the prior before the desired number of particles were accepted

# Examples
```julia
using ApproximateBayesianComputation

data = rand(Distributions.Normal(2.0, 0.5), 100)

#Construct Appropriate Functions
sample_prior = make_sample_prior(Distributions.Normal(0.0, 0.5))
function forward_model(μ::Float64)
    return rand(Distributions.Normal(μ, 0.5), 100)
end
function compute_distance1(x::Array{Float64, 1}, y::Float64)
    return abs(mean(x) - y)
end

result = abc_standard(mean(data), 200, 0.05, sample_prior, forward_model, compute_distance)
```
"""
function pabc_standard(summaryStatistics::Any,
                                  N::Int64,
                                  threshold::Union{G, Array{G, 1}},
                                  sample_prior::Function,
                                  forward_model::Function,
                                  compute_distance::Function) where G <: Real

    proposal = sample_prior()
    if typeof(proposal) <: Array
        return pabc_standardMultiD(eltype(proposal), summaryStatistics, N, length(proposal), threshold, sample_prior, forward_model, compute_distance)
    else
        return pabc_standard1D(typeof(proposal), summaryStatistics, N, threshold, sample_prior, forward_model, compute_distance)
    end
end


text:
using BenchmarkTools
using NumberTheoreticTransforms, FFTW

const x = mod.(rand(Int, 4096), 65537);
@btime fnt($x, $169, $65537);
@btime fft($x);

const x2 = mod.(rand(Int, 8192), 65537);
@btime fnt($x2, $225, $65537);
@btime fft($x2);


text:
@testset "@carray" begin
	CcharArray = @carray Cchar[2]
	@test sizeof(CcharArray) == sizeof(Cchar)*2

	CstructArray = @carray (@cstruct {
		i::Cint
	} __packed__)[10]
	@test sizeof(CstructArray) == sizeof(Cint)*10

	@cstruct CStruct {
		i::Cint
	} __packed__
	CStructArray = @carray CStruct[2]
	@test sizeof(CStructArray) == sizeof(Cint)*2

	@cstruct Opaque
	PtrArray = @carray Ptr{Opaque}[3]
	@test sizeof(PtrArray) == sizeof(Ptr)*3

	pa = PtrArray(undef)
	@test sizeof(pa) == sizeof(Ptr)*3
	@test length(pa) == 3
	@test eltype(pa) === Ptr{Opaque}
	@test pa[1] isa Ptr{Opaque}

	for i in eachindex(pa)
		pa[i] = C_NULL
		@test pa[i] == C_NULL
		pa[i] = Ptr{Opaque}(1)
		@test pa[i] != C_NULL
	end

	pa = PtrArray()
	for ptr in pa
		@test ptr == C_NULL
	end

	ca = CStructArray()
	@test length(ca) == 2
	@test eltype(ca) === CStruct
	@test ca[2] isa CBinding.Caccessor{CStruct}

	CarrayArray = @carray Cint[4][2]
	@test sizeof(CarrayArray) == sizeof(Cint)*4*2
	@test eltype(CarrayArray) === @carray Cint[4]
	@test eltype(eltype(CarrayArray)) === Cint

	ca = CarrayArray()
	@test length(ca) == 2
	@test length(ca[1]) == 4
	for i in eachindex(ca), j in eachindex(ca[i])
		@test ca[i] isa CBinding.Caccessor{@carray Cint[4]}
		@test ca[i][j] == 0
	end
end


text:
module TestNamespace

using Test
using Omega
using Callbacks: CbNode, idcb
using Lens
using Omega.Inference: Loop

function testcb()
  x = normal(0.0, 1.0)
  addz(data) = (println("in addz"); (z = 1.0,))
  testz(data) = (println("in testz"); @test haskey(data, :z))
  testnoz(data) = (println("in testz"); @test !haskey(data, :z))

  cb = CbNode(idcb, (CbNode(addz, (testz,)), testnoz))
  lenscall((Loop => cb,), rand, x, x >ₛ 0.0, 1, alg = HMCFAST)
end

testcb()

end


text:
# MIT License
#
# Copyright (c) 2018 Martin Biel
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

"""
    @scenario(args..., probability = )

Create [`Scenario`](@ref) matching some [`@uncertain`](@ref) declaration with a supplied probability.

    @scenario(var1 = val1, var2 = val2, ..., probability = 1.0)

Create [`Scenario`](@ref) matching [`@uncertain`](@ref) annotation of the form `@uncertain var1, var2, ...`

    @scenario(ξ[i=..., j=..., ...] = values, probability = 1.0)

Create [`Scenario`](@ref) matching [`@uncertain`](@ref) annotation of the form `@uncertain ξ[i=..., j=..., ...]`. `values` must have the same dimension as the specified index sets.

    @scenario(ξ[i=..., j=..., ...], expr, probability = 1.0, requested_container = :Auto)

Create [`Scenario`](@ref) matching [`@uncertain`](@ref) annotation of the form `@uncertain ξ[i=..., j=..., ...]`. Wraps JuMP's `@container` macro to create `DenseAxisArray` or `SparseAxisArray` as underlying data. See `@container` for further syntax information.

## Examples

The following are equivalent ways of creating an instance of the random vector ``[q₁(ξ) q₂(ξ) d₁(ξ) d₂(ξ)]``  of probability ``0.4`` and values ``[24.0 28.0 500.0 100.0]``.

```julia
@scenario q₁ = 24.0 q₂ = 28.0 d₁ = 500.0 d₂ = 100.0 probability = 0.4

@scenario ξ[i in 1:4] = [24.0, 28.0, 500.0, 100.0] probability = 0.4
```

"""
macro scenario(args...)
    args, kw_args, probability, requested_container = _extract_kw_args(args)
    if length(args) == 0
        if length(kw_args) > 1 || @capture(kw_args[1], var_Symbol = val_)
            return :(Scenario(; $(esc.(kw_args)...), probability = $(esc(probability))))
        else
            if @capture(kw_args[1], idx_ = val_)
                idxvars, indices = Containers._build_ref_sets(error, idx)
                values = @q begin
                    if $indices isa VectorizedProductIterator && all(idx -> idx isa Base.OneTo, $indices.prod.iterators)
                        $(esc(val))[$(esc.(idxvars)...)]
                    else
                        if $(esc(val)) isa Dict
                            $(esc(val))[($(esc.(idxvars)...),)]
                        elseif $(esc(val)) isa Array
                            zero(eltype($(esc(val))))
                        else
                            error("Unsupported right hand side in @scenario assignment.")
                        end
                    end
                end
                code = Containers.container_code(idxvars, indices, :($values), requested_container)
                return @q begin
                    ξ = Scenario($code; probability = $(esc(probability)))
                    if ξ.data isa Array
                        size(ξ.data) == size($(esc(val))) || error("Dimensions of right hand side in @scenario assignment differ from left hand side.")
                    elseif ξ.data isa DenseAxisArray
                        ξ.data.data .= $(esc(val))
                    elseif ξ.data isa SparseAxisArray
                        length(ξ.data.data) == length($(esc(val))) || error("Dimensions of right hand side in @scenario assignment differ from left hand side.")
                    end
                    ξ
                end
            end
        end
    end
    @assert length(args) == 2
    @assert isempty(kw_args)
    idx, values = args
    code = Containers.parse_container(error, idx, esc(values), requested_container)
    return :(Scenario($code; probability = $(esc(probability))))
end
function _extract_kw_args(args)
    kw_args = filter(x -> isexpr(x, :(=)) && x.args[1] != :container && x.args[1] != :probability, collect(args))
    flat_args = filter(x->!isexpr(x, :(=)), collect(args))
    requested_container = :Auto
    probability = 1.0
    for kw in args
        if isexpr(kw, :(=)) && kw.args[1] == :container
            requested_container = kw.args[2]
        end
        if isexpr(kw, :(=)) && kw.args[1] == :probability
            probability = kw.args[2]
        end
    end
    return flat_args, kw_args, probability, requested_container
end
"""
    @uncertain(def)

In a @stage block, annotate each uncertain variable using the syntax
```julia
@uncertain var1, var2, ...
```
or using JuMP's container syntax
```julia
@uncertain ξ[i=..., j=..., ...]
```
This assumes that the [`Scenario`] type is used. Matching scenario data is then conveniently created using [`@scenario`](@ref).

Alternatively, user-defined scenarios can be specified by annotating the type. Also, inside a @stochastic_model block, user-defined scenarios can be created during the @uncertain annotation, using [`@define_scenario`](@ref) syntax.

## Examples

The following are equivalent ways of declaring a random vector ``[q₁(ξ) q₂(ξ) d₁(ξ) d₂(ξ)]`` in a `@stage` block, and creating a matching scenario instance of probability ``0.4`` and values ``[24.0 28.0 500.0 100.0]``.ö

```julia
@uncertain q₁ q₂ d₁ d₂
ξ₁ = @scenario q₁ = 24.0 q₂ = 28.0 d₁ = 500.0 d₂ = 100.0 probability = 0.4

@uncertain ξ[i in 1:4]
ξ₁ = @scenario ξ[i in 1:4] = [24.0, 28.0, 500.0, 100.0] probability = 0.4

@define_scenario SimpleScenario = begin
    q₁::Float64
    q₂::Float64
    d₁::Float64
    d₂::Float64
end
@uncertain ξ::SimpleScenario
ξ₁ = SimpleScenario(24.0, 28.0, 500.0, 100.0, probability = 0.4)

@stochastic_model begin
    ...
    @uncertain ξ::SimpleScenario = begin
        q₁::Float64
        q₂::Float64
        d₁::Float64
        d₂::Float64
    end
    ...
end
ξ₁ = SimpleScenario(24.0, 28.0, 500.0, 100.0 probability = 0.4)
```

See also [`@scenario`](@ref), [`@define_scenario`](@ref), [`@parameters`](@ref), [`@decision`](@ref), [`@stage`](@ref)
"""
macro uncertain(def) @warn "@uncertain should be used inside a @stage block." end


text:
mutable struct SendOptions
  blocking::Bool
  isSSL::Bool
  username::String
  passwd::String

  SendOptions(; blocking::Bool = true, isSSL::Bool = false,
              username::AbstractString = "", passwd::AbstractString = "") =
  new(blocking, isSSL, String(username), String(passwd))
end

mutable struct SendResponse
  body::IO
  code::Int
  total_time::Float64

  SendResponse() = new(IOBuffer(), 0, 0.0)
end

function Base.show(io::IO, o::SendResponse)
  println(io, "Return Code: ", o.code)
  println(io, "Time:        ", o.total_time)
  print(io,   "Response:    ", String(take!(o.body)))
end

mutable struct ReadData
  typ::Symbol
  src::Any
  str::AbstractString
  offset::Csize_t
  sz::Csize_t

  ReadData() = new(:undefined, false, "", 0, 0)
end

mutable struct ConnContext
  curl::Ptr{CURL}
  url::String
  rd::ReadData
  resp::SendResponse
  options::SendOptions
  close_ostream::Bool
  bytes_recd::Int

  ConnContext(options::SendOptions) =
  new(C_NULL, " ", ReadData(), SendResponse(), options, false, 0)
end


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

mutable struct ApplicationGatewayTrustedRootCertificatePropertiesFormat <: SwaggerModel
    data::Any # spec type: Union{ Nothing, String } # spec name: data
    keyVaultSecretId::Any # spec type: Union{ Nothing, String } # spec name: keyVaultSecretId
    provisioningState::Any # spec type: Union{ Nothing, ProvisioningState } # spec name: provisioningState

    function ApplicationGatewayTrustedRootCertificatePropertiesFormat(;data=nothing, keyVaultSecretId=nothing, provisioningState=nothing)
        o = new()
        validate_property(ApplicationGatewayTrustedRootCertificatePropertiesFormat, Symbol("data"), data)
        setfield!(o, Symbol("data"), data)
        validate_property(ApplicationGatewayTrustedRootCertificatePropertiesFormat, Symbol("keyVaultSecretId"), keyVaultSecretId)
        setfield!(o, Symbol("keyVaultSecretId"), keyVaultSecretId)
        validate_property(ApplicationGatewayTrustedRootCertificatePropertiesFormat, Symbol("provisioningState"), provisioningState)
        setfield!(o, Symbol("provisioningState"), provisioningState)
        o
    end
end # type ApplicationGatewayTrustedRootCertificatePropertiesFormat

const _property_map_ApplicationGatewayTrustedRootCertificatePropertiesFormat = Dict{Symbol,Symbol}(Symbol("data")=>Symbol("data"), Symbol("keyVaultSecretId")=>Symbol("keyVaultSecretId"), Symbol("provisioningState")=>Symbol("provisioningState"))
const _property_types_ApplicationGatewayTrustedRootCertificatePropertiesFormat = Dict{Symbol,String}(Symbol("data")=>"String", Symbol("keyVaultSecretId")=>"String", Symbol("provisioningState")=>"ProvisioningState")
Base.propertynames(::Type{ ApplicationGatewayTrustedRootCertificatePropertiesFormat }) = collect(keys(_property_map_ApplicationGatewayTrustedRootCertificatePropertiesFormat))
Swagger.property_type(::Type{ ApplicationGatewayTrustedRootCertificatePropertiesFormat }, name::Symbol) = Union{Nothing,eval(Base.Meta.parse(_property_types_ApplicationGatewayTrustedRootCertificatePropertiesFormat[name]))}
Swagger.field_name(::Type{ ApplicationGatewayTrustedRootCertificatePropertiesFormat }, property_name::Symbol) =  _property_map_ApplicationGatewayTrustedRootCertificatePropertiesFormat[property_name]

function check_required(o::ApplicationGatewayTrustedRootCertificatePropertiesFormat)
    true
end

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


text:
abstract type AbstractTaxonomy end
abstract type AbstractClassificationTree end
abstract type AbstractRank end
abstract type AbstractTaxon end

"""
    TaxonomicRank

    A string describing the name of a rank of a taxonomy (e.g. Domain, Family, Genus),
    and the corresponding depth of that rank in the taxonomy.
"""
struct TaxonomicRank
    name::Symbol
    taxonomydepth::Int
end

struct NCBITaxonWrapper <: AbstractTaxon
    val::NCBITaxon
end


text:
## Example of how to parse mustache template to insert
## graphic. This could be part of mustache bit
## wish there were a way to *easily* get markup in the text buffer...
using Mustache, Gtk, Winston

tpl = mt"""
This is a mustache
template bold
complete with lots of stuff
what is --> {{x}} <--?
and
{{p}}
and whatever
"""

x = "this is x"
p = plot(sin, 0, 2pi);

## show tpl
w = window()
tv = textedit(w); push!(w, tv)

function add_tpl(tpl)
    ## how to show a mustache template
    for (t, l, b, e) in tpl.tokens
        if t == "text"
            push!(tv, l)
        else ## if type == "name"
            ## look up and render accordingly
            obj = Main.(symbol(l))
            if isa(obj, Winston.FramedPlot)
                c = cairographic(w)
                display(c, obj)
                push!(tv, c)
            else
                push!(tv, string(obj))
            end
        end
    end
end


text:
import LinearMaps

struct ZeroMap{T,U,V} <: LinearMap{T}
    range::U
    domain::V
end

ZeroMap{T}(range::U, domain::V) where {T,U,V} = ZeroMap{T,U,V}(range, domain)
LinearMaps.MulStyle(A::ZeroMap) = LinearMaps.FiveArg()

Base.size(A::ZeroMap) = (length(A.range), length(A.domain),)
Base.axes(A::ZeroMap) = (A.range, A.domain)

function LinearAlgebra.mul!(y::AbstractVector, L::ZeroMap, x::AbstractVector,
    α::Number, β::Number)

    y .*= β
end

function LinearAlgebra.mul!(Y::PseudoBlockMatrix, c::Number, X::ZeroMap, a::Number, b::Number)
    @assert b == 1
    return Y
end

# function LinearAlgebra.mul!(y::AbstractVector,
#     Lt::LinearMaps.TransposeMap{<:Any,<:ZeroMap},
#     x::AbstractVector, α::Number, β::Number)

#     y .*= β
# end

function LinearAlgebra.mul!(y::AbstractVector, L::ZeroMap, x::AbstractVector)
    y .= 0
end

# function LinearAlgebra.mul!(y::AbstractVector,
#     Lt::LinearMaps.TransposeMap{<:Any,<:ZeroMap}, x::AbstractVector)

#     y .= 0
# end

LinearAlgebra.adjoint(A::ZeroMap{T}) where {T} = ZeroMap{T}(A.domain, A.range)
LinearAlgebra.transpose(A::ZeroMap{T}) where {T} = ZeroMap{T}(A.domain, A.range)

function Base.:(*)(A::ZeroMap, x::AbstractVector)
    T = eltype(A)
    y = similar(A.range, T)
    fill!(y, zero(T))
    LinearAlgebra.mul!(y,A,x)
end

Base.Matrix{T}(A::ZeroMap) where {T} = zeros(T, length(A.range), length(A.domain))