text:
# Rectangular Full Packed Matrices

using LinearAlgebra: BlasFloat

import ..LAPACK2: trttf!
import Base: \
import LinearAlgebra: ldiv!

struct HermitianRFP{T<:BlasFloat} <: AbstractMatrix{T}
    data::Vector{T}
    transr::Char
    uplo::Char
end

function Base.size(A::HermitianRFP, i::Integer)
    if i == 1 || i == 2
        return (isqrt(8*length(A.data) + 1) - 1) >> 1
    elseif i > 2
        return 1
    else
        return size(A.data, i)
    end
end
function Base.size(A::HermitianRFP)
    n = size(A, 1)
    return (n, n)
end

function Base.getindex(A::HermitianRFP, i::Integer, j::Integer)
    n = size(A, 1)
    n2 = n >> 1
    if i < 1 || i > n || j < 0 || j > n
        throw(BoundsError(A, (i,j)))
    end
    if A.uplo == 'L'
        if i < j
            return conj(A[j,i])
        end

        if j <= n2 + isodd(n)
            if A.transr == 'N'
                return A.data[i + iseven(n) + (j - 1)*(n + iseven(n))]
            else
                return conj(A.data[(i - 1)*(n + iseven(n)) + j + iseven(n)])
            end
        else
            if A.transr == 'N'
                return conj(A.data[(i - n2 - 1)*(n + iseven(n)) + j - n2 - isodd(n)])
            else
                return A.data[i - n2 - isodd(n) + (j - n2 - 1)*(n + iseven(n))]
            end
        end
    else
        if i > j
            return conj(A[j,i])
        end

        if j > n2
            if A.transr == 'N'
                return A.data[i + (j - n2 - 1)*(n + iseven(n))]
            else
                return conj(A.data[(i - n2 - 1)*(n + iseven(n)) + j])
            end
        else
            if A.transr == 'N'
                return conj(A.data[(i - 1)*(n + iseven(n)) + j + n2 + 1])
            else
                return A.data[i - n2 - isodd(n) + (j - n2 - 1)*(n + iseven(n))]
            end
        end
    end
end

function Ac_mul_A_RFP(A::Matrix{T}, uplo = :U) where T<:BlasFloat
    n = size(A, 2)
    if uplo == :U
        C = LAPACK2.sfrk!('N', 'U', T <: Complex ? 'C' : 'T', 1.0, A, 0.0, Vector{T}(undef, (n*(n + 1)) >> 1))
        return HermitianRFP(C, 'N', 'U')
    elseif uplo == :L
        C = LAPACK2.sfrk!('N', 'L', T <: Complex ? 'C' : 'T', 1.0, A, 0.0, Vector{T}(undef, (n*(n + 1)) >> 1))
       return  HermitianRFP(C, 'N', 'L')
   else
        throw(ArgumentError("uplo must be either :L or :U"))
    end
end

Base.copy(A::HermitianRFP) = HermitianRFP(copy(A.data), A.transr, A.uplo)

struct TriangularRFP{T<:BlasFloat} <: AbstractMatrix{T}
    data::Vector{T}
    transr::Char
    uplo::Char
end

function TriangularRFP(A::StridedMatrix, uplo::Symbol = :U)
    if uplo == :U
        return TriangularRFP(trttf!('N', 'U', A), 'N', 'U')
    elseif uplo == :L
        return TriangularRFP(trttf!('N', 'L', A), 'N', 'L')
    else
        throw(ArgumentError("uplo must be either :U or :L but was :$uplo"))
    end
end

function Base.size(A::TriangularRFP, i::Integer)
    if i == 1 || i == 2
        return (isqrt(8*length(A.data) + 1) - 1) >> 1
    elseif i > 2
        return 1
    else
        return size(A.data, i)
    end
end
function Base.size(A::TriangularRFP)
    n = size(A, 1)
    return (n, n)
end

Base.copy(A::TriangularRFP) = TriangularRFP(copy(A.data), A.transr, A.uplo)

function Base.Array(A::TriangularRFP)
    C = LAPACK2.tfttr!(A.transr, A.uplo, A.data)
    if A.uplo == 'U'
        return triu!(C)
    else
        return tril!(C)
    end
end

LinearAlgebra.inv!(A::TriangularRFP) = TriangularRFP(LAPACK2.tftri!(A.transr, A.uplo, 'N', A.data), A.transr, A.uplo)
LinearAlgebra.inv(A::TriangularRFP)  = LinearAlgebra.inv!(copy(A))

ldiv!(A::TriangularRFP{T}, B::StridedVecOrMat{T}) where T =
    LAPACK2.tfsm!(A.transr, 'L', A.uplo, 'N', 'N', one(T), A.data, B)
(\)(A::TriangularRFP, B::StridedVecOrMat) = ldiv!(A, copy(B))

struct CholeskyRFP{T<:BlasFloat} <: Factorization{T}
    data::Vector{T}
    transr::Char
    uplo::Char
end

LinearAlgebra.cholesky!(A::HermitianRFP{T}) where {T<:BlasFloat} = CholeskyRFP(LAPACK2.pftrf!(A.transr, A.uplo, copy(A.data)), A.transr, A.uplo)
LinearAlgebra.cholesky(A::HermitianRFP{T}) where {T<:BlasFloat} = cholesky!(copy(A))
LinearAlgebra.factorize(A::HermitianRFP) = cholesky(A)

Base.copy(F::CholeskyRFP{T}) where T = CholeskyRFP{T}(copy(F.data), F.transr, F.uplo)

# Solve
(\)(A::CholeskyRFP, B::StridedVecOrMat) = LAPACK2.pftrs!(A.transr, A.uplo, A.data, copy(B))
(\)(A::HermitianRFP, B::StridedVecOrMat) = cholesky(A)\B

LinearAlgebra.inv!(A::CholeskyRFP) = HermitianRFP(LAPACK2.pftri!(A.transr, A.uplo, A.data), A.transr, A.uplo)
LinearAlgebra.inv(A::CholeskyRFP)  = LinearAlgebra.inv!(copy(A))
LinearAlgebra.inv(A::HermitianRFP) = LinearAlgebra.inv!(cholesky(A))


text:
function make_prob(T0, P, phi, p; tfinal=1.0)
    local fuel2air = 0.85 * 2 + 0.1 * 3.5 + 0.05 * 5
    X0 = zeros(ns);
    X0[species_index(gas, "CH4")] = phi * 0.85
    X0[species_index(gas, "C2H6")] = phi * 0.1
    X0[species_index(gas, "C3H8")] = phi * 0.05
    X0[species_index(gas, oxygen)] = fuel2air
    X0[species_index(gas, inert)] = fuel2air * 3.76

    X0 = X0 ./ sum(X0);
    Y0 = X2Y(gas, X0, dot(X0, gas.MW));
    u0 = vcat(Y0, T0);

    prob = ODEProblem(dudt!, u0, (0.0, tfinal), p);
    prob
end

ext: jl

max_stars_repo_name: DENG-MIT/DeepReduction

max_issues_repo_name: DENG-MIT/DeepReduction

max_forks_repo_name: DENG-MIT/DeepReduction


text:
module ScarletHeroesBot

# greet() = print("Hello World!")

using Random

DAMAGE_CHART = ((min_die_score = 10, damage = 4),
		(min_die_score = 6, damage = 2),
		(min_die_score = 2, damage = 1),
		(min_die_score = 1, damage = 0))

function convert_die_to_damage(die_roll)
	for damage_chart_entry in DAMAGE_CHART
		if die_roll >= damage_chart_entry.min_die_score
			return damage_chart_entry.damage
		end
	end
	return 0
end

function roll_damage_roll(n,m)
	damage = 0

	for die in 1:n
		damage += convert_die_to_damage(Random.rand(1:m))
	end

	damage
end

# Discord stuff to be put here.

using Discord

end # module

max_stars_repo_name: mgarbiso/scarlet-heroes-bot

max_issues_repo_name: mgarbiso/scarlet-heroes-bot

max_forks_repo_name: mgarbiso/scarlet-heroes-bot


text:
using FFTW
using LinearAlgebra
using DelimitedFiles

# using the convolutional theorem
function convolve_fft(signal1::Array{T}, signal2::Array{T}) where {T <: Number}
    return ifft(fft(signal1).*fft(signal2))
end

function main()

    # sawtooth functions for x and y
    x = [float(i)/200 for i = 1:200]
    y = [float(i)/200 for i = 1:200]

    # Normalization is not strictly necessary, but good practice
    normalize!(x)
    normalize!(y)

    # cyclic convolution via the convolutional theorem
    fft_output = convolve_fft(x, y)

    # outputting convolutions to different files for plotting in external code
    # note: we are outputting just the real component because the imaginary
    #       component is virtually 0
    writedlm("fft.dat", real(fft_output))

end

main()


text:
abstract type MotionDef end

mutable struct KinemPar
    alpha :: Float64
    h :: Float64
    alphadot :: Float64
    hdot :: Float64
    u :: Float64
    udot :: Float64
end

mutable struct KinemDef
    alpha :: MotionDef
    h :: MotionDef
    u :: MotionDef
end

struct EldUpDef <: MotionDef
    amp :: Float64
    K :: Float64
    a :: Float64
end

function (eld::EldUpDef)(t)
    sm = pi*pi*eld.K/(2*(eld.amp)*(1 - eld.a))
    t1 = 1.
    t2 = t1 + ((eld.amp)/(2*eld.K))
    ((eld.K/sm)*log(cosh(sm*(t - t1))/cosh(sm*(t - t2))))+(eld.amp/2)
end

struct EldUptstartDef <: MotionDef
    amp :: Float64
    K :: Float64
    a :: Float64
    tstart :: Float64
end

function (eld::EldUptstartDef)(t)
    sm = pi*pi*eld.K/(2*(eld.amp)*(1 - eld.a))
    t1 = eld.tstart
    t2 = t1 + ((eld.amp)/(2*eld.K))
    ((eld.K/sm)*log(cosh(sm*(t - t1))/cosh(sm*(t - t2))))+(eld.amp/2)
end

struct EldRampReturnDef <: MotionDef
    amp :: Float64
    K :: Float64
    a :: Float64
end

function (eld::EldRampReturnDef)(tt)
    fr = eld.K/(pi*abs(eld.amp));
    t1 = 1.
    t2 = t1 + (1. /(2*pi*fr));
    t3 = t2 + ((1/(4*fr)) - (1/(2*pi*fr)));
    t4 = t3 + (1. /(2*pi*fr));
    t5 = t4+1.;

    nstep = round(Int,t5/0.015) + 1
    g = zeros(nstep)
    t = zeros(nstep)

    for i = 1:nstep
        t[i] = (i-1.)*0.015
        g[i] = log((cosh(eld.a*(t[i] - t1))*cosh(eld.a*(t[i] - t4)))/(cosh(eld.a*(t[i] - t2))*cosh(eld.a*(t[i] - t3))))
    end
    maxg = maximum(g);

    gg = log((cosh(eld.a*(tt - t1))*cosh(eld.a*(tt - t4)))/(cosh(eld.a*(tt - t2))*cosh(eld.a*(tt - t3))))

    return eld.amp*gg/(maxg);

end

struct ConstDef <: MotionDef
    amp :: Float64
end

function (cons::ConstDef)(t)
    cons.amp
end

struct LinearDef <: MotionDef
    tstart :: Float64
    vstart :: Float64
    vend :: Float64
    len :: Float64
end

function (lin::LinearDef)(t)
    if t < lin.tstart
        lin.vstart
    elseif t > lin.tstart + lin.len
        lin.vend
    else
        lin.vstart + (lin.vend - lin.vstart)/lin.len*(t - lin.tstart)
    end
end

struct BendingDef <: MotionDef
    spl :: Spline1D
    scale :: Float64
    k :: Float64
    phi :: Float64
end

struct SinDef <: MotionDef
  mean :: Float64
  amp :: Float64
  k :: Float64
  phi :: Float64
end

function (kin::SinDef)(t)
  (kin.mean) + (kin.amp)*sin(2*kin.k*t + kin.phi)
end

struct CosDef <: MotionDef
  mean :: Float64
  amp :: Float64
  k :: Float64
  phi :: Float64
end

function (kin::CosDef)(t)
  (kin.mean) + (kin.amp)*cos(2*kin.k*t + kin.phi)
end

struct StepGustDef <: MotionDef
    amp :: Float64
    tstart :: Float64
    tgust :: Float64
end
 function (sgust::StepGustDef)(t)
    if t >= sgust.tstart && t <= sgust.tstart+sgust.tgust
        amp = (sgust.amp)
    else
        amp = 0.
    end
    amp
end

struct EldUpIntDef <: MotionDef
    amp :: Float64
    K :: Float64
    a :: Float64
end

function (eld::EldUpIntDef)(t)

    dt = 0.015
    nsteps = t/dt + 1
    nsteps = round(Int,nsteps)
    dt = t/(nsteps-1)
    sm = pi*pi*eld.K/(2*eld.amp*(1 - eld.a))
    t1 = 1.
    t2 = t1 + ((eld.amp)/(2*eld.K))

    prev_h = 0
    amp = 0
    for i = 1:nsteps
      tmpt = (i-1)*dt
      if (eld.amp == 0.)
      	 hdot = 0.
      else
         hdot = ((eld.K/sm)*log(cosh(sm*(tmpt - t1))/cosh(sm*(tmpt - t2))))+(eld.amp/2.)
      end
      amp = prev_h + hdot*dt
      prev_h = amp
    end
    if (nsteps == 1)
      amp = 0.
    end
    amp
end

struct EldUpInttstartDef <: MotionDef
    amp :: Float64
    K :: Float64
    a :: Float64
    tstart :: Float64
end

function (eld::EldUpInttstartDef)(t)

    dt = 0.015
    nsteps = t/dt + 1
    nsteps = round(Int,nsteps)
    dt = t/(nsteps-1)
    sm = pi*pi*eld.K/(2*eld.amp*(1 - eld.a))
    t1 = eld.tstart
    t2 = t1 + ((eld.amp)/(2*eld.K))

    prev_h = 0
    amp = 0
    for i = 1:nsteps
      tmpt = (i-1)*dt
	  if (eld.amp == 0.)
      	 hdot = 0.
      else
         hdot = ((eld.K/sm)*log(cosh(sm*(tmpt - t1))/cosh(sm*(tmpt - t2))))+(eld.amp/2.)
      end
      amp = prev_h + hdot*dt
      prev_h = amp
    end
    if (nsteps == 1)
      amp = 0.
    end
    amp
end

max_stars_repo_name: hjabird/UNSflow

max_issues_repo_name: hjabird/UNSflow

max_forks_repo_name: hjabird/UNSflow


text:
using Turing, Random, Test
using Turing: Sampler, NUTS
using MCMCChains: Chains

dir = splitdir(splitdir(pathof(Turing))[1])[1]
include(dir*"/test/test_utils/AllUtils.jl")

@testset "hmc.jl" begin
    @numerical_testset "constrained bounded" begin
        obs = [0,1,0,1,1,1,1,1,1,1]

        @model constrained_test(obs) = begin
            p ~ Beta(2,2)
            for i = 1:length(obs)
                obs[i] ~ Bernoulli(p)
            end
            p
        end

        chain = sample(
            constrained_test(obs),
            HMC(1.5, 3),# using a large step size (1.5)
            1000)

        check_numerical(chain, [:p], [10/14], atol=0.1)
    end
    @numerical_testset "contrained simplex" begin
        obs12 = [1,2,1,2,2,2,2,2,2,2]

        @model constrained_simplex_test(obs12) = begin
            ps ~ Dirichlet(2, 3)
            pd ~ Dirichlet(4, 1)
            for i = 1:length(obs12)
                obs12[i] ~ Categorical(ps)
            end
            return ps
        end

        chain = sample(
            constrained_simplex_test(obs12),
            HMC(0.75, 2),
            1000)

        check_numerical(chain, ["ps[1]", "ps[2]"], [5/16, 11/16], atol=0.015)
    end
    @numerical_testset "hmc reverse diff" begin
        Random.seed!(1)
        alg = HMC(0.1, 10)
        res = sample(gdemo_default, alg, 4000)
        check_gdemo(res, rtol=0.1)
    end
    @turing_testset "matrix support" begin
        @model hmcmatrixsup() = begin
            v ~ Wishart(7, [1 0.5; 0.5 1])
        end

        model_f = hmcmatrixsup()
        vs = []
        chain = nothing
        # n_adapts, n_samples = 1_000, 2_000
        n_samples = 1_000
        for _ in 1:3
            chain = sample(model_f, HMC(0.15, 7), n_samples)
            r = reshape(chain[:v].value, n_samples, 2, 2)
            push!(vs, reshape(mean(r, dims = [1]), 2, 2))
        end

        @test maximum(abs, mean(vs) - (7 * [1 0.5; 0.5 1])) <= 0.5
    end
    @turing_testset "multivariate support" begin
        function sigmoid(t)
            return 1 / (1 + exp.(-t))
        end

        # Define NN flow
        function nn(x, b1, w11, w12, w13, bo, wo)
            h = tanh.([w11 w12 w13]' * x + b1)
            return sigmoid((wo' * h)[1] + bo)
        end

        # Generating training data
        N = 20
        M = N ÷ 4
        x1s = rand(M) * 5
        x2s = rand(M) * 5
        xt1s = Array([[x1s[i]; x2s[i]] for i = 1:M])
        append!(xt1s, Array([[x1s[i] - 6; x2s[i] - 6] for i = 1:M]))
        xt0s = Array([[x1s[i]; x2s[i] - 6] for i = 1:M])
        append!(xt0s, Array([[x1s[i] - 6; x2s[i]] for i = 1:M]))

        xs = [xt1s; xt0s]
        ts = [ones(M); ones(M); zeros(M); zeros(M)]

        # Define model

        alpha = 0.16                  # regularizatin term
        var_prior = sqrt(1.0 / alpha) # variance of the Gaussian prior

        @model bnn(ts) = begin
            b1 ~ MvNormal([0. ;0.; 0.],
                [var_prior 0. 0.; 0. var_prior 0.; 0. 0. var_prior])
            w11 ~ MvNormal([0.; 0.], [var_prior 0.; 0. var_prior])
            w12 ~ MvNormal([0.; 0.], [var_prior 0.; 0. var_prior])
            w13 ~ MvNormal([0.; 0.], [var_prior 0.; 0. var_prior])
            bo ~ Normal(0, var_prior)

            wo ~ MvNormal([0.; 0; 0],
                [var_prior 0. 0.; 0. var_prior 0.; 0. 0. var_prior])
            for i = rand(1:N, 10)
                y = nn(xs[i], b1, w11, w12, w13, bo, wo)
                ts[i] ~ Bernoulli(y)
            end
            b1, w11, w12, w13, bo, wo
        end

        # Sampling
        chain = sample(bnn(ts), HMC(0.1, 5), 10)
    end
    Random.seed!(123)
    @numerical_testset "hmcda inference" begin
        alg1 = HMCDA(1000, 0.8, 0.015)
        # alg2 = Gibbs(HMCDA(200, 0.8, 0.35, :m), HMC(0.25, 3, :s))
        alg3 = Gibbs(PG(10, :s), HMCDA(200, 0.8, 0.005, :m))
        # alg3 = Gibbs(HMC(0.25, 3, :m), PG(30, 3, :s))
        # alg3 = PG(50, 2000)

        res1 = sample(gdemo_default, alg1, 3000)
        check_gdemo(res1)

        # res2 = sample(gdemo([1.5, 2.0]), alg2)
        #
        # @test mean(res2[:s]) ≈ 49/24 atol=0.2
        # @test mean(res2[:m]) ≈ 7/6 atol=0.2

        res3 = sample(gdemo_default, alg3, 1000)
        check_gdemo(res3)
    end
    @turing_testset "hmcda constructor" begin
        alg = HMCDA(0.8, 0.75)
        println(alg)
        sampler = Sampler(alg, gdemo_default)

        alg = HMCDA(200, 0.8, 0.75)
        println(alg)
        sampler = Sampler(alg, gdemo_default)

        alg = HMCDA(200, 0.8, 0.75, :s)
        println(alg)
        sampler = Sampler(alg, gdemo_default)

        @test isa(alg, HMCDA)
        @test isa(sampler, Sampler{<:Turing.Hamiltonian})
    end
    @numerical_testset "nuts inference" begin
        alg = NUTS(1000, 0.8)
        res = sample(gdemo_default, alg, 6000)
        check_gdemo(res)
    end
    @turing_testset "nuts constructor" begin
        alg = NUTS(200, 0.65)
        sampler = Sampler(alg, gdemo_default)

        alg = NUTS(0.65)
        sampler = Sampler(alg, gdemo_default)

        alg = NUTS(200, 0.65, :m)
        sampler = Sampler(alg, gdemo_default)
    end
    @turing_testset "check discard" begin
        alg = NUTS(100, 0.8)

        c1 = sample(gdemo_default, alg, 500, discard_adapt = true)
        c2 = sample(gdemo_default, alg, 500, discard_adapt = false)

        @test size(c1, 1) == 400
        @test size(c2, 1) == 500
    end
    @turing_testset "AHMC resize" begin
        alg1 = Gibbs(PG(10, :m), NUTS(100, 0.65, :s))
        alg2 = Gibbs(PG(10, :m), HMC(0.1, 3, :s))
        alg3 = Gibbs(PG(10, :m), HMCDA(100, 0.65, 0.3, :s))
        @test sample(gdemo_default, alg1, 300) isa Chains
        @test sample(gdemo_default, alg2, 300) isa Chains
        @test sample(gdemo_default, alg3, 300) isa Chains
    end

    @turing_testset "Regression tests" begin
        # https://github.com/TuringLang/DynamicPPL.jl/issues/27
        @model mwe(::Type{T}=Float64) where {T<:Real} = begin
            m = Matrix{T}(undef, 2, 3)
            @. m ~ MvNormal(zeros(2), 1)
        end

        @test sample(mwe(), HMC(0.2, 4), 1_000) isa Chains
    end
end


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

module jtest
using ..json
using ..lexer
using ..parser
using BenchmarkTools

json_text_1 = """{"foo": [1, 2, {"bar": 2}]}"""

# json_text_2 = "{}"
# json_obj_2 = json.parse_json(json_text_2)

function simple()

json_text_3 = """{
    "a": 1,
    "b": 20e2,
    "c": [1, 2, 3],
    "d": ["first", "second", "third"],
    "e": [1, "bla", 3.14],
    "f": {
        "nested1": 10,
        "nested2": 20
    },
    "g": [false, false, true,false],
    "bla": "obj"
}"""

# @time tokens = json.lex_json(json_text_3)
json_obj_3 = json.parse(json_text_3)
end

function simple2()
    inner_str = """{
    "a": 1,
    "b": 20e2,
    "c": [1, 2, 3],
    "d": ["first", "second", "third"],
    "e": [1, "bla", 3.14],
    "f": {
        "nested1": 10,
        "nested2": 20
    },
    "g": [false, false, true,false]
    },
    """

json_text_3 = """ { "bla": [""" * chop(repeat(inner_str, 1000); head = 0, tail = 1) * "]}"

# 10 - 0.035886, allocs: 8410
# TokenList object with:
#         token_stack with 646 elements
#         number_stack with 90 elements
#         string_stack with 131 elements
#
# 100 - 0.328s, allocs: 93022
# TokenList object with:
#         token_stack with 6406 elements
#         number_stack with 900 elements
#         string_stack with 1301 elements
#
# 200 -  1.053 s, allocs: 187027
# 200 - 5ms, allocs: 110388

# 1000 - 28.5s, allocs:
# 1000 - 30ms allocs: 553602
# TokenList object with:
#         token_stack with 64006 elements
#         number_stack with 9000 elements
#         string_stack with 13001 elements
#
#

# tokens = json.lex_json(json_text_3)
b = @benchmark json.lex_json($json_text_3)
show(
    stdout,
    MIME("text/plain"),
    b
)

# json_obj_3 = json.parse(json_text_3)
end

function b_lex()
    json_text = "12345 true                                                                                "
    start_idx = 6

    b = BenchmarkTools.@benchmark lexer.lex_bool($json_text, $start_idx)
    show(
        stdout,
        MIME("text/plain"),
        b
    )
end

function benchmark_parse()
    url = "saved_mesh.txt"

    iostr = open(url, "r");
    iobuff = read(iostr, String);
    close(iostr);

    # dict = json.parse_json(iobuff)

    # dict = json.parse(iobuff)
    tokens = lexer.lex_json(iobuff)
end

function benchmark_it()
    b = BenchmarkTools.@benchmark benchmark_parse()
    show(
        stdout,
        MIME("text/plain"),
        b
    )
end

function test_parse_number()
    text_1 = "10"
    text_2 = " 10 "
    text_3 = "\t10\n"
    text_4 = "1e3"
    text_5 = "1.6e2"
    text_6 = "-1.6e2"
    text_7 = "-1.6e-2"

    num_1 = json.parse_number(text_1)
    num_2 = json.parse_number(text_2)
    num_3 = json.parse_number(text_3)
    num_4 = json.parse_number(text_4)
    num_5 = json.parse_number(text_5)
    num_6 = json.parse_number(text_6)
    num_7 = json.parse_number(text_7)
end

end

max_stars_repo_name: HomoModelicus/julia

max_issues_repo_name: HomoModelicus/julia

max_forks_repo_name: HomoModelicus/julia


text:
const pyjlanytype = pynew()

pyjlany_repr(self) = Py("<jl $(repr(self))>")

pyjlany_str(self) = Py(string(self))

function pyjlany_getattr(self, k_::Py)
    k = Symbol(pyjl_attr_py2jl(pyconvert(String, k_)))
    Py(getproperty(self, k))
end
pyjl_handle_error_type(::typeof(pyjlany_getattr), self, exc) = pybuiltins.AttributeError

function pyjlany_setattr(self, k_::Py, v_::Py)
    k = Symbol(pyjl_attr_py2jl(pyconvert(String, k_)))
    v = pyconvert(Any, v_)
    setproperty!(self, k, v)
    Py(nothing)
end
pyjl_handle_error_type(::typeof(pyjlany_setattr), self, exc) = pybuiltins.AttributeError

pyjlany_dir(self) = pylist(pyjl_attr_jl2py(string(k)) for k in propertynames(self, true))

function pyjlany_call(self, args_::Py, kwargs_::Py)
    if pylen(kwargs_) > 0
        args = pyconvert(Vector{Any}, args_)
        kwargs = pyconvert(Dict{Symbol,Any}, kwargs_)
        Py(self(args...; kwargs...))
    elseif pylen(args_) > 0
        args = pyconvert(Vector{Any}, args_)
        Py(self(args...))
    else
        Py(self())
    end
end
pyjl_handle_error_type(::typeof(pyjlany_call), self, exc) = exc isa MethodError && exc.f === self ? pybuiltins.TypeError : PyNULL

pyjlany_getitem(self, k_::Py) =
    if pyistuple(k_)
        k = pyconvert(Vector{Any}, k_)
        Py(self[k...])
    else
        k = pyconvert(Any, k_)
        Py(self[k])
    end
pyjl_handle_error_type(::typeof(pyjlany_getitem), self, exc) = exc isa BoundsError ? pybuiltins.IndexError : exc isa KeyError ? pybuiltins.KeyError : PyNULL

function pyjlany_setitem(self, k_::Py, v_::Py)
    v = pyconvert(Any, v_)
    if pyistuple(k_)
        k = pyconvert(Vector{Any}, k_)
        self[k...] = v
    else
        k = pyconvert(Any, k_)
        self[k] = v
    end
    Py(nothing)
end
pyjl_handle_error_type(::typeof(pyjlany_setitem), self, exc) = exc isa BoundsError ? pybuiltins.IndexError : exc isa KeyError ? pybuiltins.KeyError : PyNULL

function pyjlany_delitem(self, k_::Py)
    if pyistuple(k_)
        k = pyconvert(Vector{Any}, k_)
        delete!(self, k...)
    else
        k = pyconvert(Any, k_)
        delete!(self, k)
    end
    Py(nothing)
end
pyjl_handle_error_type(::typeof(pyjlany_delitem), self, exc) = exc isa BoundsError ? pybuiltins.IndexError : exc isa KeyError ? pybuiltins.KeyError : PyNULL

pyjlany_contains(self, v::Py) = Py(@pyconvert(eltype(self), v, return Py(false)) in self)
pyjl_handle_error_type(::typeof(pyjlany_contains), self, exc) = exc isa MethodError && exc.f === in ? pybuiltins.TypeError : PyNULL

struct pyjlany_op{OP}
    op :: OP
end
(op::pyjlany_op)(self) = Py(op.op(self))
function (op::pyjlany_op)(self, other_::Py)
    if pyisjl(other_)
        other = pyjlvalue(other_)
        Py(op.op(self, other))
    else
        Py(pybuiltins.NotImplemented)
    end
end
function (op::pyjlany_op)(self, other_::Py, other2_::Py)
    if pyisjl(other_) && pyisjl(other2_)
        other = pyjlvalue(other_)
        other2 = pyjlvalue(other2_)
        Py(op.op(self, other, other2))
    else
        Py(pybuiltins.NotImplemented)
    end
end
pyjl_handle_error_type(op::pyjlany_op, self, exc) = exc isa MethodError && exc.f === op.op ? pybuiltins.TypeError : PyNULL

struct pyjlany_rev_op{OP}
    op :: OP
end
function (op::pyjlany_rev_op)(self, other_::Py)
    if pyisjl(other_)
        other = pyjlvalue(other_)
        Py(op.op(self, other))
    else
        Py(pybuiltins.NotImplemented)
    end
end
function (op::pyjlany_rev_op)(self, other_::Py, other2_::Py)
    if pyisjl(other_) && pyisjl(other2_)
        other = pyjlvalue(other_)
        other2 = pyjlvalue(other2_)
        Py(op.op(self, other, other2))
    else
        Py(pybuiltins.NotImplemented)
    end
end
pyjl_handle_error_type(op::pyjlany_rev_op, self, exc) = exc isa MethodError && exc.f === op.op ? pybuiltins.TypeError : PyNULL

pyjlany_name(self) = Py(string(nameof(self)))
pyjl_handle_error_type(::typeof(pyjlany_name), self, exc) = exc isa MethodError && exc.f === nameof ? pybuiltins.AttributeError : PyNULL

function pyjlany_display(self, mime_::Py)
    mime = pyconvertarg(Union{Nothing,String}, mime_, "mime")
    x = Utils.ExtraNewline(self)
    if mime === nothing
        display(x)
    else
        display(mime, x)
    end
    Py(nothing)
end

function pyjlany_help(self, mime_::Py)
    mime = pyconvertarg(Union{Nothing,String}, mime_, "mime")
    x = Utils.ExtraNewline(Docs.doc(self))
    if mime === nothing
        display(x)
    else
        display(mime, x)
    end
    Py(nothing)
end

function pyjlany_mimebundle(self, include::Py, exclude::Py)
    # TODO: use include/exclude
    mimes = Utils.mimes_for(self)
    # make the bundle
    ans = pydict()
    for m in mimes
        try
            io = IOBuffer()
            show(io, MIME(m), self)
            v = take!(io)
            ans[m] = vo = istextmime(m) ? pystr(String(v)) : pybytes(v)
            pydel!(vo)
        catch err
            # silently skip anything that didn't work
        end
    end
    return ans
end

function init_jlwrap_any()
    jl = pyjuliacallmodule
    filename = "$(@__FILE__):$(1+@__LINE__)"
    pybuiltins.exec(pybuiltins.compile("""
    class AnyValue(ValueBase):
        __slots__ = ()
        __module__ = "juliacall"
        def __repr__(self):
            if self._jl_isnull():
                return "<jl NULL>"
            else:
                return self._jl_callmethod($(pyjl_methodnum(pyjlany_repr)))
        def __str__(self):
            if self._jl_isnull():
                return "NULL"
            else:
                return self._jl_callmethod($(pyjl_methodnum(pyjlany_str)))
        def __getattr__(self, k):
            if k.startswith("__") and k.endswith("__"):
                raise AttributeError(k)
            else:
                return self._jl_callmethod($(pyjl_methodnum(pyjlany_getattr)), k)
        def __setattr__(self, k, v):
            try:
                ValueBase.__setattr__(self, k, v)
            except AttributeError:
                if k.startswith("__") and k.endswith("__"):
                    raise AttributeError(k)
                else:
                    self._jl_callmethod($(pyjl_methodnum(pyjlany_setattr)), k, v)
        def __dir__(self):
            return ValueBase.__dir__(self) + self._jl_callmethod($(pyjl_methodnum(pyjlany_dir)))
        def __call__(self, *args, **kwargs):
            return self._jl_callmethod($(pyjl_methodnum(pyjlany_call)), args, kwargs)
        def __len__(self):
            return self._jl_callmethod($(pyjl_methodnum(pyjlany_op(length))))
        def __getitem__(self, k):
            return self._jl_callmethod($(pyjl_methodnum(pyjlany_getitem)), k)
        def __setitem__(self, k, v):
            self._jl_callmethod($(pyjl_methodnum(pyjlany_setitem)), k, v)
        def __delitem__(self, k):
            self._jl_callmethod($(pyjl_methodnum(pyjlany_delitem)), k)
        def __iter__(self):
            return self._jl_callmethod($(pyjl_methodnum(pyjlany_op(Iterator))))
        def __reversed__(self):
            return self._jl_callmethod($(pyjl_methodnum(pyjlany_op(reverse))))
        def __contains__(self, v):
            return self._jl_callmethod($(pyjl_methodnum(pyjlany_contains)), v)
        def __pos__(self):
            return self._jl_callmethod($(pyjl_methodnum(pyjlany_op(+))))
        def __neg__(self):
            return self._jl_callmethod($(pyjl_methodnum(pyjlany_op(-))))
        def __abs__(self):
            return self._jl_callmethod($(pyjl_methodnum(pyjlany_op(abs))))
        def __invert__(self):
            return self._jl_callmethod($(pyjl_methodnum(pyjlany_op(~))))
        def __add__(self, other):
            return self._jl_callmethod($(pyjl_methodnum(pyjlany_op(+))), other)
        def __sub__(self, other):
            return self._jl_callmethod($(pyjl_methodnum(pyjlany_op(-))), other)
        def __mul__(self, other):
            return self._jl_callmethod($(pyjl_methodnum(pyjlany_op(*))), other)
        def __truediv__(self, other):
            return self._jl_callmethod($(pyjl_methodnum(pyjlany_op(/))), other)
        def __floordiv__(self, other):
            return self._jl_callmethod($(pyjl_methodnum(pyjlany_op(÷))), other)
        def __mod__(self, other):
            return self._jl_callmethod($(pyjl_methodnum(pyjlany_op(%))), other)
        def __pow__(self, other, modulo=None):
            if modulo is None:
                return self._jl_callmethod($(pyjl_methodnum(pyjlany_op(^))), other)
            else:
                return self._jl_callmethod($(pyjl_methodnum(pyjlany_op(powermod))), other, modulo)
        def __lshift__(self, other):
            return self._jl_callmethod($(pyjl_methodnum(pyjlany_op(<<))), other)
        def __rshift__(self, other):
            return self._jl_callmethod($(pyjl_methodnum(pyjlany_op(>>))), other)
        def __and__(self, other):
            return self._jl_callmethod($(pyjl_methodnum(pyjlany_op(&))), other)
        def __xor__(self, other):
            return self._jl_callmethod($(pyjl_methodnum(pyjlany_op(⊻))), other)
        def __or__(self, other):
            return self._jl_callmethod($(pyjl_methodnum(pyjlany_op(|))), other)
        def __radd__(self, other):
            return self._jl_callmethod($(pyjl_methodnum(pyjlany_rev_op(+))), other)
        def __rsub__(self, other):
            return self._jl_callmethod($(pyjl_methodnum(pyjlany_rev_op(-))), other)
        def __rmul__(self, other):
            return self._jl_callmethod($(pyjl_methodnum(pyjlany_rev_op(*))), other)
        def __rtruediv__(self, other):
            return self._jl_callmethod($(pyjl_methodnum(pyjlany_rev_op(/))), other)
        def __rfloordiv__(self, other):
            return self._jl_callmethod($(pyjl_methodnum(pyjlany_rev_op(÷))), other)
        def __rmod__(self, other):
            return self._jl_callmethod($(pyjl_methodnum(pyjlany_rev_op(%))), other)
        def __rpow__(self, other, modulo=None):
            if modulo is None:
                return self._jl_callmethod($(pyjl_methodnum(pyjlany_rev_op(^))), other)
            else:
                return self._jl_callmethod($(pyjl_methodnum(pyjlany_rev_op(powermod))), other, modulo)
        def __rlshift__(self, other):
            return self._jl_callmethod($(pyjl_methodnum(pyjlany_rev_op(<<))), other)
        def __rrshift__(self, other):
            return self._jl_callmethod($(pyjl_methodnum(pyjlany_rev_op(>>))), other)
        def __rand__(self, other):
            return self._jl_callmethod($(pyjl_methodnum(pyjlany_rev_op(&))), other)
        def __rxor__(self, other):
            return self._jl_callmethod($(pyjl_methodnum(pyjlany_rev_op(⊻))), other)
        def __ror__(self, other):
            return self._jl_callmethod($(pyjl_methodnum(pyjlany_rev_op(|))), other)
        def __eq__(self, other):
            return self._jl_callmethod($(pyjl_methodnum(pyjlany_op(==))), other)
        def __ne__(self, other):
            return self._jl_callmethod($(pyjl_methodnum(pyjlany_op(!=))), other)
        def __le__(self, other):
            return self._jl_callmethod($(pyjl_methodnum(pyjlany_op(≤))), other)
        def __lt__(self, other):
            return self._jl_callmethod($(pyjl_methodnum(pyjlany_op(<))), other)
        def __ge__(self, other):
            return self._jl_callmethod($(pyjl_methodnum(pyjlany_op(≥))), other)
        def __gt__(self, other):
            return self._jl_callmethod($(pyjl_methodnum(pyjlany_op(>))), other)
        def __hash__(self):
            return self._jl_callmethod($(pyjl_methodnum(pyjlany_op(hash))))
        @property
        def __name__(self):
            return self._jl_callmethod($(pyjl_methodnum(pyjlany_name)))
        def _jl_raw(self):
            return self._jl_callmethod($(pyjl_methodnum(pyjlraw)))
        def _jl_display(self, mime=None):
            return self._jl_callmethod($(pyjl_methodnum(pyjlany_display)), mime)
        def _jl_help(self, mime=None):
            return self._jl_callmethod($(pyjl_methodnum(pyjlany_help)), mime)
        def _repr_mimebundle_(self, include=None, exclude=None):
            return self._jl_callmethod($(pyjl_methodnum(pyjlany_mimebundle)), include, exclude)
    """, filename, "exec"), jl.__dict__)
    pycopy!(pyjlanytype, jl.AnyValue)
end

"""
    pyjl([t], x)

Create a Python object wrapping the Julia object `x`.

If `x` is mutable, then mutating the returned object also mutates `x`, and vice versa.

Its Python type is normally inferred from the type of `x`, but can be specified with `t`.

For example if `x` is an `AbstractVector` then the object will have type `juliacall.VectorValue`.
This object will satisfy the Python sequence interface, so for example uses 0-up indexing.
"""
pyjl(v) = pyjl(pyjlanytype, v)


text:
module Spaces

using Genie, Stipple, StippleUI, StippleUI.API
import Genie.Renderer.Html: HTMLString, normal_element, template

export space

function __init__()
  Genie.Renderer.Html.register_normal_element("q__space", context = Genie.Renderer.Html)
end

function space(args...; wrap::Function = StippleUI.DEFAULT_WRAPPER, kwargs...)
  wrap() do
    Genie.Renderer.Html.q__space(args...; kwargs...)
  end
end

end


text:
# Autogenerated wrapper script for LAME_jll for powerpc64le-linux-gnu
export lame, libmp3lame

JLLWrappers.@generate_wrapper_header("LAME")
JLLWrappers.@declare_executable_product(lame)
JLLWrappers.@declare_library_product(libmp3lame, "libmp3lame.so.0")
function __init__()
    JLLWrappers.@generate_init_header()
    JLLWrappers.@init_executable_product(
        lame,
        "bin/lame",
    )

    JLLWrappers.@init_library_product(
        libmp3lame,
        "lib/libmp3lame.so",
        RTLD_LAZY | RTLD_DEEPBIND,
    )

    JLLWrappers.@generate_init_footer()
end  # __init__()


text:
module DynamicPressures

struct PressureTube
    L::Vector{Float64}
    D::Vector{Float64}
    V::Vector{Float64}
    ϕ::Vector{Float64}

end


text:
# Test constraint deletion
@testset "JuMP.delete (Constraints)" begin
    # initialize model and references
    m = InfiniteModel()
    @infinite_parameter(m, 0 <= par <= 1)
    @infinite_variable(m, inf(par))
    @point_variable(m, inf(0.5), pt)
    @hold_variable(m, x)
    var = build_variable(error, inf, Dict{Int, Float64}(1 => 0.5), check = false)
    rv = add_variable(m, var)
    data = TestData(par, 0, 1)
    meas = measure(inf + par - x, data)
    d1 = @deriv(inf, par)
    @constraint(m, cref, par - inf + pt + 2x - rv + meas - d1 <= 1)
    # test normal deletion
    @test isa(delete(m, cref), Nothing)
    @test !is_valid(m, cref)
    @test !used_by_constraint(par)
    @test !used_by_constraint(inf)
    @test !used_by_constraint(pt)
    @test !used_by_constraint(x)
    @test !used_by_constraint(rv)
    @test !used_by_constraint(meas)
    @test !used_by_constraint(d1)
    @test isempty(InfiniteOpt._data_dictionary(cref))
    # test assertion error
    @test_throws AssertionError delete(m, cref)
end

# Test deleting variable information
@testset "Variable Information" begin
    # initialize model and references
    m = InfiniteModel()
    @infinite_parameter(m, 0 <= par <= 1)
    @infinite_variable(m, 0 <= inf1(par) <= 1, Bin)
    @infinite_variable(m, inf2(par) == 1, Int)
    @point_variable(m, inf1(0.5), pt1)
    @point_variable(m, inf2(0.5), pt2)
    @hold_variable(m, 0 <= gb1 <= 1, Bin)
    @hold_variable(m, gb2 == 1, Int)
    @derivative_variable(m, d(inf1)/d(par), 0 <= d1 <= 1)
    @derivative_variable(m, d(inf2)/d(par), d2 == 1)
    # test delete_lower_bound
    @testset "JuMP.delete_lower_bound" begin
        # test with infinite variable
        @test has_lower_bound(inf1)
        @test isa(delete_lower_bound(inf1), Nothing)
        @test !has_lower_bound(inf1)
        @test_throws ErrorException delete_lower_bound(inf2)
        # test with point variable
        @test has_lower_bound(pt1)
        @test isa(delete_lower_bound(pt1), Nothing)
        @test !has_lower_bound(pt1)
        @test_throws ErrorException delete_lower_bound(pt2)
        # test with hold variable
        @test has_lower_bound(gb1)
        @test isa(delete_lower_bound(gb1), Nothing)
        @test !has_lower_bound(gb1)
        @test_throws ErrorException delete_lower_bound(gb2)
        # test with derivative
        @test has_lower_bound(d1)
        @test isa(delete_lower_bound(d1), Nothing)
        @test !has_lower_bound(d1)
        @test_throws ErrorException delete_lower_bound(d2)
    end
    # test delete_upper_bound
    @testset "JuMP.delete_upper_bound" begin
        # test with infinite variable
        @test has_upper_bound(inf1)
        @test isa(delete_upper_bound(inf1), Nothing)
        @test !has_upper_bound(inf1)
        @test_throws ErrorException delete_upper_bound(inf2)
        # test with point variable
        @test has_upper_bound(pt1)
        @test isa(delete_upper_bound(pt1), Nothing)
        @test !has_upper_bound(pt1)
        @test_throws ErrorException delete_upper_bound(pt2)
        # test with hold variable
        @test has_upper_bound(gb1)
        @test isa(delete_upper_bound(gb1), Nothing)
        @test !has_upper_bound(gb1)
        @test_throws ErrorException delete_upper_bound(gb2)
        # test with derivative
        @test has_upper_bound(d1)
        @test isa(delete_upper_bound(d1), Nothing)
        @test !has_upper_bound(d1)
        @test_throws ErrorException delete_upper_bound(d2)
    end
    # test unfix
    @testset "JuMP.unfix" begin
        # test with infinite variable
        @test is_fixed(inf2)
        @test isa(unfix(inf2), Nothing)
        @test !is_fixed(inf2)
        @test_throws ErrorException unfix(inf1)
        # test with point variable
        @test is_fixed(pt2)
        @test isa(unfix(pt2), Nothing)
        @test !is_fixed(pt2)
        @test_throws ErrorException unfix(pt1)
        # test with hold variable
        @test is_fixed(gb2)
        @test isa(unfix(gb2), Nothing)
        @test !is_fixed(gb2)
        @test_throws ErrorException unfix(gb1)
        # test with derivative
        @test is_fixed(d2)
        @test isa(unfix(d2), Nothing)
        @test !is_fixed(d2)
        @test_throws ErrorException unfix(d1)
    end
    # test unset_binary
    @testset "JuMP.unset_binary" begin
        # test with infinite variable
        @test is_binary(inf1)
        @test isa(unset_binary(inf1), Nothing)
        @test !is_binary(inf1)
        @test_throws ErrorException unset_binary(inf2)
        # test with point variable
        @test is_binary(pt1)
        @test isa(unset_binary(pt1), Nothing)
        @test !is_binary(pt1)
        @test_throws ErrorException unset_binary(pt2)
        # test with hold variable
        @test is_binary(gb1)
        @test isa(unset_binary(gb1), Nothing)
        @test !is_binary(gb1)
        @test_throws ErrorException unset_binary(gb2)
    end
    # test unset_integer
    @testset "JuMP.unset_integer" begin
        # test with infinite variable
        @test is_integer(inf2)
        @test isa(unset_integer(inf2), Nothing)
        @test !is_integer(inf2)
        @test_throws ErrorException unset_integer(inf1)
        # test with point variable
        @test is_integer(pt2)
        @test isa(unset_integer(pt2), Nothing)
        @test !is_integer(pt2)
        @test_throws ErrorException unset_integer(pt1)
        # test with hold variable
        @test is_integer(gb2)
        @test isa(unset_integer(gb2), Nothing)
        @test !is_integer(gb2)
        @test_throws ErrorException unset_integer(gb1)
    end
end

# Test scalar parameter deletion
@testset "Scalar Parameters" begin
    # initialize model
    m = InfiniteModel()
    # setup the parameters
    @infinite_parameter(m, 0 <= par <= 1)
    @infinite_parameter(m, 0 <= par2 <= 1)
    @infinite_parameter(m, 0 <= pars[1:2] <= 1)
    @infinite_parameter(m, 0 <= par3 <= 1)
    @finite_parameter(m, fin, 42)
    @finite_parameter(m, fin2, 42)
    dpar = dispatch_variable_ref(par)
    dpars = dispatch_variable_ref.(pars)
    dpar2 = dispatch_variable_ref(par2)
    dpar3 = dispatch_variable_ref(par3)
    dfin = dispatch_variable_ref(fin)
    dfin2 = dispatch_variable_ref(fin2)
    # setup the variables
    @infinite_variable(m, inf(par))
    @infinite_variable(m, inf2(par, par2))
    @infinite_variable(m, inf3(par, pars))
    @infinite_variable(m, inf4(par, par2, pars))
    @point_variable(m, inf(0.5), pt)
    pt2 = @point_variable(m, inf2(0.5, 0.5))
    @point_variable(m, inf3(0, [0, 0]), pt3)
    @hold_variable(m, x)
    var = build_variable(error, inf4, Dict{Int, Float64}(2 => 0.5), check = false)
    rv = add_variable(m, var)
    dinf = dispatch_variable_ref(inf)
    dinf2 = dispatch_variable_ref(inf2)
    dinf3 = dispatch_variable_ref(inf3)
    dinf4 = dispatch_variable_ref(inf4)
    dpt = dispatch_variable_ref(pt)
    dpt2 = dispatch_variable_ref(pt2)
    dpt3 = dispatch_variable_ref(pt3)
    dx = dispatch_variable_ref(x)
    drv = dispatch_variable_ref(rv)
    # setup the measure
    data = TestData(par, 0, 1)
    mref = measure(inf + par - x + rv + par2 + par3 + fin, data)
    mref2 = measure(par2, data)
    dmref = dispatch_variable_ref(mref)
    dmref2 = dispatch_variable_ref(mref2)
    # setup a derivative
    d1 = @deriv(inf2, par2)
    # setup the constraints
    @constraint(m, con, inf2 + inf4 - par2 + par3 + fin <= 0)
    constr = ScalarConstraint(par2, MOI.GreaterThan(0.))
    con2 = add_constraint(m, constr)
    # setup objective
    set_objective(m, MOI.MIN_SENSE, fin)
    # test _check_param_in_data
    @testset "_check_param_in_data" begin
        @test_throws ErrorException InfiniteOpt._check_param_in_data(par, data)
        @test isa(InfiniteOpt._check_param_in_data(par2, data), Nothing)
        @test isa(InfiniteOpt._check_param_in_data(pars[1], data), Nothing)
        @test_throws ErrorException InfiniteOpt._check_param_in_data(par, BadData())
    end
    # test _update_reduced_variable
    @testset "_update_reduced_variable" begin
        # test removing single parameter that is not reduced
        _update_variable_param_refs(dinf4, IC.VectorTuple(par2, pars))
        @test isa(InfiniteOpt._update_reduced_variable(drv, 1:1), Nothing)
        @test infinite_variable_ref(drv) == inf4
        @test eval_supports(drv) == Dict(1 => 0.5)
        @test string(drv) == "inf4(0.5, [pars[1], pars[2]])"
        # Undo changes
        InfiniteOpt._set_core_variable_object(drv, var)
        _update_variable_param_refs(dinf4, IC.VectorTuple(par, par2, pars))
        # test removing single parameter that is reduced
        _update_variable_param_refs(dinf4, IC.VectorTuple(par, pars))
        @test eval_supports(drv) == Dict(2 => 0.5)
        @test isa(InfiniteOpt._update_reduced_variable(drv, 2:2), Nothing)
        @test infinite_variable_ref(drv) == inf4
        @test eval_supports(drv) == Dict{Int, Float64}()
        @test string(drv) == "inf4(par, [pars[1], pars[2]])"
        # Undo changes
        _update_variable_param_refs(dinf4, IC.VectorTuple(par, par2, pars))
        # test removing a different single parameter
        eval_supports(drv)[1] = 0.5
        eval_supports(drv)[2] = 0.5
        _update_variable_param_refs(dinf4, IC.VectorTuple(par, pars))
        @test isa(InfiniteOpt._update_reduced_variable(drv, 2:2), Nothing)
        @test infinite_variable_ref(drv) == inf4
        @test eval_supports(drv) == Dict(1 => 0.5)
        @test string(drv) == "inf4(0.5, [pars[1], pars[2]])"
        # Undo changes
        InfiniteOpt._set_core_variable_object(drv, var)
        _update_variable_param_refs(dinf4, IC.VectorTuple(par, par2, pars))
        # test removing array element
        eval_supports(drv)[3] = 0.2
        eval_supports(drv)[4] = 0.1
        _update_variable_param_refs(dinf4, IC.VectorTuple(par, par2))
        @test isa(InfiniteOpt._update_reduced_variable(drv, 3:4), Nothing)
        @test infinite_variable_ref(drv) == inf4
        @test eval_supports(drv) == Dict(2 => 0.5)
        @test set_name(drv, "") isa Nothing
        @test string(drv) == "inf4(par, 0.5)"
        # Undo changes
        var = build_variable(error, inf4, Dict{Int, Float64}(2 => 0.5), check = false)
        InfiniteOpt._set_core_variable_object(drv, var)
        _update_variable_param_refs(dinf4, IC.VectorTuple(par, par2, pars))
    end
    # test _update_measures
    @testset "_update_measures" begin
        @test InfiniteOpt._update_measures(m, par2) isa Nothing
        @test measure_function(dmref) == inf + par - x + rv + par3 + fin
        @test measure_function(dmref2) == zero(JuMP.GenericAffExpr{Float64, GeneralVariableRef})
        @test InfiniteOpt._object_numbers(dmref) == [2, 3, 4]
        @test InfiniteOpt._object_numbers(dmref2) == []
        @test InfiniteOpt._parameter_numbers(dmref) == [2, 3, 4, 5]
        @test InfiniteOpt._parameter_numbers(dmref2) == []
        # undo changes
        meas = Measure(inf + par - x + rv + par2 + par3 + fin, data, [2, 4], [2, 5], false)
        InfiniteOpt._set_core_variable_object(dmref, meas)
        meas = Measure(par2, data, [2], [2], false)
        InfiniteOpt._set_core_variable_object(dmref2, meas)
    end
    # test _update_constraints
    @testset "_update_constraints" begin
        @test InfiniteOpt._update_constraints(m, par2) isa Nothing
        @test jump_function(constraint_object(con)) == inf2 + inf4 + par3 + fin
        @test jump_function(constraint_object(con2)) == zero(JuMP.GenericAffExpr{Float64, GeneralVariableRef})
        @test isempty(setdiff(InfiniteOpt._object_numbers(con), [1, 2, 3, 4]))
        @test InfiniteOpt._object_numbers(con2) == []
        # undo changes
        constr = ScalarConstraint(inf2 + inf4 - par2 + par3 + fin, MOI.LessThan(0.))
        InfiniteOpt._set_core_constraint_object(con, constr)
        constr = ScalarConstraint(par2, MOI.GreaterThan(0.))
        InfiniteOpt._set_core_constraint_object(con2, constr)
    end
    # test _update_number_list
    @testset "_update_number_list" begin
        list = [1, 2, 3, 4, 5]
        @test InfiniteOpt._update_number_list([2, 3], list) isa Nothing
        @test list == [1, 2, 3]
        list = [1, 3, 4, 5]
        @test InfiniteOpt._update_number_list([2], list) isa Nothing
        @test list == [1, 2, 3, 4]
    end
    # test JuMP.delete for IndependentParameters
    @testset "JuMP.delete (IndependentParameterRef)" begin
        # test parameter function dependency
        push!(InfiniteOpt._parameter_function_dependencies(par2), ParameterFunctionIndex(1))
        @test_throws ErrorException delete(m, par2)
        popfirst!(InfiniteOpt._parameter_function_dependencies(par2))
        # add parameter function for object number updating
        pfunc = parameter_function(sin, par)
        # test normal usage
        @test isa(delete(m, par2), Nothing)
        @test !is_valid(m, par2)
        @test !is_valid(m, d1)
        @test measure_function(dmref) == inf + par - x + rv + par3 + fin
        @test measure_function(dmref2) == zero(JuMP.GenericAffExpr{Float64, GeneralVariableRef})
        @test parameter_refs(inf2) == (par,)
        @test parameter_refs(inf4) == (par, pars)
        @test parameter_values(pt2) == (0.5,)
        @test parameter_refs(rv) == (par, pars)
        @test string(inf2) == "inf2(par)"
        @test string(inf4) == "inf4(par, pars)"
        @test string(pt2) == "inf2(0.5)"
        @test set_name(rv, "") isa Nothing
        @test string(rv) == "inf4(par, [pars[1], pars[2]])"
        @test jump_function(constraint_object(con)) == inf2 + inf4 + par3 + fin
        @test jump_function(constraint_object(con2)) == zero(JuMP.GenericAffExpr{Float64, GeneralVariableRef})
        expected = [IndependentParameterIndex(1), DependentParametersIndex(1),
                    IndependentParameterIndex(3)]
        @test InfiniteOpt._param_object_indices(m) == expected
        @test InfiniteOpt._last_param_num(m) == 4
        @test InfiniteOpt._object_number(dpar) == 1
        @test InfiniteOpt._object_number(dpars[1]) == 2
        @test InfiniteOpt._object_number(dpar3) == 3
        @test InfiniteOpt._parameter_number(dpar3) == 4
        @test InfiniteOpt._parameter_number(dpars[2]) == 3
        @test InfiniteOpt._object_numbers(dinf2) == [1]
        @test InfiniteOpt._parameter_numbers(dinf4) == [1, 2, 3]
        @test isempty(setdiff(InfiniteOpt._object_numbers(inf3), [1, 2]))
        @test InfiniteOpt._parameter_numbers(dinf) == [1]
        @test isempty(setdiff(InfiniteOpt._object_numbers(drv), [1, 2]))
        @test InfiniteOpt._object_numbers(dmref) == [3]
        @test InfiniteOpt._parameter_numbers(dmref) == [4]
        @test isempty(setdiff(InfiniteOpt._object_numbers(con), [1, 2, 3]))
        @test isempty(InfiniteOpt._object_numbers(con2))
        # test special measure case with single parameter (possible through
        # multiple deletions) and with single parameter in constraint
        @test isa(delete(m, par3), Nothing)
        @test measure_function(dmref) == inf + par - x + rv + fin
        @test jump_function(constraint_object(con)) == inf2 + inf4 + fin
        @test isempty(setdiff(InfiniteOpt._object_numbers(con), [1, 2]))
        expected = [IndependentParameterIndex(1), DependentParametersIndex(1)]
        @test InfiniteOpt._param_object_indices(m) == expected
        @test InfiniteOpt._last_param_num(m) == 3
        @test InfiniteOpt._parameter_number(dpars[2]) == 3
        @test InfiniteOpt._object_numbers(dinf2) == [1]
        @test InfiniteOpt._parameter_numbers(dinf4) == [1, 2, 3]
        # test invalid parameter
        @test_throws AssertionError delete(m, par2)
        @test_throws AssertionError delete(m, par3)
        # test measure data check
        @test_throws ErrorException delete(m, par)
    end
    # test delete for finite parameters
    @testset "JuMP.delete (FiniteParameterRef)" begin
        # test first case
        @test delete(m, fin) isa Nothing
        @test measure_function(dmref) == inf + par - x + rv
        @test jump_function(constraint_object(con)) == inf2 + inf4
        @test objective_function(m) == zero(JuMP.GenericAffExpr{Float64, GeneralVariableRef})
        @test objective_sense(m) == MOI.FEASIBILITY_SENSE
        # test error
        @test_throws AssertionError delete(m, fin)
        # test different objective
        @objective(m, Min, fin2 + x + 1)
        @test delete(m, fin2) isa Nothing
        @test objective_function(m) == x + 1
        @test objective_sense(m) == MOI.MIN_SENSE
    end
 end

 # test deletion of dependent parameters
 @testset "Dependent Parameters" begin
     # initialize model
     m = InfiniteModel()
     # setup the parameters
     @infinite_parameter(m, 0 <= par <= 1)
     @infinite_parameter(m, 0 <= pars[1:2] <= 1)
     @infinite_parameter(m, 0 <= par2 <= 1)
     dpar = dispatch_variable_ref(par)
     dpars = dispatch_variable_ref.(pars)
     dpar2 = dispatch_variable_ref(par2)
     # setup the variables
     @infinite_variable(m, inf(par))
     @infinite_variable(m, inf2(par, par2))
     @infinite_variable(m, inf3(par, pars))
     @infinite_variable(m, inf4(par, par2, pars))
     @point_variable(m, inf(0.5), pt)
     pt2 = @point_variable(m, inf2(0.5, 0.5))
     @point_variable(m, inf3(0, [0, 0]), pt3)
     @hold_variable(m, x)
     var = build_variable(error, inf4, Dict{Int, Float64}(2 => 0.5, 3 => 0, 4 => 4),
                          check = false)
     rv = add_variable(m, var)
     dinf = dispatch_variable_ref(inf)
     dinf2 = dispatch_variable_ref(inf2)
     dinf3 = dispatch_variable_ref(inf3)
     dinf4 = dispatch_variable_ref(inf4)
     dpt = dispatch_variable_ref(pt)
     dpt2 = dispatch_variable_ref(pt2)
     dpt3 = dispatch_variable_ref(pt3)
     dx = dispatch_variable_ref(x)
     drv = dispatch_variable_ref(rv)
     # setup the measure
     data = TestData(par, 0, 1)
     mref = measure(inf + par - x + rv + pars[1], data)
     data = TestData(pars[2], 0, 1)
     mref2 = measure(inf4, data)
     dmref = dispatch_variable_ref(mref)
     dmref2 = dispatch_variable_ref(mref2)
     # setup the derivatives
     d1 = @deriv(inf3, pars[1])
     d2 = @deriv(inf3, pars[2])
     # setup the constraints
     @constraint(m, con, inf2 + inf4 - par2 + pars[1] + pars[2] <= 0)
     # test delete for dependent parameters
     @testset "JuMP.delete (DependentParameterRefs)" begin
         # test measure error
         @test_throws ErrorException delete(m, pars)
         mindex = index(dmref2)
         filter!(e -> e != mindex, InfiniteOpt._measure_dependencies(inf4))
         filter!(e -> e != mindex, InfiniteOpt._measure_dependencies(pars[2]))
         InfiniteOpt._delete_data_object(dmref2)
         # test parameter function dependency
         data = InfiniteOpt._data_object(first(pars))
         push!(data.parameter_func_indices, ParameterFunctionIndex(1))
         @test_throws ErrorException delete(m, pars)
         empty!(data.parameter_func_indices)
         # test regular
         @test delete(m, pars) isa Nothing
         @test !is_valid(m, d1)
         @test !is_valid(m, d2)
         @test parameter_refs(dinf) == (par,)
         @test parameter_refs(dinf3) == (par,)
         @test parameter_refs(dinf4) == (par, par2)
         @test string(dinf) == "inf(par)"
         @test string(dinf4) == "inf4(par, par2)"
         @test set_name(drv, "") isa Nothing
         @test string(drv) == "inf4(par, 0.5)"
         @test parameter_values(dpt3) == (0,)
         @test parameter_values(dpt2) == (0.5, 0.5)
         @test measure_function(dmref) == inf + par - x + rv
         @test jump_function(constraint_object(con)) == inf2 + inf4 - par2
         expected = [IndependentParameterIndex(1), IndependentParameterIndex(2)]
         @test InfiniteOpt._param_object_indices(m) == expected
         @test InfiniteOpt._last_param_num(m) == 2
         @test InfiniteOpt._object_number(dpar) == 1
         @test InfiniteOpt._object_number(dpar2) == 2
         @test InfiniteOpt._parameter_number(dpar2) == 2
         @test isempty(setdiff(InfiniteOpt._object_numbers(dinf2), [1, 2]))
         @test InfiniteOpt._parameter_numbers(dinf4) == [1, 2]
         @test InfiniteOpt._object_numbers(inf3) == [1]
         @test InfiniteOpt._parameter_numbers(dinf) == [1]
         @test InfiniteOpt._object_numbers(drv) == [1]
         @test InfiniteOpt._object_numbers(dmref) == []
         @test InfiniteOpt._parameter_numbers(dmref) == []
         @test isempty(setdiff(InfiniteOpt._object_numbers(con), [1, 2]))
         # test assertion error
         @test_throws AssertionError delete(m, pars)
     end
  end

 # Test reduced variable deletion
 @testset "JuMP.delete (Reduced Variables)" begin
     # intialize the model
     m = InfiniteModel()
     @infinite_parameter(m, 0 <= par <= 1)
     @infinite_parameter(m, 0 <= par2 <= 1)
     @infinite_variable(m, inf(par, par2))
     @point_variable(m, inf(0.5, 0.5), pt)
     @hold_variable(m, x)
     var = build_variable(error, inf, Dict{Int, Float64}(2 => 0.5), check = false)
     rv = add_variable(m, var)
     rv2 = add_variable(m, var)
     data = TestData(par, 0, 1)
     meas = measure(inf + par - x + rv, data)
     meas2 = measure(rv2, data)
     d1 = @deriv(rv, par)
     @constraint(m, con, x + rv <= 0)
     constr = ScalarConstraint(rv2, MOI.GreaterThan(0.))
     con2 = add_constraint(m, constr)
     # test normal deletion
     @test isa(delete(m, rv), Nothing)
     @test !is_valid(m, d1)
     @test measure_function(meas) == inf + par - x
     @test InfiniteOpt._object_numbers(meas) == [2]
     @test jump_function(constraint_object(con)) == x + 0
     @test InfiniteOpt._object_numbers(con) == []
     @test InfiniteOpt._reduced_variable_dependencies(inf) == [JuMP.index(rv2)]
     @test !haskey(InfiniteOpt._data_dictionary(m, ReducedVariable), JuMP.index(rv))
     # test deletion of special cases
     @test isa(delete(m, rv2), Nothing)
     @test measure_function(meas2) == zero(JuMP.GenericAffExpr{Float64, GeneralVariableRef})
     @test InfiniteOpt._object_numbers(meas2) == []
     @test jump_function(constraint_object(con2)) == zero(JuMP.GenericAffExpr{Float64, GeneralVariableRef})
     @test InfiniteOpt._object_numbers(con2) == []
     @test InfiniteOpt._reduced_variable_dependencies(inf) == []
     @test !haskey(InfiniteOpt._data_dictionary(m, ReducedVariable), JuMP.index(rv2))
     # test error
     @test_throws AssertionError delete(m, rv)
     @test_throws AssertionError delete(m, rv2)
 end

 # Test variable deletion
 @testset "JuMP.delete (Hold Variables)" begin
     # intialize the model
     m = InfiniteModel()
     @infinite_parameter(m, 0 <= par <= 1)
     @hold_variable(m, 0 <= x <= 1, Bin, parameter_bounds = (par == 0))
     @hold_variable(m, y == 1, Int)
     data = TestData(par, 0, 0)
     meas1 = measure(x + y + par, data)
     meas2 = measure(y, data)
     @constraint(m, con1, x + y + par <= 0)
     con2 = add_constraint(m, ScalarConstraint(y, MOI.LessThan(0.)))
     @objective(m, Min, x + y)
     # test deletion of x
     @test isa(delete(m, x), Nothing)
     @test num_constraints(m) == 4
     @test measure_function(meas1) == y + par
     @test jump_function(constraint_object(con1)) == y + par
     @test objective_function(m) == y + 0
     @test !haskey(InfiniteOpt._data_dictionary(m, HoldVariable), JuMP.index(x))
     # test deletion of y
     set_objective_function(m, y)
     @test isa(delete(m, y), Nothing)
     @test num_constraints(m) == 2
     @test measure_function(meas1) == par + 0
     @test measure_function(meas2) == zero(JuMP.GenericAffExpr{Float64, GeneralVariableRef})
     @test jump_function(constraint_object(con1)) == par + 0
     @test jump_function(constraint_object(con2)) == zero(JuMP.GenericAffExpr{Float64, GeneralVariableRef})
     @test objective_function(m) == zero(JuMP.GenericAffExpr{Float64, GeneralVariableRef})
     @test !haskey(InfiniteOpt._data_dictionary(m, HoldVariable), JuMP.index(y))
     # test errors
     @test_throws AssertionError delete(m, x)
     @test_throws AssertionError delete(m, y)
 end

 # Test variable deletion
 @testset "JuMP.delete (Point Variables)" begin
     # intialize the model
     m = InfiniteModel()
     @infinite_parameter(m, 0 <= par <= 1)
     @infinite_variable(m, inf(par))
     @point_variable(m, inf(0), 0 <= x <= 1, Bin)
     @point_variable(m, inf(1), y == 1, Int)
     data = TestData(par, 0, 1)
     meas1 = measure(x + y + par, data)
     meas2 = measure(y, data)
     @constraint(m, con1, x + y + par <= 0)
     con2 = add_constraint(m, ScalarConstraint(y, MOI.LessThan(0.)))
     @objective(m, Min, x + y)
     # test deletion of x
     @test isa(delete(m, x), Nothing)
     @test num_constraints(m) == 4
     @test measure_function(meas1) == y + par
     @test InfiniteOpt._object_numbers(meas1) == []
     @test jump_function(constraint_object(con1)) == y + par
     @test InfiniteOpt._object_numbers(con1) == [1]
     @test objective_function(m) == y + 0
     @test !haskey(InfiniteOpt._data_dictionary(m, PointVariable), JuMP.index(x))
     # test deletion of y
     set_objective_function(m, y)
     @test isa(delete(m, y), Nothing)
     @test num_constraints(m) == 2
     @test measure_function(meas1) == par + 0
     @test measure_function(meas2) == zero(JuMP.GenericAffExpr{Float64, GeneralVariableRef})
     @test jump_function(constraint_object(con1)) == par + 0
     @test jump_function(constraint_object(con2)) == zero(JuMP.GenericAffExpr{Float64, GeneralVariableRef})
     @test objective_function(m) == zero(JuMP.GenericAffExpr{Float64, GeneralVariableRef})
     @test !haskey(InfiniteOpt._data_dictionary(m, PointVariable), JuMP.index(y))
     # test errors
     @test_throws AssertionError delete(m, x)
     @test_throws AssertionError delete(m, y)
 end

 # Test variable deletion
 @testset "JuMP.delete (Infinite Variables)" begin
     # intialize the model
     m = InfiniteModel()
     @infinite_parameter(m, 0 <= par <= 1)
     @infinite_variable(m, 0 <= x(par) <= 1, Bin)
     @infinite_variable(m, y(par) == 1, Int)
     @point_variable(m, x(0), x0)
     var = build_variable(error, x, Dict{Int, Float64}(1 => 0.5), check = false)
     rv = add_variable(m, var)
     data = TestData(par, 0, 1)
     meas1 = measure(x + y + par, data)
     meas2 = measure(y, data)
     d1 = @deriv(x, par)
     @constraint(m, con1, x + y + par <= 0)
     con2 = add_constraint(m, ScalarConstraint(y, MOI.LessThan(0.)))
     # test deletion of x
     @test isa(delete(m, x), Nothing)
     @test num_constraints(m) == 4
     @test measure_function(meas1) == y + par
     @test InfiniteOpt._object_numbers(meas1) == []
     @test jump_function(constraint_object(con1)) == y + par
     @test InfiniteOpt._object_numbers(con1) == [1]
     @test InfiniteOpt._infinite_variable_dependencies(par) == [index(y)]
     @test !is_valid(m, rv)
     @test !is_valid(m, x0)
     @test !is_valid(m, d1)
     @test !haskey(InfiniteOpt._data_dictionary(m, InfiniteVariable), JuMP.index(x))
     # test deletion of y
     @test isa(delete(m, y), Nothing)
     @test num_constraints(m) == 2
     @test measure_function(meas1) == par + 0
     @test measure_function(meas2) == zero(JuMP.GenericAffExpr{Float64, GeneralVariableRef})
     @test InfiniteOpt._object_numbers(meas1) == []
     @test jump_function(constraint_object(con1)) == par + 0
     @test jump_function(constraint_object(con2)) == zero(JuMP.GenericAffExpr{Float64, GeneralVariableRef})
     @test InfiniteOpt._object_numbers(con1) == [1]
     @test InfiniteOpt._object_numbers(con2) == []
     @test InfiniteOpt._infinite_variable_dependencies(par) == []
     @test !haskey(InfiniteOpt._data_dictionary(m, InfiniteVariable), JuMP.index(y))
     # test errors
     @test_throws AssertionError delete(m, x)
     @test_throws AssertionError delete(m, y)
 end

 # Test derivative deletion
 @testset "JuMP.delete (Derivatives)" begin
    # intialize the model
    m = InfiniteModel()
    @infinite_parameter(m, 0 <= par <= 1)
    @infinite_variable(m, 0 <= x(par) <= 1, Bin)
    @infinite_variable(m, y(par) == 1, Int)
    d1 = @deriv(x, par)
    d2 = @deriv(y, par)
    d3 = @deriv(d1, par)
    @point_variable(m, d1(0), dx0)
    var = build_variable(error, d1, Dict{Int, Float64}(1 => 0.5), check = false)
    rv = add_variable(m, var)
    data = TestData(par, 0, 1)
    meas1 = measure(d1 + y + par, data)
    meas2 = measure(d2, data)
    @constraint(m, con1, d1 + d2 + par <= 0)
    con2 = add_constraint(m, ScalarConstraint(d2, MOI.LessThan(0.)))
    cref = @constraint(m, d1 == 0)
    push!(InfiniteOpt._derivative_constraint_dependencies(d1), index(cref))
    InfiniteOpt._set_has_derivative_constraints(par, true)
    # test deletion of d1
    @test isa(delete(m, d1), Nothing)
    @test num_constraints(m) == 7
    @test measure_function(meas1) == y + par
    @test InfiniteOpt._object_numbers(meas1) == []
    @test jump_function(constraint_object(con1)) == d2 + par
    @test InfiniteOpt._object_numbers(con1) == [1]
    @test InfiniteOpt._derivative_dependencies(par) == [index(d2)]
    @test !is_valid(m, rv)
    @test !is_valid(m, dx0)
    @test !is_valid(m, d3)
    @test !is_valid(m, cref)
    @test !haskey(InfiniteOpt._data_dictionary(m, Derivative), JuMP.index(d1))
    @test !has_derivative_constraints(par)
    @test !haskey(m.deriv_lookup, (x, par))
    # test deletion of d2
    @test isa(delete(m, d2), Nothing)
    @test num_constraints(m) == 7
    @test measure_function(meas1) == y + par
    @test measure_function(meas2) == zero(JuMP.GenericAffExpr{Float64, GeneralVariableRef})
    @test InfiniteOpt._object_numbers(meas1) == []
    @test jump_function(constraint_object(con1)) == par + 0
    @test jump_function(constraint_object(con2)) == zero(JuMP.GenericAffExpr{Float64, GeneralVariableRef})
    @test InfiniteOpt._object_numbers(con1) == [1]
    @test InfiniteOpt._object_numbers(con2) == []
    @test InfiniteOpt._derivative_dependencies(par) == []
    @test !haskey(InfiniteOpt._data_dictionary(m, Derivative), JuMP.index(d2))
    @test !haskey(m.deriv_lookup, (y, par))
    # test errors
    @test_throws AssertionError delete(m, d1)
    @test_throws AssertionError delete(m, d2)
 end

  # Test infinite parameter function deletion
 @testset "JuMP.delete (Parameter Function)" begin
     # intialize the model
     m = InfiniteModel()
     @infinite_parameter(m, 0 <= par <= 1)
     f = parameter_function(sin, par)
     data = TestData(par, 0, 0)
     meas1 = measure(f + par, data)
     meas2 = measure(f, data)
     @constraint(m, con1, f + par <= 0)
     con2 = add_constraint(m, ScalarConstraint(f, MOI.LessThan(0.)))
     d = deriv(f, par)
     rv = add_variable(m, build_variable(error, f, Dict(1 => 0.)))
     # test deletion of x
     @test isa(delete(m, f), Nothing)
     @test num_constraints(m) == 2
     @test measure_function(meas1) == par + 0
     @test measure_function(meas2) == zero(JuMP.GenericAffExpr{Float64, GeneralVariableRef})
     @test jump_function(constraint_object(con1)) == par + 0
     @test jump_function(constraint_object(con2)) == zero(JuMP.GenericAffExpr{Float64, GeneralVariableRef})
     @test !haskey(InfiniteOpt._data_dictionary(f), JuMP.index(f))
     @test !is_valid(m, f)
     @test !is_valid(m, d)
     @test !is_valid(m, rv)
     # test errors
     @test_throws AssertionError delete(m, f)
 end

 # Test variable deletion
 @testset "JuMP.delete (Measures)" begin
     # intialize the model
     m = InfiniteModel()
     @infinite_parameter(m, 0 <= par <= 1)
     @infinite_parameter(m, 0 <= par2 <= 1)
     @infinite_parameter(m, 0 <= pars[1:2] <= 1)
     @infinite_variable(m, w(pars))
     @infinite_variable(m, x(par))
     @infinite_variable(m, y(par2))
     @point_variable(m, x(0), x0)
     var = build_variable(error, x, Dict{Int, Float64}(1 => 0.5), check = false)
     rv = add_variable(m, var)
     data = TestData(par, 0, 1)
     data2 = TestData(pars, [0, 0], [1, 1])
     meas = measure(x, data)
     meas1 = measure(x + x0 + rv + par + meas, data)
     meas2 = measure(x + x0 + rv + par, data)
     meas3 = measure(meas1 + x0, data)
     meas4 = measure(meas2, data)
     meas5 = measure(w, data2)
     meas6 = measure(x + y, data)
     d1 = @deriv(meas6, par2)
     @constraint(m, con1, x0 + meas1 <= 0)
     con2 = add_constraint(m, ScalarConstraint(meas2, MOI.LessThan(0.)))
     @objective(m, Min, meas1 + x0)
     # test deletion of meas1
     @test isa(delete(m, meas1), Nothing)
     @test measure_function(meas3) == x0 + 0
     @test InfiniteOpt._object_numbers(meas3) == []
     @test jump_function(constraint_object(con1)) == x0 + 0
     @test InfiniteOpt._object_numbers(con1) == []
     @test objective_function(m) == x0 + 0
     @test InfiniteOpt._measure_dependencies(x) == [JuMP.index(meas), JuMP.index(meas2), JuMP.index(meas6)]
     @test InfiniteOpt._measure_dependencies(y) == [JuMP.index(meas6)]
     @test length(InfiniteOpt._measure_dependencies(par)) == 5
     @test InfiniteOpt._measure_dependencies(rv) == [JuMP.index(meas2)]
     @test !haskey(InfiniteOpt._data_dictionary(m, Measure), JuMP.index(meas1))
     # test deletion of meas2
     set_objective_function(m, meas2)
     @test isa(delete(m, meas2), Nothing)
     @test measure_function(meas4) == zero(JuMP.GenericAffExpr{Float64, GeneralVariableRef})
     @test InfiniteOpt._object_numbers(meas4) == []
     @test jump_function(constraint_object(con2)) == zero(JuMP.GenericAffExpr{Float64, GeneralVariableRef})
     @test InfiniteOpt._object_numbers(con2) == []
     @test objective_function(m) == zero(JuMP.GenericAffExpr{Float64, GeneralVariableRef})
     @test InfiniteOpt._measure_dependencies(x) == [JuMP.index(meas), JuMP.index(meas6)]
     @test InfiniteOpt._measure_dependencies(y) == [JuMP.index(meas6)]
     @test length(InfiniteOpt._measure_dependencies(par)) == 4
     @test InfiniteOpt._measure_dependencies(rv) == []
     @test !haskey(InfiniteOpt._data_dictionary(m, Measure), JuMP.index(meas2))
     # test deletion of meas5
     @test isa(delete(m, meas5), Nothing)
     @test InfiniteOpt._measure_dependencies(pars[1]) == []
     @test InfiniteOpt._measure_dependencies(pars[2]) == []
     # test deletion of meas6
     @test isa(delete(m, meas6), Nothing)
     @test !is_valid(m, d1)
     # test errors
     @test_throws AssertionError delete(m, meas1)
     @test_throws AssertionError delete(m, meas2)
 end


text:
### A Pluto.jl notebook ###
# v0.15.1

using Markdown
using InteractiveUtils

# ╔═╡ 86c233b6-0ac2-4869-a423-0336c837b73b
begin
	using Pkg
	Pkg.activate( "~/julia/vw/ScottishTaxBenefitModel" )
	Pkg.add( "BenchmarkTools" )
end

# ╔═╡ 4f30d000-ea1e-11eb-1a93-9be9c3779dc5
begin
	using Test
	using CSV
	using DataFrames
	using StatsBase
	using BenchmarkTools

	using ScottishTaxBenefitModel
	using ScottishTaxBenefitModel.GeneralTaxComponents
	using ScottishTaxBenefitModel.STBParameters
	using ScottishTaxBenefitModel.Runner:
		do_one_run
	using .RunSettings: Settings

	using .Utils
	include("../test/testutils.jl")
end

# ╔═╡ 1d044997-c2bb-4c7a-b372-474160b27fd5
begin

	settings = Settings()

	BenchmarkTools.DEFAULT_PARAMETERS.seconds = 120
	BenchmarkTools.DEFAULT_PARAMETERS.samples = 2

	function basic_run()::NamedTuple

		sys = [get_system(scotland=false), get_system( scotland=true )]
		results = do_one_run( settings, sys )
		return results
	end

end

# ╔═╡ 629ef4aa-0c3f-46bd-a7ea-4a06af43937c

# ╔═╡ 8eeec2d4-0b33-4883-aab1-79fb4051a196
begin
	res = basic_run()
	res.hh[1]
end

# ╔═╡ a06a02e6-3c01-4dd4-966f-0564cede93ff

# ╔═╡ Cell order:
# ╠═86c233b6-0ac2-4869-a423-0336c837b73b
# ╠═4f30d000-ea1e-11eb-1a93-9be9c3779dc5
# ╠═1d044997-c2bb-4c7a-b372-474160b27fd5
# ╠═629ef4aa-0c3f-46bd-a7ea-4a06af43937c
# ╠═8eeec2d4-0b33-4883-aab1-79fb4051a196
# ╠═a06a02e6-3c01-4dd4-966f-0564cede93ff

max_stars_repo_name: grahamstark/ScottishTaxBenefitModel

max_issues_repo_name: grahamstark/ScottishTaxBenefitModel

max_forks_repo_name: grahamstark/ScottishTaxBenefitModel


text:
# This file is a part of Julia. License is MIT: https://julialang.org/license

#
#  Test the pseudo-inverse
#

debug = false

using Base.Test

function hilb(T::Type, n::Integer)
    a=Array{T}(n,n)
    for i=1:n
        for j=1:n
            a[j,i]=one(T)/(i+j-one(T))
        end
    end
    return a
end
hilb(n::Integer) = hilb(Float64,n)

function hilb(T::Type, m::Integer, n::Integer)
    a=Array{T}(m,n)
    for i=1:n
        for j=1:m
            a[j,i]=one(T)/(i+j-one(T))
        end
    end
    return a
end
hilb(m::Integer, n::Integer) = hilb(Float64,m,n)

function onediag(T::Type, m::Integer, n::Integer)
    a=zeros(T,m,n)
    for i=1:min(n,m)
        a[i,i]=one(T)/(float(i)^5)
    end
    a[1,1] = 0
    a[min(m,n),min(m,n)] = 0
    return a
end
onediag(m::Integer, n::Integer) = onediag(Float64, m::Integer, n::Integer)

function onediag_sparse(T::Type, n::Integer)
    a=zeros(T,n)
    for i=1:n
        a[i]=one(T)/(float(i)^5)
    end
    a[1] = 0
    a[n] = 0
    return Diagonal(a)
end
onediag_sparse(n::Integer) = onediag_sparse(Float64, n::Integer)

function tridiag(T::Type, m::Integer, n::Integer)
    a=zeros(T,m,n)
    for i=1:min(n,m)
        a[i,i]=one(T)/(float(i)^5)
    end
    for i=1:min(n,m)-1
        a[i+1,i]=2*one(T)/(float(i)^5)
        a[1,i+1]=2*one(T)/(float(i)^5)
    end
    return a
end
tridiag(m::Integer, n::Integer) = tridiag(Float64, m::Integer, n::Integer)

function randn_float64(m::Integer, n::Integer)
    a=randn(m,n)
    b=Array{Float64}(m,n)
    for i=1:n
        for j=1:m
            b[j,i]=convert(Float64,a[j,i])
        end
    end
    return b
end

function randn_float32(m::Integer, n::Integer)
    a=randn(m,n)
    b=Array{Float32}(m,n)
    for i=1:n
        for j=1:m
            b[j,i]=convert(Float32,a[j,i])
        end
    end
    return b
end

function test_pinv(a,m,n,tol1,tol2,tol3)
    debug && println("=== julia/matlab pinv, default tol=eps(1.0)*max(size(a)) ===")
    apinv = @inferred pinv(a)

    @test vecnorm(a*apinv*a-a)/vecnorm(a) ≈ 0 atol=tol1
    x0 = randn(n); b = a*x0; x = apinv*b
    @test vecnorm(a*x-b)/vecnorm(b) ≈ 0 atol=tol1
    debug && println(vecnorm(a*apinv*a - a)/vecnorm(a))
    debug && println(vecnorm(a*x-b)/vecnorm(b))

    debug && println("=== julia pinv, tol=sqrt(eps(1.0)) ===")
    apinv = pinv(a,sqrt(eps(real(one(eltype(a))))))

    @test vecnorm(a*apinv*a-a)/vecnorm(a) ≈ 0 atol=tol2
    x0 = randn(n); b = a*x0; x = apinv*b
    @test vecnorm(a*x-b)/vecnorm(b) ≈ 0 atol=tol2
    debug && println(vecnorm(a*apinv*a - a)/vecnorm(a))
    debug && println(vecnorm(a*x-b)/vecnorm(b))
end

srand(12345)

let
    for eltya in (Float64, Complex128)

        debug && println("\n\n<<<<<", eltya, ">>>>>")

        m = 1000
        n = 100
        debug && println("\n\n n = ", n, ", m = ",m)

        default_tol = (real(one(eltya))) * max(m,n) * 10

        debug && println("\n--- dense/ill-conditioned matrix ---\n")
        ###    a = randn_float64(m,n) * hilb(eltya,n)
        a = hilb(eltya,m,n)
        test_pinv(a,m,n,1e-2,1e-5,1e-5)

        debug && println("\n--- dense/diagonal matrix ---\n")
        a = onediag(eltya,m,n)
        test_pinv(a,m,n,default_tol,default_tol,default_tol)

        debug && println("\n--- dense/tri-diagonal matrix ---\n")
        a = tridiag(eltya,m,n)
        test_pinv(a,m,n,default_tol,1e-5,default_tol)

        debug && println("\n--- Diagonal matrix ---\n")
        a = onediag_sparse(eltya,m)
        test_pinv(a,m,m,default_tol,default_tol,default_tol)

        m = 100
        n = 100
        debug && println("\n\n n = ", n, ", m = ",m)

        default_tol = (real(one(eltya))) * max(m,n) * 10

        debug && println("\n--- dense/ill-conditioned matrix ---\n")
        ###    a = randn_float64(m,n) * hilb(eltya,n)
        a = hilb(eltya,m,n)
        test_pinv(a,m,n,1e-2,1e-5,1e-5)

        debug && println("\n--- dense/diagonal matrix ---\n")
        a = onediag(eltya,m,n)
        test_pinv(a,m,n,default_tol,default_tol,default_tol)

        debug && println("\n--- dense/tri-diagonal matrix ---\n")
        a = tridiag(eltya,m,n)
        test_pinv(a,m,n,default_tol,1e-5,default_tol)

        debug && println("\n--- Diagonal matrix ---\n")
        a = onediag_sparse(eltya,m)
        test_pinv(a,m,m,default_tol,default_tol,default_tol)

        m = 100
        n = 1000
        debug && println("\n\n n = ", n, ", m = ",m)

        default_tol = (real(one(eltya))) * max(m,n) * 10

        debug && println("\n--- dense/ill-conditioned matrix ---\n")
    ###    a = randn_float64(m,n) * hilb(eltya,n)
        a = hilb(eltya,m,n)
        test_pinv(a,m,n,1e-2,1e-5,1e-5)

        debug && println("\n--- dense/diagonal matrix ---\n")
        a = onediag(eltya,m,n)
        test_pinv(a,m,n,default_tol,default_tol,default_tol)

        debug && println("\n--- dense/tri-diagonal matrix ---\n")
        a = tridiag(eltya,m,n)
        test_pinv(a,m,n,default_tol,1e-5,default_tol)

        debug && println("\n--- Diagonal matrix ---\n")
        a = onediag_sparse(eltya,m)
        test_pinv(a,m,m,default_tol,default_tol,default_tol)
    end
end

for eltya in (Float32, Complex64)

    debug && println("\n\n<<<<<", eltya, ">>>>>")

    m = 1000
    n = 100
    debug && println("\n\n n = ", n, ", m = ",m)

    default_tol = (real(one(eltya))) * max(m,n) * 10

    debug && println("\n--- dense/ill-conditioned matrix ---\n")
###    a = randn_float32(m,n) * hilb(eltya,n)
    a = hilb(eltya,m,n)
    test_pinv(a,m,n,1e0,1e-2,1e-2)

    debug && println("\n--- dense/diagonal matrix ---\n")
    a = onediag(eltya,m,n)
    test_pinv(a,m,n,default_tol,default_tol,default_tol)

    debug && println("\n--- dense/tri-diagonal matrix ---\n")
    a = tridiag(eltya,m,n)
    test_pinv(a,m,n,default_tol,1e-2,default_tol)

    debug && println("\n--- Diagonal matrix ---\n")
    a = onediag_sparse(eltya,m)
    test_pinv(a,m,m,default_tol,default_tol,default_tol)

    m = 100
    n = 100
    debug && println("\n\n n = ", n, ", m = ",m)

    default_tol = (real(one(eltya))) * max(m,n) * 10

    debug && println("\n--- dense/ill-conditioned matrix ---\n")
###    a = randn_float32(m,n) * hilb(eltya,n)
    a = hilb(eltya,m,n)
    test_pinv(a,m,n,1e0,1e-2,1e-2)

    debug && println("\n--- dense/diagonal matrix ---\n")
    a = onediag(eltya,m,n)
    test_pinv(a,m,n,default_tol,default_tol,default_tol)

    debug && println("\n--- dense/tri-diagonal matrix ---\n")
    a = tridiag(eltya,m,n)
    test_pinv(a,m,n,default_tol,1e-2,default_tol)

    debug && println("\n--- Diagonal matrix ---\n")
    a = onediag_sparse(eltya,m)
    test_pinv(a,m,m,default_tol,default_tol,default_tol)

    m = 100
    n = 1000
    debug && println("\n\n n = ", n, ", m = ",m)

    default_tol = (real(one(eltya))) * max(m,n) * 10

    debug && println("\n--- dense/ill-conditioned matrix ---\n")
###    a = randn_float32(m,n) * hilb(eltya,n)
    a = hilb(eltya,m,n)
    test_pinv(a,m,n,1e0,1e-2,1e-2)

    debug && println("\n--- dense/diagonal matrix ---\n")
    a = onediag(eltya,m,n)
    test_pinv(a,m,n,default_tol,default_tol,default_tol)

    debug && println("\n--- dense/tri-diagonal matrix ---\n")
    a = tridiag(eltya,m,n)
    test_pinv(a,m,n,default_tol,1e-2,default_tol)

    debug && println("\n--- Diagonal matrix ---\n")
    a = onediag_sparse(eltya,m)
    test_pinv(a,m,m,default_tol,default_tol,default_tol)

end

# test zero matrices
for eltya in (Float32, Float64, Complex64, Complex128)
    debug && println("\n\n<<<<<", eltya, ">>>>>")
    debug && println("\n--- zero constant ---")
    a = pinv(zero(eltya))
    @test a ≈ 0.0
end

for eltya in (Float32, Float64, Complex64, Complex128)
    debug && println("\n\n<<<<<", eltya, ">>>>>")
    debug && println("\n--- zero vector ---")
    a = pinv([zero(eltya); zero(eltya)])
    @test a[1] ≈ 0.0
    @test a[2] ≈ 0.0
end

for eltya in (Float32, Float64, Complex64, Complex128)
    debug && println("\n\n<<<<<", eltya, ">>>>>")
    debug && println("\n--- zero Diagonal matrix ---")
    a = pinv(Diagonal([zero(eltya); zero(eltya)]))
    @test a.diag[1] ≈ 0.0
    @test a.diag[2] ≈ 0.0
end

# test sub-normal matrices
for eltya in (Float32, Float64)
    debug && println("\n\n<<<<<", eltya, ">>>>>")
    debug && println("\n--- sub-normal constant ---")
    a = pinv(realmin(eltya)/100)
    @test a ≈ 0.0
    debug && println("\n\n<<<<<Complex{", eltya, "}>>>>>")
    debug && println("\n--- sub-normal constant ---")
    a = pinv(realmin(eltya)/100*(1+1im))
    @test a ≈ 0.0
end

for eltya in (Float32, Float64)
    debug && println("\n\n<<<<<", eltya, ">>>>>")
    debug && println("\n--- sub-normal vector ---")
    a = pinv([realmin(eltya); realmin(eltya)]/100)
    @test a[1] ≈ 0.0
    @test a[2] ≈ 0.0
    debug && println("\n\n<<<<<Complex{", eltya, "}>>>>>")
    debug && println("\n--- sub-normal vector ---")
    a = pinv([realmin(eltya); realmin(eltya)]/100*(1+1im))
    @test a[1] ≈ 0.0
    @test a[2] ≈ 0.0
end

for eltya in (Float32, Float64)
    debug && println("\n\n<<<<<", eltya, ">>>>>")
    debug && println("\n--- sub-normal Diagonal matrix ---")
    a = pinv(Diagonal([realmin(eltya); realmin(eltya)]/100))
    @test a.diag[1] ≈ 0.0
    @test a.diag[2] ≈ 0.0
    debug && println("\n\n<<<<<Complex{", eltya, "}>>>>>")
    debug && println("\n--- sub-normal Diagonal matrix ---")
    a = pinv(Diagonal([realmin(eltya); realmin(eltya)]/100*(1+1im)))
    @test a.diag[1] ≈ 0.0
    @test a.diag[2] ≈ 0.0
end

max_stars_repo_name: caodi/julia

max_issues_repo_name: caodi/julia

max_forks_repo_name: caodi/julia


text:
const sym2loader = Dict{Symbol,Vector{Symbol}}()
const sym2saver  = Dict{Symbol,Vector{Symbol}}()

is_installed(pkg::Symbol) = get(Pkg.installed(), string(pkg), nothing) != nothing

function _findmod(f::Symbol)
    for (u,v) in Base.loaded_modules
        (Symbol(v) == f) && return u
    end
    nothing
end
function topimport(modname)
    @eval Base.__toplevel__  import $modname
    u = _findmod(modname)
    @eval $modname = Base.loaded_modules[$u]
end

function checked_import(pkg::Symbol)
    # kludge for test suite
    if isdefined(Main, pkg)
        m1 = getfield(Main, pkg)
        isa(m1, Module) && return m1
    end
    if isdefined(FileIO, pkg)
        m1 = getfield(FileIO, pkg)
        isa(m1, Module) && return m1
    end
    m = _findmod(pkg)
    m == nothing || return Base.loaded_modules[m]
    topimport(pkg)
    return Base.loaded_modules[_findmod(pkg)]
end

for (applicable_, add_, dict_) in (
        (:applicable_loaders, :add_loader, :sym2loader),
        (:applicable_savers,  :add_saver,  :sym2saver))
    @eval begin
        function $applicable_(::Union{Type{DataFormat{sym}}, Formatted{DataFormat{sym}}}) where sym
            if haskey($dict_, sym)
                return $dict_[sym]
            end
            error("No $($applicable_) found for $(sym)")
        end
        function $add_(::Type{DataFormat{sym}}, pkg::Symbol) where sym
            list = get($dict_, sym, Symbol[])
            $dict_[sym] = push!(list, pkg)
        end
    end
end

"`add_loader(fmt, :Package)` triggers `using Package` before loading format `fmt`"
add_loader
"`add_saver(fmt, :Package)` triggers `using Package` before saving format `fmt`"
add_saver

"""
- `load(filename)` loads the contents of a formatted file, trying to infer
the format from `filename` and/or magic bytes in the file.
- `load(strm)` loads from an `IOStream` or similar object. In this case,
there is no filename extension, so we rely on the magic bytes for format
identification.
- `load(File(format"PNG", filename))` specifies the format directly, and bypasses inference.
- `load(Stream(format"PNG", io))` specifies the format directly, and bypasses inference.
- `load(f; options...)` passes keyword arguments on to the loader.
"""
load

"""
Some packages may implement a streaming API, where the contents of the file can
be read in chunks and processed, rather than all at once. Reading from these
higher-level streams should return a formatted object, like an image or chunk of
video or audio.

- `loadstreaming(filename)` loads the contents of a formatted file, trying to infer
the format from `filename` and/or magic bytes in the file. It returns a streaming
type that can be read from in chunks, rather than loading the whole contents all
at once
- `loadstreaming(strm)` loads the stream from an `IOStream` or similar object.
In this case, there is no filename extension, so we rely on the magic bytes
for format identification.
- `loadstreaming(File(format"WAV",filename))` specifies the format directly, and
bypasses inference.
- `loadstreaming(Stream(format"WAV", io))` specifies the format directly, and
bypasses inference.
- `loadstreaming(f; options...)` passes keyword arguments on to the loader.
"""
loadstreaming

"""
- `save(filename, data...)` saves the contents of a formatted file,
trying to infer the format from `filename`.
- `save(Stream(format"PNG",io), data...)` specifies the format directly, and bypasses inference.
- `save(File(format"PNG",filename), data...)` specifies the format directly, and bypasses inference.
- `save(f, data...; options...)` passes keyword arguments on to the saver.
"""
save

"""
Some packages may implement a streaming API, where the contents of the file can
be written in chunks, rather than all at once. These higher-level streams should
accept formatted objects, like an image or chunk of video or audio.

- `savestreaming(filename, data...)` saves the contents of a formatted file,
trying to infer the format from `filename`.
- `savestreaming(File(format"WAV",filename))` specifies the format directly, and
bypasses inference.
- `savestreaming(Stream(format"WAV", io))` specifies the format directly, and
bypasses inference.
- `savestreaming(f, data...; options...)` passes keyword arguments on to the saver.
"""
savestreaming

# if a bare filename or IO stream are given, query for the format and dispatch
# to the formatted handlers below
for fn in (:load, :loadstreaming, :save, :savestreaming, :metadata)
    @eval $fn(s::Union{AbstractString,IO}, args...; options...) =
        $fn(query(s), args...; options...)
end

# return a save function, so you can do `thing_to_save |> save("filename.ext")`
function save(s::Union{AbstractString,IO}; options...)
    data -> save(s, data; options...)
end

# Allow format to be overridden with first argument
function save(df::Type{DataFormat{sym}}, f::AbstractString, data...; options...) where sym
    libraries = applicable_savers(df)
    checked_import(libraries[1])
    Core.eval(Main, :($save($File($(DataFormat{sym}), $f),
                       $data...; $options...)))
end

function savestreaming(df::Type{DataFormat{sym}}, s::IO, data...; options...) where sym
    libraries = applicable_savers(df)
    checked_import(libraries[1])
    Core.eval(Main, :($savestreaming($Stream($(DataFormat{sym}), $s),
                                $data...; $options...)))
end

function save(df::Type{DataFormat{sym}}, s::IO, data...; options...) where sym
    libraries = applicable_savers(df)
    checked_import(libraries[1])
    Core.eval(Main, :($save($Stream($(DataFormat{sym}), $s),
                       $data...; $options...)))
end

function savestreaming(df::Type{DataFormat{sym}}, f::AbstractString, data...; options...) where sym
    libraries = applicable_savers(df)
    checked_import(libraries[1])
    Core.eval(Main, :($savestreaming($File($(DataFormat{sym}), $f),
                                $data...; $options...)))
end

# do-syntax for streaming IO
for fn in (:loadstreaming, :savestreaming)
    @eval function $fn(@nospecialize(f::Function), @nospecialize(args...); @nospecialize(kwargs...))
        str = $fn(args...; kwargs...)
        try
            f(str)
        finally
            close(str)
        end
    end
end

# Handlers for formatted files/streams

for fn in (:load, :loadstreaming, :metadata)
    @eval function $fn(@nospecialize(q::Formatted), @nospecialize(args...); @nospecialize(options...))
        if unknown(q)
            isfile(filename(q)) || open(filename(q))  # force systemerror
            throw(UnknownFormat(q))
        end
        libraries = applicable_loaders(q)
        failures  = Any[]
        for library in libraries
            try
                Library = checked_import(library)
                gen2_func_name = Symbol("fileio_" * $(string(fn)))
                if isdefined(Library, gen2_func_name)
                    return Core.eval(Library, :($gen2_func_name($q, $args...; $options...)))
                end
                if !has_method_from(methods(Library.$fn), Library)
                    throw(LoaderError(string(library), "$($fn) not defined"))
                end
                return Core.eval(Main, :($(Library.$fn)($q, $args...; $options...)))
            catch e
                push!(failures, (e, q))
            end
        end
        handle_exceptions(failures, "loading $(repr(filename(q)))")
    end
end

for fn in (:save, :savestreaming)
    @eval function $fn(@nospecialize(q::Formatted), @nospecialize(data...); @nospecialize(options...))
        unknown(q) && throw(UnknownFormat(q))
        libraries = applicable_savers(q)
        failures  = Any[]
        for library in libraries
            try
                Library = checked_import(library)
                gen2_func_name = Symbol("fileio_" * $(string(fn)))
                if isdefined(Library, gen2_func_name)
                    return Core.eval(Library, :($gen2_func_name($q, $data...; $options...)))
                end
                if !has_method_from(methods(Library.$fn), Library)
                    throw(WriterError(string(library), "$($fn) not defined"))
                end
                return Core.eval(Main, :($(Library.$fn)($q, $data...; $options...)))
            catch e
                push!(failures, (e, q))
            end
        end
        handle_exceptions(failures, "saving $(repr(filename(q)))")
    end
end

# returns true if the given method table includes a method defined by the given
# module, false otherwise
function has_method_from(mt, Library)
    for m in mt
        if getmodule(m) == Library
            return true
        end
    end
    false
end

getmodule(m) = m.module


text:
using AlphaZero

include("games.jl")
GAME = get(ENV, "GAME", "connect-four")
SelectedGame = GAME_MODULE[GAME]
using .SelectedGame: Game

const DEPTH = parse(Int, get(ENV, "DEPTH", "5"))

computer = MinMax.Player{Game}(depth=DEPTH, τ=0.2)

println("Profiling thinking time:")
AlphaZero.select_move(computer, Game())
@time AlphaZero.select_move(computer, Game())
println("")

interactive!(Game(), computer, Human{Game}())


text:
mgr = OdrManagerLite()
@test mgr.has_activated_position == false

a = 0x00
pos = Position(pointer_from_objref(a))
pos = 2 # delete ptr

# these should trigger warnings
@test isa(get_trackpos(mgr), Nothing)
@test isa(get_lanepos(mgr), Nothing)
@test isa(get_inertialpos(mgr), Nothing)
@test isa(get_footpoint(mgr), Nothing)

XODR_FILE = joinpath(Pkg.dir("OpenDriveManagerLite", "test"), "1lane.xodr")
@test loadfile(mgr, XODR_FILE)
printdata(mgr)

pos = create_position(mgr)
@test pos.ptr != C_NULL
@test mgr.has_activated_position == true

activate_position(mgr, pos)
@test mgr.has_activated_position == true
footpoint2inertial(mgr)
@test isa(get_footpoint(mgr), Coord)

@test get_trackpos(mgr) == init!(TrackCoord())

lanepos = get_lanepos(mgr)
@test lanepos.trackid == 0
@test isapprox(lanepos.s, 0.0)
@test isapprox(lanepos.t, 0.0)
@test isapprox(lanepos.z, 0.0)
@test isapprox(lanepos.h, 0.0)
@test lanepos.laneid == 0
@test isapprox(lanepos.offset, 0.0)

@test get_inertialpos(mgr) == init!(Coord())
# @test get_footpoint(mgr) == init!(Coord())

function check_pos(mgr, trackid, s, t, z_track, h_track, x, y, z_inertial, h_inertial)
    trackpos = get_trackpos(mgr)
    @test trackpos.trackid == trackid
    @test isapprox(trackpos.s, s, atol=1e-3)
    @test isapprox(trackpos.t, t, atol=1e-3)
    @test isapprox(trackpos.z, z_track, atol=1e-3)
    @test isapprox(trackpos.h, h_track, atol=1e-4)

    lanepos = get_lanepos(mgr)
    @test lanepos.trackid == trackid
    @test isapprox(lanepos.s, s, atol=1e-3)
    @test isapprox(lanepos.t, t, atol=1e-3)
    @test isapprox(lanepos.z, z_track, atol=1e-3)
    @test isapprox(lanepos.h, h_track, atol=1e-4)

    @test track2inertial(mgr)
    ipos = get_inertialpos(mgr)
    @test isapprox(ipos.x, x, atol=1e-3)
    @test isapprox(ipos.y, y, atol=1e-3)
    @test isapprox(ipos.z, z_inertial, atol=1e-3)
    @test isapprox(ipos.h, h_inertial, atol=1e-4)
end
function check_pos(mgr, trackid, s, t, z_track, h_track, laneid, offset,
                                 x, y, z_inertial, h_inertial)
    trackpos = get_trackpos(mgr)
    @test trackpos.trackid == trackid
    @test isapprox(trackpos.s, s, atol=1e-3)
    @test isapprox(trackpos.t, t, atol=1e-3)
    @test isapprox(trackpos.z, z_track, atol=1e-3)
    @test isapprox(trackpos.h, h_track, atol=1e-4)

    lanepos = get_lanepos(mgr)
    @test lanepos.trackid == trackid
    @test isapprox(lanepos.s, s, atol=1e-3)
    @test isapprox(lanepos.t, t, atol=1e-3)
    @test isapprox(lanepos.z, z_track, atol=1e-3)
    @test isapprox(lanepos.h, h_track, atol=1e-4)
    @test lanepos.laneid == laneid
    @test lanepos.offset == offset

    @test lane2inertial(mgr)
    ipos = get_inertialpos(mgr)
    @test isapprox(ipos.x, x, atol=1e-3)
    @test isapprox(ipos.y, y, atol=1e-3)
    @test isapprox(ipos.z, z_inertial, atol=1e-3)
    @test isapprox(ipos.h, h_inertial, atol=1e-4)
end
function check_lanepos(mgr, trackid, laneid, s, offset,
                            x, y, z_inertial, h_inertial)
    trackpos = get_trackpos(mgr)
    @test trackpos.trackid == trackid
    @test isapprox(trackpos.s, s, atol=1e-3)

    lanepos = get_lanepos(mgr)
    @test lanepos.trackid == trackid
    @test isapprox(lanepos.s, s, atol=1e-3)
    @test lanepos.laneid == laneid
    @test lanepos.offset == offset

    @test lane2inertial(mgr)
    ipos = get_inertialpos(mgr)
    @test isapprox(ipos.x, x, atol=1e-3)
    @test isapprox(ipos.y, y, atol=1e-3)
    @test isapprox(ipos.z, z_inertial, atol=1e-3)
    @test isapprox(ipos.h, h_inertial, atol=1e-4)
end

set_pos(mgr, TrackCoord(0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0))
check_pos(mgr, 0, 1.0, 2.0, 3.0, 4.0,
                  1.0, 2.0, 9.5, 4.0)

set_pos(mgr, TrackCoord(0, 10.0, 2.0, 3.0, 1.0, 5.0, 6.0))
check_pos(mgr, 0, 10.0, 2.0, 3.0, 1.0,
                  10.0, 2.0, 9.5, 1.0)

set_pos(mgr, TrackCoord(0, 2785.3981634, 500.0, 1.0, 0.0, 5.0, 6.0))
check_pos(mgr, 0, 2785.3981634, 500.0, 1.0, 0.0,
                  2000.0,       500.0, 9.5, pi/2)

set_pos(mgr, LaneCoord(0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, -1, 0.0))
check_pos(mgr, 0, 1.0, 2.0, 3.0, 4.0,
                  1.0, 2.0, 9.5, 4.0)

set_pos(mgr, LaneCoord(0, 10.0, 2.0, 3.0, 1.0, 5.0, 6.0, -1, 0.0))
check_pos(mgr, 0, 10.0, 2.0, 3.0, 1.0,
                  10.0, 2.0, 9.5, 1.0)

set_pos(mgr, LaneCoord(0, 2785.3981634, 500.0, 1.0, 0.0, 5.0, 6.0, -1, 0.0))
check_pos(mgr, 0, 2785.3981634, 500.0, 1.0, 0.0,
                  2000.0,       500.0, 9.5, pi/2)

set_trackpos(mgr, 0, 1.0, 2.0)
check_pos(mgr, 0, 1.0, 2.0, 1.0, 0.0,
                  1.0, 2.0, 9.5, 0.0)

set_trackpos(mgr, TrackCoord(0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0))
check_pos(mgr, 0, 1.0, 2.0, 3.0, 4.0,
                  1.0, 2.0, 9.5, 4.0)

set_trackpos(mgr, TrackCoord(0, 10.0, 2.0, 3.0, 1.0, 5.0, 6.0))
check_pos(mgr, 0, 10.0, 2.0, 3.0, 1.0,
                  10.0, 2.0, 9.5, 1.0)

set_trackpos(mgr, TrackCoord(0, 2785.3981634, 500.0, 1.0, 0.0, 5.0, 6.0))
check_pos(mgr, 0, 2785.3981634, 500.0, 1.0, 0.0,
                  2000.0,       500.0, 9.5, pi/2)

set_lanepos(mgr, LaneCoord(0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, -1, 0.0))
check_pos(mgr, 0, 1.0, 2.0, 3.0, 4.0, -1, 0.0,
                  1.0, -1.625, 9.5, 4.0)

set_lanepos(mgr, LaneCoord(0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, -1, 0.5))
check_pos(mgr, 0, 1.0, 2.0, 3.0, 4.0, -1, 0.5,
                  1.0, -1.625+0.5, 9.5, 4.0)

set_lanepos(mgr, 0, -1, 1.0, 0.0)
check_lanepos(mgr, 0, -1, 1.0, 0.0,
                      1.0, -1.625, 9.5, 4.0)

set_lanepos(mgr, 0, -1, 1.0, 0.5)
check_lanepos(mgr, 0, -1, 1.0, 0.5,
                  1.0, -1.625+0.5, 9.5, 4.0)

set_trackpos(mgr, 0, 0.0, 0.0)
@test track2inertial(mgr)
set_pos(mgr, Coord(1.0, 2.0, 3.0, 4.0, 5.0, 6.0))
@test inertial2track(mgr)
@test get_inertialpos(mgr) == Coord(1.0, 2.0, 3.0, 4.0, 5.0, 6.0)
pos = get_trackpos(mgr)
@test pos.trackid == 0
@test isapprox(pos.s, 1.0, atol=1e-3)
@test isapprox(pos.t, 2.0, atol=1e-3)

set_inertialpos(mgr, 1000.0, -1.0, 0.0)
@test inertial2track(mgr)

pos = get_inertialpos(mgr)
@test isapprox(pos.x, 1000.0, atol=1e-3)
@test isapprox(pos.y,   -1.0, atol=1e-3)
@test isapprox(pos.z,    0.0, atol=1e-3)

pos = get_trackpos(mgr)
@test pos.trackid == 0
@test isapprox(pos.s, 1000.0, atol=1e-3)
@test isapprox(pos.t,   -1.0, atol=1e-3)

@test inertial2lane(mgr)
pos = get_lanepos(mgr)
@test pos.trackid == 0
@test isapprox(pos.s, 1000.0, atol=1e-3)
@test isapprox(pos.t,   -1.0, atol=1e-3)
@test isapprox(pos.z,    9.5, atol=1e-3)
@test pos.laneid == -1
@test isapprox(pos.offset, 0.625)

set_inertialpos(mgr, 1000.0, -2.0, 0.0)
@test inertial2lane(mgr)
pos = get_lanepos(mgr)
@test pos.trackid == 0
@test isapprox(pos.s, 1000.0, atol=1e-3)
@test isapprox(pos.t,   -2.0, atol=1e-3)
@test isapprox(pos.z,    9.5, atol=1e-3)
@test pos.laneid == -1
@test isapprox(pos.offset, 0.625-1.0)

@test isapprox(get_curvature(mgr), 0.0, atol=1e-5)

set_inertialpos(mgr, 2500.0, 500.0, 0.0)
@test inertial2track(mgr)
@test isapprox(get_curvature(mgr), 1/500.0, atol=1e-5)

@test isapprox(get_track_len(mgr, 0), 2000.0*2 + 2*pi*500.0)
@test isapprox(get_lane_width(mgr), 3.25)

print_odrmanagerlite(mgr)

mgr = 2
gc()

max_stars_repo_name: sisl/OpenDriveManagerLite

max_issues_repo_name: sisl/OpenDriveManagerLite

max_forks_repo_name: sisl/OpenDriveManagerLite


text:
#!/usr/bin/julia

# Copyright (C) 2021, 2022 Matheus Fernandes Bigolin <mfrdrbigolin@disroot.org>
# SPDX-License-Identifier: MIT

"Day Two, Dive!"

include("Utils.jl")

using .Utils

const DIRS = Dict("forward" => 1, "down" => im, "up" => -im)

"""Return the product of the final horizontal position with the final depth,
according to the `commands`.  Consider the aiming with `is_aiming`."""
function solve(commands, is_aiming = false)
    coords = [DIRS[dir]*magn for (dir, magn) in commands]

    let pos = aim = 0
        for coord in coords
            if is_aiming
                aim += imag(coord)
                pos += real(coord) + real(coord)*aim*im
            else
                pos += coord
            end
        end

        return real(pos) * imag(pos)
    end
end

const INSTR_REG = r"(forward|down|up) (\d+)"

function main()
    usage_and_exit(length(ARGS) != 1)

    input_data = [match(INSTR_REG, dir).captures for dir in readlines(ARGS[1])]
    typed_data = [[dir, parse(Int, magn)] for (dir, magn) in input_data]

    println(solve(typed_data))
    println(solve(typed_data, true))
end

if abspath(PROGRAM_FILE) == @__FILE__
    main()
end


text:
# See estimate/posterior.jl for a test of the wrapper for dsgevar_likelihood that
# takes a DSGEVAR as an input.
fp = dirname(@__FILE__)
@testset "Likelihood function of DSGE-VAR p(Y | θ, λ)" begin
    matdata = load(joinpath(fp, "../../reference/test_dsgevar_likelihood.jld2"))

    # note that nobs in the Matlab code is T in the Julia code (n_observations)
    # and lambda is actually λ * T in the Julia code
    @test matdata["lnpy0"] ≈ DSGE.dsgevar_likelihood(matdata["YYYY"],
                                                matdata["XXYY"], matdata["XXXX"],
                                                matdata["yyyyd"], matdata["xxyyd"],
                                                matdata["xxxxd"], Int(matdata["nobs"]),
                                                matdata["lambda"] / matdata["nobs"])
    @test matdata["lnpyinf"] ≈ DSGE.dsgevar_likelihood(matdata["YYYY"],
                                                  matdata["XXYY"], matdata["XXXX"],
                                                  matdata["yyyyd"], matdata["xxyyd"],
                                                  matdata["xxxxd"], Int(matdata["nobs"]),
                                                  Inf)
    @test_throws DomainError matdata["lnpyinf"] ≈ DSGE.dsgevar_likelihood(matdata["YYYY"],
                                                  matdata["XXYY"], matdata["XXXX"],
                                                  matdata["yyyyd"], matdata["xxyyd"],
                                                  matdata["xxxxd"], Int(matdata["nobs"]),
                                                  -1.)
end


text:
_JULIET_EXISTS = try
    import Juliet
    true
end

function subscribe(event_name, fn_handler)
    !_JULIET_EXISTS && return

    event_sys = Main.Juliet.get_system(Main.Juliet.Event)
    Main.Juliet.Event.register_handler(event_sys, "epicenter-$event_name", fn_handler)
end

# -------

global variable_module = nothing
global mods_seen = Module[Core, Base, current_module()]

function lookup_variables(mod::Module)
	global variable_module

	if in(mod, mods_seen)
		return
	end
	push!(mods_seen, mod)

	for name in names(mod)
		if isa(mod.(name), Module)
			lookup_variables(mod.(name))
		else
			variable_module[name] = mod
		end
	end
end

function setparam(params...)
	global variable_module
	if variable_module == nothing
		variable_module = Dict()
		lookup_variables(Main)
	end
    for param in params
    	param_key = param[1]
    	param_string = string(param_key)
    	if contains(string(param_string), ".")
    		param_key = symbol(split(param_string, ".")[1])
    	end
    	eval(variable_module[param_key], :($(param[1]) = $(param[2])))
    end
end