text:
module TestWithBase

using Base.Iterators: flatten
using Baselet
using Test

args_and_kwargs(args...; kwargs...) = args, (; kwargs...)

==ᶜ(x, y) = collect(x) == collect(y)

# Dummy implementations
accumulate(op, xs::Tuple; kw...) = Tuple(Base.accumulate(op, collect(xs); kw...))
cumsum(xs::Tuple) = Tuple(Base.cumsum(collect(xs)))
cumprod(xs::Tuple) = Tuple(Base.cumprod(collect(xs)))

raw_testdata_pure = """
getindex((100, 200, 300, 400), 2:3) ==
zip((11, 22, 33)) ==ᶜ
zip((11, 22, 33), (111, 222, 333)) ==ᶜ
accumulate(+, (11, 22, 33)) ===
accumulate(+, (11, 22, 33); init=100) ===
cumsum((11, 22, 33)) ===
cumprod((11, 22, 33)) ===
enumerate((11, 22, 33)) ==ᶜ
flatten(((11, 22), (33, 44, 55))) ==ᶜ
any((false, false, false)) ===
any((false, true, false)) ===
any((false, true, false, missing)) ===
any((false, false, false, missing)) ===
any(==(0), (10, 11, 12)) ===
any(==(10), (10, 11, 12)) ===
any(==(0), (10, 11, 12, missing)) ===
any(==(10), (10, 11, 12, missing)) ===
all((true, true, true)) ===
all((true, false, true)) ===
all((true, true, true, missing)) ===
all((true, false, true, missing)) ===
all(==(0), (10, 10, 10)) ===
all(==(10), (10, 10, 10)) ===
all(==(0), (10, 10, 10, missing)) ===
all(==(10), (10, 10, 10, missing)) ===
findfirst(()) ==
findfirst((false, true)) ==
findfirst((false, false)) ==
findfirst(==(10), ()) ==
findfirst(==(10), (11, 10, 10)) ==
findfirst(==(10), (11, 11, 11)) ==
findlast(()) ==
findlast((false, true)) ==
findlast((false, false)) ==
findlast(==(10), ()) ==
findlast(==(10), (11, 10, 10)) ==
findlast(==(10), (11, 11, 11)) ==
findall(()) ==ᶜ
findall((false, true)) ==ᶜ
findall((false, false)) ==ᶜ
findall(==(10), ()) ==ᶜ
findall(==(10), (11, 10, 10)) ==ᶜ
findall(==(10), (11, 11, 11)) ==ᶜ
findmax((1, 2, 3, 2, 3, 1)) ===
findmax((1, NaN, 2, 3, NaN, 2)) ===
findmin((1, 2, 3, 2, 3, 1)) ===
findmin((1, NaN, 2, 3, NaN, 2)) ===
argmax((1, 2, 3, 2, 3, 1)) ===
argmax((1, NaN, 2, 3, NaN, 2)) ===
argmin((1, 2, 3, 2, 3, 1)) ===
argmin((1, NaN, 2, 3, NaN, 2)) ===
maximum((1, 2, 3, 2, 3, 1)) ===
maximum((1, NaN, 2, 3, NaN, 2)) ===
minimum((1, 2, 3, 2, 3, 1)) ===
minimum((1, NaN, 2, 3, NaN, 2)) ===
extrema((1, 2, 3, 2, 3, 1)) ===
extrema((1, NaN, 2, 3, NaN, 2)) ===
in(1, (1, 2, 3)) ===
in(0, (1, 2, 3)) ===
in(0, (1, 2, 3, missing)) ===
in(1, (1, 2, 3, missing)) ===
in(missing, (missing,)) ===
in(NaN, (NaN,)) ===
in(0.0, (-0.0,)) ===
unique((11, 12, 13)) ==ᶜ
unique((11, 11, 11)) ==ᶜ
unique(abs, (11, -12, 13, 12)) ==ᶜ
unique(abs, (11, -11, 11)) ==ᶜ
union((11, 12, 13)) ==ᶜ
union((11, 12, 13), (12, 13)) ==ᶜ
union((11, 12, 13), (12, 13, 14), (15, 13, 12)) ==ᶜ
intersect((11, 12, 13)) ==ᶜ
intersect((11, 12, 13), (12, 13)) ==ᶜ
intersect((11, 12, 13), (12, 13, 14), (15, 13, 12)) ==ᶜ
setdiff((11, 12, 13), ()) ==ᶜ
setdiff((), (11, 12, 13)) ==ᶜ
setdiff((11, 12, 13), (12, 13)) ==ᶜ
setdiff((11, 12, 13), (12, 13, 14), (15, 13, 12)) ==ᶜ
"""

# An array of `(label, (f, args, kwargs, comparison))`
testdata_pure = map(split(raw_testdata_pure, "\n", keepempty = false)) do x
    f, rest = split(x, "(", limit = 2)
    input, comparison = rsplit(rest, ")", limit = 2)
    comparison = strip(comparison)
    ex = Meta.parse("DUMMY($input)")
    ex.args[1] = args_and_kwargs
    @eval ($x, ($(Symbol(f)), $ex..., $(Symbol(comparison))))
end

@testset "$label" for (label, (f, args, kwargs, ==′)) in testdata_pure
    Baselet_f = getproperty(Baselet, nameof(f))
    Specialized_f = getproperty(Baselet.Specialized, nameof(f))
    @test Baselet_f(args...; kwargs...) ==′ f(args...; kwargs...)
    @test Specialized_f(args...; kwargs...) ==′ f(args...; kwargs...)
    @test typeof(Baselet_f(args...; kwargs...)) == typeof(Specialized_f(args...; kwargs...))
end

function test_all_implementations(test)
    @testset for m in [Base, Baselet, Baselet.Specialized]
        test(m)
    end
end

@testset "foreach(x -> push!(xs, x), 1:5)" begin
    test_all_implementations() do m
        xs = Int[]
        m.foreach(1:5) do x
            push!(xs, x)
        end
        @test xs == 1:5
    end
end

@testset "foreach(x -> push!(xs, x), (1, 2, 3))" begin
    test_all_implementations() do m
        xs = Int[]
        m.foreach((1, 2, 3)) do x
            push!(xs, x)
        end
        @test xs == 1:3
    end
end

@testset "foreach((a, b) -> push!(xs, a + b), 1:5, 6:10)" begin
    test_all_implementations() do m
        xs = Int[]
        m.foreach(1:5, 6:10) do a, b
            push!(xs, a + b)
        end
        @test xs == 7:2:15
    end
end

@testset "foreach((a, b) -> push!(xs, a + b), (1, 2, 3), (6, 7, 8))" begin
    test_all_implementations() do m
        xs = Int[]
        m.foreach((1, 2, 3), (6, 7, 8)) do a, b
            push!(xs, a + b)
        end
        @test xs == 7:2:11
    end
end

end  # module


text:
using LinearAlgebra
cd(@__DIR__)
D = KitBase.read_dict("t1_2f.txt")
set = KitBase.set_setup(D)
ps = KitBase.set_geometry(D)
vs = KitBase.set_velocity(D)
gas = KitBase.set_property(D)
begin
    primL = [1.0, KitBase.sound_speed(1.0, gas.γ) * gas.Ma, 0.0, 1.0]
    wL = KitBase.prim_conserve(primL, gas.γ)
    hL = KitBase.maxwellian(vs.u, vs.v, primL)
    bL = @. hL * gas.K / 2 / primL[end]

    fw = function (x, y, p)
        return wL
    end
    ff = function (x, y, p)
        h = maxwellian(vs.u, vs.v, primL)
        b = h * gas.K / 2 / primL[end]
        return h, b
    end
    bc = function (x, y, p)
        return primL
    end
    ib = KitBase.IB2F(fw, ff, bc, NamedTuple())
end
ks = KitBase.SolverSet(set, ps, vs, gas, ib)
ctr, face = KitBase.init_fvm(ks, ks.pSpace)
dt = KitBase.timestep(ks, ctr, 0.0)
nt = ks.set.maxTime ÷ dt |> Int
for iter = 1:nt
    KitBase.reconstruct!(ks, ctr)
    KitBase.evolve!(ks, ctr, face, dt)
    #=
    @inbounds for i in eachindex(face)
        vn = ks.vSpace.u .* face[i].n[1] .+ ks.vSpace.v .* face[i].n[2]
        vt = ks.vSpace.v .* face[i].n[1] .- ks.vSpace.u .* face[i].n[2]

        if !(-1 in ps.faceCells[i, :])
            KitBase.flux_kfvs!(
                face[i].fw,
                face[i].fh,
                face[i].fb,
                ctr[ps.faceCells[i, 1]].h,
                ctr[ps.faceCells[i, 1]].b,
                ctr[ps.faceCells[i, 2]].h,
                ctr[ps.faceCells[i, 2]].b,
                vn,
                vt,
                ks.vSpace.weights,
                dt,
                face[i].len,
            )
            face[i].fw .= KitBase.global_frame(face[i].fw, face[i].n[1], face[i].n[2])
        else
            idx = ifelse(ps.faceCells[i, 1] != -1, 1, 2)

            if ps.cellType[ps.faceCells[i, idx]] == 2
                bc = KitBase.local_frame(ks.ib.primR, face[i].n[1], face[i].n[2])

                KitBase.flux_boundary_maxwell!(
                    face[i].fw,
                    face[i].fh,
                    face[i].fb,
                    bc,
                    ctr[ps.faceCells[i, idx]].h,
                    ctr[ps.faceCells[i, idx]].b,
                    vn,
                    vt,
                    ks.vSpace.weights,
                    ks.gas.K,
                    dt,
                    face[i].len,
                )

                face[i].fw .= KitBase.global_frame(face[i].fw, face[i].n[1], face[i].n[2])
            end
        end
    end
    =#
    res = zeros(4)
    KitBase.update!(ks, ctr, face, dt, res)
    #=
    sumres = zeros(4)
    sumavg = zeros(4)
    @inbounds for i in eachindex(ctr)
        if ps.cellType[i] in (0, 2)
            dirc = [sign(dot(ctr[i].n[j], face[ps.cellFaces[i, j]].n)) for j = 1:3]

            KitBase.step!(
                ctr[i].w,
                ctr[i].prim,
                ctr[i].h,
                ctr[i].b,
                face[ps.cellFaces[i, 1]].fw,
                face[ps.cellFaces[i, 1]].fh,
                face[ps.cellFaces[i, 1]].fb,
                face[ps.cellFaces[i, 2]].fw,
                face[ps.cellFaces[i, 2]].fh,
                face[ps.cellFaces[i, 2]].fb,
                face[ps.cellFaces[i, 3]].fw,
                face[ps.cellFaces[i, 3]].fh,
                face[ps.cellFaces[i, 3]].fb,
                ks.vSpace.u,
                ks.vSpace.v,
                ks.vSpace.weights,
                ks.gas.K,
                ks.gas.γ,
                ks.gas.μᵣ,
                ks.gas.ω,
                ks.gas.Pr,
                ks.pSpace.cellArea[i],
                dirc,
                dt,
                sumres,
                sumavg,
                :bgk,
            )
        end
    end

    for i in eachindex(ps.cellType)
        if ps.cellType[i] == 3
            ids = ps.cellNeighbors[i, :]
            deleteat!(ids, findall(x -> x == -1, ids))
            id1, id2 = ids
            ctr[i].w .= 0.5 .* (ctr[id1].w .+ ctr[id2].w)
            ctr[i].h .= 0.5 .* (ctr[id1].h .+ ctr[id2].h)
            ctr[i].b .= 0.5 .* (ctr[id1].b .+ ctr[id2].b)
            ctr[i].prim .= KitBase.conserve_prim(ctr[i].w, ks.gas.γ)
        end
    end
    =#
end
KitBase.write_vtk(ks, ctr)

D = KitBase.read_dict("t1_1f.txt")
set = KitBase.set_setup(D)
begin
    primL = [1.0, KitBase.sound_speed(1.0, gas.γ) * gas.Ma, 0.0, 1.0]
    wL = KitBase.prim_conserve(primL, gas.γ)
    hL = KitBase.maxwellian(vs.u, vs.v, primL)
    fw = function (x, y, p)
        return wL
    end
    ff = function (x, y, p)
        h = maxwellian(vs.u, vs.v, primL)
        return h
    end
    bc = function (x, y, p)
        return primL
    end
    ib = KitBase.IB1F(fw, ff, bc, NamedTuple())
end
ks = KitBase.SolverSet(set, ps, vs, gas, ib, @__DIR__)
ctr, face = KitBase.init_fvm(ks, ks.pSpace)
KitBase.reconstruct!(ks, ctr)
KitBase.evolve!(ks, ctr, face, dt)
res = zeros(4)
KitBase.update!(ks, ctr, face, dt, res)

D = KitBase.read_dict("t1_0f.txt")
set = KitBase.set_setup(D)
ks = KitBase.SolverSet(set, ps, vs, gas, ib, @__DIR__)
ctr, face = KitBase.init_fvm(ks, ks.pSpace)
KitBase.reconstruct!(ks, ctr)
KitBase.evolve!(ks, ctr, face, dt)
res = zeros(4)
KitBase.update!(ks, ctr, face, dt, res)

ext: jl


text:
using AlgebraicDynamics.DWDDynam
using Catlab.WiringDiagrams
using Test

# Identity
A = [:A]
uf(u, x, p, t) = [x[1] - u[1]]
rf(u) = u
mf = ContinuousMachine{Float64}(1,1,1, uf, rf)

f = Box(:f, A, A)
d_id = singleton_diagram(f)
m_id = oapply(d_id, [mf])

x0 = 1
p0 = 200
@test eval_dynamics(m_id, [x0], [p0]) == [p0 - x0]
@test readout(m_id, [x0]) == [x0]

# unfed parameter
d12 = WiringDiagram(A, A)
f1 = add_box!(d12, f)
f2 = add_box!(d12, f)
add_wires!(d12, Pair[
    (f1, 1) => (f2, 1),
    (f2, 1) => (output_id(d12), 1)
])
m12 = oapply(d12, mf)

# composite
add_wire!(d12, (input_id(d12), 1) => (f1, 1))
m12 = oapply(d12, [mf, mf])

x0 = -1
y0 = 29
p0 = 200
@test eval_dynamics(m12, [x0, y0], [p0]) == [p0 - x0, x0 - y0]
@test readout(m12, [x0,y0]) == [y0]

# break and back together
d = WiringDiagram(A,A)
f1 = add_box!(d, f)
f2 = add_box!(d, f)
add_wires!(d, Pair[
    (input_id(d), 1) => (f1, 1),
    (input_id(d), 1) => (f2, 1),
    (f1, 1) => (output_id(d), 1),
    (f2, 1) => (output_id(d), 1)
])
m = oapply(d, Dict(:f => mf))

x0 = -1
y0 = 29
p0 = 200
@test eval_dynamics(m, [x0, y0], [p0]) == [p0 - x0, p0 - y0]
@test readout(m, [x0,y0]) == [x0 + y0]

@test m.ninputs == 1
@test m.nstates == 2
@test m.noutputs == 1

# trace
d_trace = WiringDiagram(A, A)
f1 = add_box!(d_trace, f)
add_wires!(d_trace, Pair[
    (input_id(d_trace), 1) => (f1, 1),
    (f1, 1) => (f1, 1),
    (f1, 1) => (output_id(d_trace), 1)
])
m_trace = oapply(d_trace, mf)
@test nstates(m_trace) == 1
@test eval_dynamics(m_trace, [x0], [p0]) == [p0]
@test readout(m_trace, [x0]) == [x0]

# oapply and ocompose
d_tot = ocompose(d, [d12, d_id])
m_tot1 = oapply(d_tot, mf)
m_tot2 = oapply(d, [m12, m_id])
x0 = [-1, 5.5, 20]
@test nstates(m_tot1) == 3
@test nstates(m_tot2) == 3

@test eval_dynamics(m_tot1, x0, [p0]) == eval_dynamics(m_tot2, x0, [p0])
@test eval_dynamics(m_tot1, x0, [p0]) == [p0 - x0[1], x0[1] - x0[2], p0 - x0[3]]

@test readout(m_tot1, x0) == [x0[2] + x0[3]]
@test readout(m_tot2, x0) == [x0[2] + x0[3]]

# big diagram
d = WiringDiagram([:A, :A], [:A, :A, :A])
b1 = add_box!(d, Box(:f, [:A, :A], [:A]))
b2 = add_box!(d, Box(:g, [:A], [:A, :A]))
b3 = add_box!(d, Box(:h, [:A], [:A]))

bin = input_id(d); bout = output_id(d)

add_wires!(d, Pair[
    (bin, 1) => (b1, 2),
    (bin, 1) => (b2, 1),
    (bin, 2) => (b3, 1),
    (b1, 1) => (bout, 1),
    (b2, 1) => (bout, 1),
    (b2, 1) => (bout, 2),
    (b2, 2) => (b2, 1),
    (b3, 1) => (b2, 1),
    (b3, 1) => (bout, 3)
])

m1 = ContinuousMachine{Float64}(2,1,1,
        (u, x, p, t) -> [x[1] * x[2]  - u[1]],
        u -> 2*u)
m2 = ContinuousMachine{Float64}(1, 2, 2,
        (u, x, p, t) -> [u[1]*u[2], x[1]^2*u[2]],
        u -> u)

m3 = ContinuousMachine{Float64}(1,2,1,
        (u, x, p, t) -> [u[1]^2 - x[1], u[2] - u[1]],
        u -> [u[1] + u[2]])

xs = Dict(:f => m1, :g => m2, :h => m3, :j => mf)
m = oapply(d, xs)
@test ninputs(m) == 2
@test nstates(m) == 5
@test noutputs(m) == 3
u = [2.0, 3.0, 5.0, -7.0, -0.5]
x = [0.1, 11.0]
@test eval_dynamics(m, u, x) ==
    [-u[1], u[2]*u[3], (x[1]+u[3]+u[4]+u[5])^2*u[3], u[4]^2 - x[2], u[5] - u[4]]
@test readout(m, u) == [2*u[1] + u[2], u[2], u[4] + u[5]]
@test readout(oapply(d_id, m3), [u[4], u[5]]) == [u[4] + u[5]]

# eulers
h = 0.15
euler_m = oapply(d, euler_approx([m1, m2, m3], h))
@test eval_dynamics(euler_m, u, x) == u + h*eval_dynamics(m, u, x)
@test eval_dynamics(euler_m, u, x) == eval_dynamics(euler_approx(m, h), u, x)
euler_m2 = oapply(d, euler_approx([m1, m2, m3]))
@test eval_dynamics(euler_m, u, x) == eval_dynamics(euler_m2, u, x, [h])

h = 0.02
xs = Dict(:h => m3, :f => m1, :g => m2)
euler_m = oapply(d, euler_approx(xs, h))
@test eval_dynamics(euler_m, u, x) == u + h*eval_dynamics(m, u, x)
@test eval_dynamics(euler_m, u, x) == eval_dynamics(euler_approx(m, h), u, x)
euler_m2 = oapply(d, euler_approx(xs))
@test eval_dynamics(euler_m, u, x) == eval_dynamics(euler_m2, u, x, [h])


text:
macro parameters(expr)
  expr = macroexpand(__module__, expr) # to expand @static
  expr isa Expr && expr.head == :struct || error("Invalid usage of @kwdef")
  T = expr.args[2]
  if T isa Expr && T.head == :<:
    T = T.args[1]
  end

  params_ex = Expr(:parameters)
  call_args = Any[]
  domains_vals = Any[]

  _parameters!(expr.args[3], params_ex.args, call_args, domains_vals)
  # Only define a constructor if the type has fields, otherwise we'll get a stack
  # overflow on construction
  if !isempty(params_ex.args)
    if T isa Symbol
      kwdefs = quote
        ($(esc(T)))($params_ex) = ($(esc(T)))($(call_args...))
        FreeParameters.domains(::Type{$(esc(T))}) =
          ($(domains_vals...),)
      end
    elseif T isa Expr && T.head == :curly
      # if T == S{A<:AA,B<:BB}, define two methods
      #   S(...) = ...
      #   S{A,B}(...) where {A<:AA,B<:BB} = ...
      S = T.args[1]
      P = T.args[2:end]
      Q = [U isa Expr && U.head == :<: ? U.args[1] : U for U in P]
      SQ = :($S{$(Q...)})
      kwdefs = quote
        ($(esc(S)))($params_ex) =($(esc(S)))($(call_args...))
        ($(esc(SQ)))($params_ex) where {$(esc.(P)...)} =
          ($(esc(SQ)))($(call_args...))
        FreeParameters.domains(::Type{$(esc(SQ))}) where {$(esc.(P)...)} =
          ($(domains_vals...),)
      end
    else
      error("Invalid usage of @parameters")
    end
  else
    kwdefs = nothing
  end
  quote
    Base.@__doc__($(esc(expr)))
    $kwdefs
  end
end

# @kwdef helper function
# mutates arguments inplace
function _parameters!(blk, params_args, call_args, domains_vals)
  for i in eachindex(blk.args)
    ei = blk.args[i]
    if ei isa Symbol
      #  var
      push!(params_args, ei)
      push!(call_args, ei)
      push!(domains_vals, Any)
    elseif ei isa Expr
      if ei.head == :(=)
        lhs = ei.args[1]
        if lhs isa Symbol
          #  var = defexpr [∈ domexpr]
          var = lhs
          T = Any
        elseif lhs isa Expr && lhs.head == :(::) && lhs.args[1] isa Symbol
          #  var::T = defexpr [∈ domexpr]
          var = lhs.args[1]
          T = lhs.args[2]
        else
          # something else, e.g. inline inner constructor
          #   F(...) = ...
          continue
        end
        rhs = ei.args[2]  # defexpr

        if rhs isa Expr && rhs.head == :call && rhs.args[1] in (:∈, :in)
          defexpr = rhs.args[2]
          domexpr = rhs.args[3]
        else
          defexpr = rhs
          domexpr = T
        end

        if domexpr isa Expr && domexpr.head == :tuple
          domexpr = :(RealDomain($(esc(domexpr.args[1])), $(esc(domexpr.args[1]))))
        else
          domexpr = esc(domexpr)
        end

        push!(params_args, Expr(:kw, var, esc(defexpr)))
        push!(call_args, var)
        push!(domains_vals, domexpr)

        blk.args[i] = lhs

      elseif ei.head == :call && ei.args[1] in (:∈, :in)
        lhs = ei.args[2]
        if lhs isa Symbol
          #  var ∈ domexpr
          var = lhs
        elseif lhs isa Expr && lhs.head == :(::) && lhs.args[1] isa Symbol
          #  var::T ∈ domexpr
          var = lhs.args[1]
        else
          # something else, e.g. inline inner constructor
          #   F(...)
          continue
        end
        domexpr = ei.args[3]

        if domexpr isa Expr && domexpr.head == :tuple
          domexpr = :(RealDomain($(esc(domexpr.args[1])), $(esc(domexpr.args[1]))))
        else
          domexpr = esc(domexpr)
        end

        push!(params_args, var)
        push!(call_args, var)
        push!(domains_vals, domexpr)

        blk.args[i] = lhs

      elseif ei.head == :(::) && ei.args[1] isa Symbol
        # var::Typ
        var = ei.args[1]
        push!(params_args, var)
        push!(call_args, var)
        push!(domains_vals, Any)
      elseif ei.head == :block
        # can arise with use of @static inside type decl
        _parameters!(ei, params_args, call_args, domains_vals)
      end
    end
  end
  blk
end


text:
using HypothesisTests
using Test
using DelimitedFiles
using StatsBase

@testset "Correlation" begin
    # Columns are line number, calcium, iron
    nutrient = readdlm(joinpath(@__DIR__, "data", "nutrient.txt"))[:, 1:3]
    w = CorrelationTest(nutrient[:,2], nutrient[:,3])
    let out = sprint(show, w)
        @test occursin("reject h_0", out) && !occursin("fail to", out)
    end
    let ci = confint(w)
        @test first(ci) ≈ 0.3327138 atol=1e-6
        @test last(ci) ≈ 0.4546639 atol=1e-6
    end
    @test nobs(w) == 737
    @test dof(w) == 735
    @test pvalue(w) < 1e-25

    x = CorrelationTest(nutrient[:,1], nutrient[:,2])
    @test occursin("fail to reject", sprint(show, x))
    let ci = confint(x)
        @test first(ci) ≈ -0.1105478 atol=1e-6
        @test last(ci) ≈ 0.0336730 atol=1e-6
    end
    @test pvalue(x) ≈ 0.2948405 atol=1e-6
end

@testset "Partial correlation" begin
    # Columns are information, similarities, arithmetic, picture completion
    wechsler = readdlm(joinpath(@__DIR__, "data", "wechsler.txt"))[:,2:end]
    w = CorrelationTest(wechsler[:,1], wechsler[:,2], wechsler[:,3:4])
    let out = sprint(show, w)
        @test occursin("reject h_0", out) && !occursin("fail to", out)
    end
    let ci = confint(w)
        @test first(ci) ≈ 0.4963917 atol=1e-6
        @test last(ci) ≈ 0.8447292 atol=1e-6
    end
    @test nobs(w) == 37
    @test dof(w) == 33
    @test pvalue(w) < 0.00001

    X = [ 2 1 0
          4 2 0
         15 3 1
         20 4 1]
    x = CorrelationTest(view(X,:,1), view(X,:,2), view(X,:,3))
    @test occursin("fail to reject", sprint(show, x))
    @test confint(x) == (-1.0, 1.0)
    @test nobs(x) == 4
    @test dof(x) == 1
    @test pvalue(x) ≈ 0.25776212 atol=1e-6
end


text:
using ModelingToolkit
using NonlinearSolve
using Test

@variables x y z u
@parameters σ ρ β

eqs = [0 ~ σ * (y - x),
    0 ~ x * (ρ - z) - y,
    0 ~ x * y - β * z]

par = [
    σ => 1,
    ρ => 0.1 + σ,
    β => ρ * 1.1,
]
u0 = [
    x => u,
    y => σ, # default u0 from default p
    z => u - 0.1,
]
ns = NonlinearSystem(eqs, [x, y, z], [σ, ρ, β], name = :ns, defaults = [par; u0])
ns.y = u * 1.1
resolved = ModelingToolkit.varmap_to_vars(Dict(), parameters(ns),
                                          defaults = ModelingToolkit.defaults(ns))
@test resolved == [1, 0.1 + 1, (0.1 + 1) * 1.1]

prob = NonlinearProblem(ns, [u => 1.0], Pair[])
@test prob.u0 == [1.0, 1.1, 0.9]
@show sol = solve(prob, NewtonRaphson())

@variables a
@parameters b
top = NonlinearSystem([0 ~ -a + ns.x + b], [a], [b], systems = [ns], name = :top)
top.b = ns.σ * 0.5
top.ns.x = u * 0.5

res = ModelingToolkit.varmap_to_vars(Dict(), parameters(top),
                                     defaults = ModelingToolkit.defaults(top))
@test res == [0.5, 1, 0.1 + 1, (0.1 + 1) * 1.1]

prob = NonlinearProblem(top, [states(ns, u) => 1.0, a => 1.0], [])
@test prob.u0 == [1.0, 0.5, 1.1, 0.9]
@show sol = solve(prob, NewtonRaphson())

# test NullParameters+defaults
prob = NonlinearProblem(top, [states(ns, u) => 1.0, a => 1.0])
@test prob.u0 == [1.0, 0.5, 1.1, 0.9]
@show sol = solve(prob, NewtonRaphson())

# test initial conditions and parameters at the problem level
pars = @parameters(begin
                       x0
                       t
                   end)
vars = @variables(begin x(t) end)
der = Differential(t)
eqs = [der(x) ~ x]
@named sys = ODESystem(eqs, t, vars, [x0])
pars = [
    x0 => 10.0,
]
initialValues = [
    x => x0,
]
tspan = (0.0, 1.0)
problem = ODEProblem(sys, initialValues, tspan, pars)
@test problem.u0 isa Vector{Float64}


text:
function GetModes(l,m,n,s; amax = 0.99, ϵ = 0.01, Nmax = 300)
    ##Initialize
    as = [a for a in 0.0:ϵ:amax]
    ωs = zero(im*(as))
    Almss = zero(im*(as))
    Cllss = zero([zero(22) for i in 1:length(as)])
    NCsize = 22; Nas = 100
    Cllss = zeros(Complex{Float64},NCsize,Nas)

    #Get Schwarzschild Modes
    ωsch, Almsch = SchwarzschildModes(l,n,s)

    ϵs = 0.0000001 #Finite difference step size

    P = ModeParameters((l=l,s=s,m=m,n=n,a=0.0,ω = ωsch,Alm = Almsch, Nmax = Nmax, lmax = 10))

    NmaxTrials = [100,300,500,1000,5_000,10_000,50_000]
    #NmaxTrials = [10,15,30,50,100,500,1000,5000]
    lmaxTrials = [10,12,15,15,20,22]

    for i =1:length(as)
        P.a = as[i]
        ω₀ = P.ω; Alm₀ = P.Alm
        ωnew = P.ω + 1.0; Almnew = Alm₀ + 1.0;
        iterations = 1;
        while ((abs(ωnew-ω₀) > 1e-10) | (abs(Almnew-Alm₀) > 1e-10)) & (iterations < 6)
            P.Nmax = NmaxTrials[iterations]
            P.lmax = lmaxTrials[iterations]
            ω₀ = P.ω; Alm₀ = P.Alm;
            Newton!(P,ϵs)
            ωnew = P.ω; Almnew = P.Alm
            iterations += 1
        end

        ωs[i] = P.ω
        Almss[i] = P.Alm
        _,Cll,_ = ComputeAₗₘ(P.s,P.m,P.a*P.ω, P.Alm,P.lmax)
        for j in length(Cll)
            for i in Nas
                Cllss[j,i]  = Cll[j]
            end
        end

    end
    as,ωs,Almss,Cllss,P, ϵ
end


text:
module SubsetSelectionCIO

using SubsetSelection, JuMP, Gurobi, CPLEX, MathOptInterface, LinearAlgebra, GLMNet

import Compat.String

include("inner_op.jl")

export oa_formulation

getthreads() = haskey(ENV, "SLURM_JOB_CPUS_PER_NODE") ? parse(Int, ENV["SLURM_JOB_CPUS_PER_NODE"]) : 0

###########################
# FUNCTION oa_formulation
###########################
"""Computes the minimum regression error with Ridge regularization subject an explicit
cardinality constraint using cutting-planes.

w^* := arg min  ∑_i ℓ(y_i, x_i^T w) +1/(2γ) ||w||^2
           st.  ||w||_0 = k

INPUTS
  ℓ           - LossFunction to use
  Y           - Vector of outputs. For classification, use ±1 labels
  X           - Array of inputs
  k           - Sparsity parameter
  γ           - ℓ2-regularization parameter
  indices0    - (optional) Initial solution
  ΔT_max      - (optional) Maximum running time in seconds for the MIP solver. Default is 60s
  gap         - (optional) MIP solver accuracy

OUTPUT
  indices     - Indicates which features are used as regressors
  w           - Regression coefficients
  Δt          - Computational time (in seconds)
  status      - Solver status at termination
  Gap         - Optimality gap at termination
  cutCount    - Number of cuts needed in the cutting-plane algorithm
  """
function oa_formulation(ℓ::LossFunction, Y, X, k::Int, γ;
          indices0=findall(rand(size(X,2)) .< k/size(X,2)),
          ΔT_max=60, verbose=false, Gap=0e-3, solver::Symbol=:Gurobi,
          rootnode::Bool=true, rootCuts::Int=20, stochastic::Bool=false)

  n,p = size(X)

  miop = (solver == :Gurobi) ? Model(Gurobi.Optimizer) : Model(CPLEX.Optimizer)
  set_optimizer_attribute(miop, (solver == :Gurobi) ? "TimeLimit" : "CPX_PARAM_TILIM", ΔT_max)
  set_optimizer_attribute(miop, (solver == :Gurobi) ? "OutputFlag" : "CPX_PARAM_SCRIND", 1*verbose)
  set_optimizer_attribute(miop, (solver == :Gurobi) ? "MIPGap" : "CPX_PARAM_EPGAP", Gap)
  set_optimizer_attribute(miop, (solver == :Gurobi) ? "Threads" : "CPXPARAM_Threads", getthreads())

  s0 = zeros(p); s0[indices0] .= 1.
  c0, ∇c0 = inner_op(ℓ, Y, X, s0, γ, stochastic=stochastic)

  # Optimization variables
  @variable(miop, s[j=1:p], Bin, start=s0[j])
  @variable(miop, t>=0, start=1.005*c0)

  for j in 1:p
    JuMP.set_start_value(s[j], s0[j])
  end
  JuMP.set_start_value(t, 1.005*c0)

  # Objective
  @objective(miop, Min, t)

  # Constraints
  @constraint(miop, sum(s) <= k)

  #Root node analysis
  cutCount=1; bestObj=sum(s0)<= k ? c0 : +Inf; bestSolution=sum(s0)<= k ? s0[:] : [] ;
  @constraint(miop, t>= c0 + dot(∇c0, s-s0))

  if rootnode
    s1 = zeros(p)
    l1 = isa(ℓ, SubsetSelection.Classification) ? glmnet(X, convert(Matrix{Float64}, [(Y.<= 0) (Y.>0)]), GLMNet.Binomial(), dfmax=k, intercept=false) : glmnet(X, Y, dfmax=k, intercept=false)
    for  i in size(l1.betas, 2):-1:max(size(l1.betas, 2)-rootCuts,1) #Add first rootCuts cuts from Lasso path
      ind = findall(abs.(l1.betas[:, i]) .> 1e-8); s1[ind] .= 1.
      c1, ∇c1 = inner_op(ℓ, Y, X, s1, γ, stochastic=stochastic)
      @constraint(miop, t>= c1 + dot(∇c1, s-s1))
      cutCount += 1; s1 .= 0.
    end
  end

  # Outer approximation method for Convex Integer Optimization (CIO)
  function outer_approximation(cb_data)
    s_val = [callback_value(cb_data, s[j]) for j in 1:p] #vectorized version of callback_value is not currently offered in JuMP
    # if maximum(s_val.*(1 .- s_val)) < 10*eps()
      s_val = 1.0 .* (rand(p) .< s_val) #JuMP updates calls Lazy Callbacks at fractional solutions as well

      c, ∇c = inner_op(ℓ, Y, X, s_val, γ, stochastic=stochastic)
      if stochastic && callback_value(cb_data, t) > c #If stochastic version and did not cut the solution
          c, ∇c = inner_op(ℓ, Y, X, s_val, γ, stochastic=false)
      end
      if sum(s_val)<=k && c<bestObj #if feasible and best value
        bestObj = c; bestSolution=s_val[:]
      end

      con = @build_constraint(t >= c + dot(∇c, s-s_val))
      MOI.submit(miop, MOI.LazyConstraint(cb_data), con)
      cutCount += 1
    # end
  end
  MOI.set(miop, MOI.LazyConstraintCallback(), outer_approximation)

  # # Feed warmstart
  # if (solver == :Gurobi)
  #   wsCount = 0
  #   function warm_start(cb_data)
  #     if wsCount == 0
  #       MOI.submit(miop, MOI.HeuristicSolution(cb_data), [s[j] for j in 1:p], floor.(Int, s0))
  #       MOI.submit(miop, MOI.HeuristicSolution(cb_data), [t], [c0])
  #       wsCount += 1
  #     end
  #   end
  #   MOI.set(miop, MOI.HeuristicCallback(), warm_start)
  # end

  t0 = time()
  optimize!(miop)
  status = termination_status(miop)
  Δt = JuMP.solve_time(miop)

  Gap = 1 - JuMP.objective_bound(miop) /  abs(JuMP.objective_value(miop))
  if JuMP.objective_bound(miop) < bestObj
    bestSolution = value.(s)[:]
  end

  # Find selected regressors and run a standard linear regression with Tikhonov regularization
  indices = findall(bestSolution .> .5)
  w = SubsetSelection.recover_primal(ℓ, Y, X[:, indices], γ)

  return indices, w, Δt, status, Gap, cutCount
end

end # module


text:
module Logistic

using RecordedArrays
using Random
using Test
using EvolutionaryModelingTools

const c = ContinuousClock(100.0) # define a clock, the population will growth for 100 time unit

const r = 0.5
const d = 0.1
const K = 100
const n = recorded(DynamicEntry, c, 10)   # define a scalar to record population size

# simulate with this package

Random.seed!(1)

@cfunc growth_c(r, n) = r * n
@ufunc growth_u!(ind, n) = n[ind.I...] += 1 # ensure the indexing is correct

@cfunc death_c(d, n) = d * n
@ufunc death_u!(ind, n) = n[ind.I...] -= 1 # ensure the indexing is correct

@cfunc comp_c(r, K, n) = r * n * n / K
@ufunc comp_u!(ind::CartesianIndex{0}, n) = n[ind] -= 1

# the ind must be CartesianIndex{0}, this is just for test
@ufunc check_extinction(ind::CartesianIndex{0}, n) = n[ind] == 0 ? :extinct : :finnish # check

growth = Reaction(growth_c, growth_u!)
death = Reaction(death_c, death_u!)
competition = Reaction(comp_c, comp_u!)

ps = (; r, d, K, n)
rs = (growth, death, competition)

e1 = getentries(gillespie(check_extinction, c, ps, rs)[1].n)

# simulate manually

Random.seed!(1)

for _ in c
    global n
    # evaluate a_i
    growth_rate = r * n              # intrinsic growth
    death_rate = d * n               # intrinsic death
    competition_rate = r * n * n / K # resource competition

    summed = growth_rate + death_rate + competition_rate  # sum a_i

    τ = -log(rand()) / summed # compute time interval

    increase!(c, τ) # update current time

    # sample a reaction and adjust population size
    rn = rand() * summed
    if rn < growth_rate
        n[1] += 1
    else
        n[1] -= 1
    end

    state(n) <= 0 && break # break if population extinct
end

e2 = getentries(n)

@test getts(e1) == getts(e2)
@test getvs(e1) == getvs(e2)

end


text:
include("../src/Model.jl")
using Plots

using ModelingToolkit
using Calculus
using ForwardDiff
using OrdinaryDiffEq
using DifferentialEquations
##

## Use Functor

n = 10000
p1 = LinRange(0.001, 10, n)
out = zeros(n)

@time for (c, i) in enumerate(p1)
    R= Model.positive_feedback(s=i)
    prob = SteadyStateProblem(R, 0.0)

    #prob = ODEProblem(R, R.x, (0.0,100.0))
    local sol = solve(prob, DynamicSS(Rosenbrock23()))
    out[c] = sol.u
end

plot(p1, out)
plot!(xaxis=:log)

##

@parameters t s kK kA m x_50 x_tot kp
@variables x(t)
@derivatives D'~t

s = Model.positive_feedback(x,s, kK, kA, m, x_50, x_tot, kp)

dx = s(x, nothing, nothing)


text:
# Define several base scenarios derived from the large urban environment

# ego + 2 cars
const TwoCars = UrbanPOMDP(max_cars=2, max_peds=0, max_obstacles=0, car_birth=0.9, ped_birth=0.9)

# ego + 1 ped + 1 car
const PedCar = UrbanPOMDP(max_cars=1, max_peds=1, max_obstacles=0, car_birth=0.9, ped_birth=0.9)

# ego + 1 ped + 1 obstacle
const ObsPed = UrbanPOMDP(max_cars=0, max_peds=1, max_obstacles=1, car_birth=0.9, ped_birth=0.9)

# ego + 1 car + 1 obstacle
const ObsCar = UrbanPOMDP(max_cars=1, max_peds=0, max_obstacles=1, car_birth=0.9, ped_birth=0.9)

# Wrappers
@with_kw struct TwoCarsScenario
    problem::UrbanPOMDP = TwoCars
end

@with_kw struct PedCarScenario
    problem::UrbanPOMDP = PedCar
end

@with_kw struct ObsPedScenario
    problem::UrbanPOMDP = ObsPed
end

@with_kw struct ObsCarScenario
    problem::UrbanPOMDP = ObsCar
end

### Extract input

# return a list of tuple (pb_id, pb_input)
function get_problem_input(ego::Vector{Float64},
                           car_map::OrderedDict{String, Vector{Float64}},
                           ped_map::OrderedDict{String, Vector{Float64}},
                           obs_map::OrderedDict{String, Vector{Float64}})
    inputs = Tuple{Symbol, Vector{Float64}}[]
    # build obs ped
    for (ped, ped_state) in ped_map
        obs_states = []
        for (obs, obs_state) in obs_map
            push!(obs_states, obs_state)

        end
        feature_vec = vcat(ego, ped_state, obs_states...)
        push!(inputs, (:obsped, feature_vec))
    end

    # build obs car
    for (car, car_state) in car_map
        obs_states = []
        for (obs, obs_state) in obs_map
            push!(obs_states, obs_state)
        end
        feature_vec = vcat(ego, car_state, obs_states...)
        push!(inputs, (:obscar, feature_vec))
    end

    # build ped car
    for (ped, ped_state) in ped_map
        for (car, car_state) in car_map
            feature_vec = vcat(ego, car_state, ped_state)
            push!(inputs, (:pedcar, feature_vec))
        end
    end

    # build twocars
     for (car, car_state) in car_map
        for (car, car_state) in car_map
            feature_vec = vcat(ego, car_state, car_state)
            push!(inputs, (:twocars, feature_vec))
        end
    end
    return inputs
end

function decompose_input(pomdp::UrbanPOMDP, o::Vector{Float64})
    ego, car_map, ped_map, obs_map = split_o(o, pomdp)
    inputs = get_problem_input(ego, car_map, ped_map, obs_map)
    return inputs
end

max_stars_repo_name: MaximeBouton/AutomotivePOMDPs

max_issues_repo_name: MaximeBouton/AutomotivePOMDPs

max_forks_repo_name: MaximeBouton/AutomotivePOMDPs


text:
using Cairo
using Maple
using Glob
import JSON

include("extract_sprites_images.jl")
include("extract_sprites_meta.jl")

atlases = ARGS[1]
atlas = ARGS[3]
dest = "$(ARGS[2])/$(atlas)"

mkpath(dest)

dataFiles = vcat(glob("$(atlas)/*.data", atlases), glob("$(atlas)?.data", atlases))

sprites = Dict{String, Sprite}()
encodedSprites = Dict{String, Any}()

for data in dataFiles
  png = "$(dest)/$(splitext(basename(data))[1]).png"
  dumpSprites(data, png)
  sprites = merge(sprites, loadSprites("$(atlases)/$(atlas).meta", png))
end

println(join(keys(sprites), ", "))

for spriteName in keys(sprites)
  sprite = sprites[spriteName]

  originalSurface = sprite.surface

  @printf "%s => height = %d, width = %d, offsetX = %d, offsetY = %d, x = %d, y = %d, realWidth = %d, realHeight = %d, filename = %s\n" spriteName sprite.height sprite.width sprite.offsetX sprite.offsetY sprite.x sprite.y sprite.realWidth sprite.realHeight sprite.filename

  rawSpriteSurface = CairoARGBSurface(sprite.width, sprite.height)
  spriteSurface = CairoARGBSurface(sprite.width, sprite.height)

  ctx = CairoContext(rawSpriteSurface)

  set_source_surface(ctx, originalSurface, -sprite.x, -(sprite.y/2))

  paint(ctx)

  newCtx = CairoContext(spriteSurface)
  scale(newCtx, 1, 2)
  set_source_surface(newCtx, rawSpriteSurface, 0, 0)

  paint(newCtx)

  write_to_png(spriteSurface, "$(dest)/$(spriteName).png")

  spriteJson = Dict{String, Any}()

  spriteJson["width"] = sprite.width
  spriteJson["height"] = sprite.height
  spriteJson["offsetX"] = sprite.offsetX
  spriteJson["offsetY"] = sprite.offsetY
  spriteJson["x"] = sprite.x
  spriteJson["y"] = sprite.y
  spriteJson["realWidth"] = sprite.realWidth
  spriteJson["realHeight"] = sprite.realHeight
  spriteJson["filename"] = sprite.filename

  encodedSprites[spriteName] = spriteJson
end

json = JSON.json(encodedSprites)

open("$(dest)/$(atlas).json", "w") do f
    write(f, json)
end

max_stars_repo_name: npdmfixup/Fuji

max_issues_repo_name: npdmfixup/Fuji

max_forks_repo_name: npdmfixup/Fuji


text:
#=
Copyright (c) 2016 Saurav Sachidanand

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
=#

function decode_unsigned(start_idx, bytes::Array{UInt8, 1})
    const addntl_info = bytes[start_idx] & ADDNTL_INFO_MASK

    if addntl_info < SINGLE_BYTE_UINT_PLUS_ONE
        return addntl_info, sizeof(UInt8)
    elseif addntl_info == ADDNTL_INFO_UINT8
        const data = zero(UInt8)
        const byte_len = sizeof(UInt8)
    elseif addntl_info == ADDNTL_INFO_UINT16
        const data = zero(UInt16)
        const byte_len = sizeof(UInt16)
    elseif addntl_info == ADDNTL_INFO_UINT32
        const data = zero(UInt32)
        const byte_len = sizeof(UInt32)
    elseif addntl_info == ADDNTL_INFO_UINT64
        const data = zero(UInt64)
        const byte_len = sizeof(UInt64)
    end

    for i in 1:byte_len
        data <<= BITS_PER_BYTE
        data |= bytes[start_idx + i]
    end

    return data, byte_len + 1
end

function decode_next_indef(start_idx, bytes::Array{UInt8, 1}, typ::UInt8,
                           with_iana::Bool)
    bytes_consumed = 1

    if typ == TYPE_2
        byte_string = UInt8[]
        while bytes[start_idx + bytes_consumed] != BREAK_INDEF
            sub_byte_string, sub_bytes_consumed =
                decode_next(start_idx + bytes_consumed, bytes, with_iana)
            bytes_consumed += sub_bytes_consumed

            push!(byte_string, sub_byte_string)
        end
        const data = byte_string
    elseif typ == TYPE_3
        buf = IOBuffer()
        while bytes[start_idx + bytes_consumed] != BREAK_INDEF
            sub_utf8_string, sub_bytes_consumed =
                decode_next(start_idx + bytes_consumed, bytes, with_iana)
            bytes_consumed += sub_bytes_consumed

            write(buf, sub_utf8_string)
        end
        const data = takebuf_string(buf)
    elseif typ == TYPE_4
        vec = Vector()
        while bytes[start_idx + bytes_consumed] != BREAK_INDEF
            item, sub_bytes_consumed =
                decode_next(start_idx + bytes_consumed, bytes, with_iana)
            bytes_consumed += sub_bytes_consumed

            push!(vec, item)
        end
        const data = vec
    elseif typ == TYPE_5
        dict = Dict()
        while bytes[start_idx + bytes_consumed] != BREAK_INDEF
            key, sub_bytes_consumed =
                decode_next(start_idx + bytes_consumed, bytes, with_iana)
            bytes_consumed += sub_bytes_consumed

            value, sub_bytes_consumed =
                decode_next(start_idx + bytes_consumed, bytes, with_iana)
            bytes_consumed += sub_bytes_consumed

            dict[key] = value
        end
        const data = dict
    end

    bytes_consumed += 1

    return data, bytes_consumed
end

function decode_next(start_idx, bytes::Array{UInt8, 1}, with_iana::Bool)
    const first_byte = bytes[start_idx]
    const typ = first_byte & TYPE_BITS_MASK

        if typ == TYPE_0
            data, bytes_consumed = decode_unsigned(start_idx, bytes)

        elseif typ == TYPE_1
            data, bytes_consumed = decode_unsigned(start_idx, bytes)
            if (i = Int128(data) + 1) > typemax(Int64)
                data = -i
            else
                data = -(Signed(data) + 1)
            end

        elseif typ == TYPE_6
            tag, bytes_consumed = decode_unsigned(start_idx, bytes)

            function retrieve_plain_pair()
                tagged_data, data_bytes =
                    decode_next(start_idx + bytes_consumed, bytes,
                                with_iana)
                bytes_consumed += data_bytes

                return Pair(tag, tagged_data)
            end

            if with_iana
                if tag == POS_BIG_INT_TAG || tag == NEG_BIG_INT_TAG
                    big_int_bytes, sub_bytes_consumed =
                        decode_next(start_idx + bytes_consumed, bytes,
                                    with_iana)
                    bytes_consumed += sub_bytes_consumed

                    big_int = parse(BigInt, bytes2hex(big_int_bytes),
                                    HEX_BASE)
                    if tag == NEG_BIG_INT_TAG
                        big_int = -(big_int + 1)
                    end

                    const data = big_int
                else
                    const data = retrieve_plain_pair()
                end
            else
                const data = retrieve_plain_pair()
            end

        elseif typ == TYPE_7
            const addntl_info = first_byte & ADDNTL_INFO_MASK
            bytes_consumed = 1

            if addntl_info < SINGLE_BYTE_SIMPLE_PLUS_ONE + 1
                bytes_consumed += 1
                if addntl_info < SINGLE_BYTE_SIMPLE_PLUS_ONE
                    const simple_val = addntl_info
                else
                    bytes_consumed += 1
                    const simple_val = bytes[start_idx + 1]
                end

                if simple_val == SIMPLE_FALSE
                    const data = false
                elseif simple_val == SIMPLE_TRUE
                    const data = true
                elseif simple_val == SIMPLE_NULL
                    const data = Null()
                elseif simple_val == SIMPLE_UNDEF
                    const data = Undefined()
                else
                    const data = Simple(simple_val)
                end
            else
                if addntl_info == ADDNTL_INFO_FLOAT64
                    const float_byte_len = SIZE_OF_FLOAT64
                elseif addntl_info == ADDNTL_INFO_FLOAT32
                    const float_byte_len = SIZE_OF_FLOAT32
                elseif addntl_info == ADDNTL_INFO_FLOAT16
                    error("Decoding 16-bit floats isn't supported.")
                end

                bytes_consumed += float_byte_len
                const data = hex2num(bytes2hex(
                    bytes[(start_idx + 1):(start_idx + float_byte_len)]
                ))
            end

        elseif first_byte & ADDNTL_INFO_MASK == ADDNTL_INFO_INDEF
            data, bytes_consumed =
                decode_next_indef(start_idx, bytes, typ, with_iana)

        elseif typ == TYPE_2
            byte_string_len, bytes_consumed =
                decode_unsigned(start_idx, bytes)
            start_idx += bytes_consumed

            const data =
                bytes[start_idx:(start_idx + byte_string_len - 1)]
            bytes_consumed += byte_string_len

        elseif typ == TYPE_3
            string_bytes, bytes_consumed =
                decode_unsigned(start_idx, bytes)
            start_idx += bytes_consumed
            const data =
                UTF8String(bytes[start_idx:(start_idx + string_bytes - 1)])
            bytes_consumed += string_bytes

        elseif typ == TYPE_4
            vec_len, bytes_consumed = decode_unsigned(start_idx, bytes)
            data = Vector(vec_len)
            for i in 1:vec_len
                data[i], sub_bytes_consumed =
                    decode_next(start_idx + bytes_consumed, bytes, with_iana)
                bytes_consumed += sub_bytes_consumed
            end

        elseif typ == TYPE_5
            map_len, bytes_consumed = decode_unsigned(start_idx, bytes)
            data = Dict()
            for i in 1:map_len
                key, key_bytes =
                    decode_next(start_idx + bytes_consumed, bytes, with_iana)
                bytes_consumed += key_bytes

                value, value_bytes =
                    decode_next(start_idx + bytes_consumed, bytes, with_iana)
                bytes_consumed += value_bytes

                data[key] = value
            end
        end

    return data, bytes_consumed
end


text:
function downloadGPSData(gpsWeek::Int, day::Int)
    baseUrl = "https://cddis.nasa.gov/archive/gnss/products/"
    sp3Url  = baseUrl * string(gpsWeek) * "\\igs" * string(gpsWeek) * string(day) * ".sp3"

    fileName = datadir("igs") * "\\igs" * string(gpsWeek) * string(day) * ".sp3"
    download(sp3Url, fileName*".Z")

    try
        stream = DeflateDecompressorStream(open(fileName*".Z"))
        for line in eachline(stream)

        end
    finally
        close(stream)
    end
end

max_stars_repo_name: GrantHecht/OptimalEstimationProject


text:
"""
// ****************************************
// R. Aggarwal
// Tranfer Matrix Analysis for the high-x data
// should be used as N = T K S
// K - radiative corrections
// S - Born level integrated sigma .. to be read externally
//       (Units pb-1)
// T- Transfer Matrix (has data luminosity taken into account)
//*******************************************
"""

include("../data/zeus_transfer_matrix.jl")

export get_pred_N
export get_data_events

function get_data_events(eMPp)
    if eMPp == 0
        return Data_Events_ePp
    else
        return Data_Events_eMp
    end
end

function get_K_elements(eMPp)
    if eMPp == 0
        return Kii_ePp
    else
        return Kii_eMp
    end
end

function get_L_data(eMPp)
    if eMPp == 0
        return Ld_ePp
    else
        return Ld_eMp
    end
end

function get_TM_elements(eMPp)
    lumi_data = get_L_data(eMPp)
    TM_elements = TM_Elements_eMp
    if eMPp == 0
        TM_elements = TM_Elements_ePp
    end
    for i in 1:429
        for j in 1:153
         TM_elements[i,j] =TM_elements[i,j] * lumi_data
        end
    end
    return TM_elements
end

function get_pred_N(Integ_xsec, eMPp)

    TM = get_TM_elements(eMPp);
    K = get_K_elements(eMPp)

    xsec_pred = zeros(153)
    for j in 1:153
        temp=0.
        for i in 1:429

        temp = temp +(TM[i,j]./K[i]) * Integ_xsec[i];
        end
        xsec_pred[j] = temp
    end

    return xsec_pred;

end


text:
# This file is auto-generated by AWSMetadata.jl
using AWS
using AWS.AWSServices: schemas
using AWS.Compat
using AWS.UUIDs

"""
    create_discoverer(source_arn)
    create_discoverer(source_arn, params::Dict{String,<:Any})

Creates a discoverer.

# Arguments
- `source_arn`: The ARN of the event bus.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"CrossAccount"`: Support discovery of schemas in events sent to the bus from another
  account. (default: true).
- `"Description"`: A description for the discoverer.
- `"tags"`: Tags associated with the resource.
"""
function create_discoverer(SourceArn; aws_config::AbstractAWSConfig=global_aws_config())
    return schemas(
        "POST",
        "/v1/discoverers",
        Dict{String,Any}("SourceArn" => SourceArn);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function create_discoverer(
    SourceArn,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return schemas(
        "POST",
        "/v1/discoverers",
        Dict{String,Any}(
            mergewith(_merge, Dict{String,Any}("SourceArn" => SourceArn), params)
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    create_registry(registry_name)
    create_registry(registry_name, params::Dict{String,<:Any})

Creates a registry.

# Arguments
- `registry_name`: The name of the registry.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Description"`: A description of the registry to be created.
- `"tags"`: Tags to associate with the registry.
"""
function create_registry(registryName; aws_config::AbstractAWSConfig=global_aws_config())
    return schemas(
        "POST",
        "/v1/registries/name/$(registryName)";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function create_registry(
    registryName,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return schemas(
        "POST",
        "/v1/registries/name/$(registryName)",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    create_schema(content, type, registry_name, schema_name)
    create_schema(content, type, registry_name, schema_name, params::Dict{String,<:Any})

Creates a schema definition. Inactive schemas will be deleted after two years.

# Arguments
- `content`: The source of the schema definition.
- `type`: The type of schema.
- `registry_name`: The name of the registry.
- `schema_name`: The name of the schema.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Description"`: A description of the schema.
- `"tags"`: Tags associated with the schema.
"""
function create_schema(
    Content,
    Type,
    registryName,
    schemaName;
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return schemas(
        "POST",
        "/v1/registries/name/$(registryName)/schemas/name/$(schemaName)",
        Dict{String,Any}("Content" => Content, "Type" => Type);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function create_schema(
    Content,
    Type,
    registryName,
    schemaName,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return schemas(
        "POST",
        "/v1/registries/name/$(registryName)/schemas/name/$(schemaName)",
        Dict{String,Any}(
            mergewith(
                _merge, Dict{String,Any}("Content" => Content, "Type" => Type), params
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    delete_discoverer(discoverer_id)
    delete_discoverer(discoverer_id, params::Dict{String,<:Any})

Deletes a discoverer.

# Arguments
- `discoverer_id`: The ID of the discoverer.

"""
function delete_discoverer(discovererId; aws_config::AbstractAWSConfig=global_aws_config())
    return schemas(
        "DELETE",
        "/v1/discoverers/id/$(discovererId)";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function delete_discoverer(
    discovererId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return schemas(
        "DELETE",
        "/v1/discoverers/id/$(discovererId)",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    delete_registry(registry_name)
    delete_registry(registry_name, params::Dict{String,<:Any})

Deletes a Registry.

# Arguments
- `registry_name`: The name of the registry.

"""
function delete_registry(registryName; aws_config::AbstractAWSConfig=global_aws_config())
    return schemas(
        "DELETE",
        "/v1/registries/name/$(registryName)";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function delete_registry(
    registryName,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return schemas(
        "DELETE",
        "/v1/registries/name/$(registryName)",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    delete_resource_policy()
    delete_resource_policy(params::Dict{String,<:Any})

Delete the resource-based policy attached to the specified registry.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"registryName"`: The name of the registry.
"""
function delete_resource_policy(; aws_config::AbstractAWSConfig=global_aws_config())
    return schemas(
        "DELETE", "/v1/policy"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET
    )
end
function delete_resource_policy(
    params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()
)
    return schemas(
        "DELETE",
        "/v1/policy",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    delete_schema(registry_name, schema_name)
    delete_schema(registry_name, schema_name, params::Dict{String,<:Any})

Delete a schema definition.

# Arguments
- `registry_name`: The name of the registry.
- `schema_name`: The name of the schema.

"""
function delete_schema(
    registryName, schemaName; aws_config::AbstractAWSConfig=global_aws_config()
)
    return schemas(
        "DELETE",
        "/v1/registries/name/$(registryName)/schemas/name/$(schemaName)";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function delete_schema(
    registryName,
    schemaName,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return schemas(
        "DELETE",
        "/v1/registries/name/$(registryName)/schemas/name/$(schemaName)",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    delete_schema_version(registry_name, schema_name, schema_version)
    delete_schema_version(registry_name, schema_name, schema_version, params::Dict{String,<:Any})

Delete the schema version definition

# Arguments
- `registry_name`: The name of the registry.
- `schema_name`: The name of the schema.
- `schema_version`: The version number of the schema

"""
function delete_schema_version(
    registryName,
    schemaName,
    schemaVersion;
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return schemas(
        "DELETE",
        "/v1/registries/name/$(registryName)/schemas/name/$(schemaName)/version/$(schemaVersion)";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function delete_schema_version(
    registryName,
    schemaName,
    schemaVersion,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return schemas(
        "DELETE",
        "/v1/registries/name/$(registryName)/schemas/name/$(schemaName)/version/$(schemaVersion)",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    describe_code_binding(language, registry_name, schema_name)
    describe_code_binding(language, registry_name, schema_name, params::Dict{String,<:Any})

Describe the code binding URI.

# Arguments
- `language`: The language of the code binding.
- `registry_name`: The name of the registry.
- `schema_name`: The name of the schema.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"schemaVersion"`: Specifying this limits the results to only this schema version.
"""
function describe_code_binding(
    language, registryName, schemaName; aws_config::AbstractAWSConfig=global_aws_config()
)
    return schemas(
        "GET",
        "/v1/registries/name/$(registryName)/schemas/name/$(schemaName)/language/$(language)";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function describe_code_binding(
    language,
    registryName,
    schemaName,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return schemas(
        "GET",
        "/v1/registries/name/$(registryName)/schemas/name/$(schemaName)/language/$(language)",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    describe_discoverer(discoverer_id)
    describe_discoverer(discoverer_id, params::Dict{String,<:Any})

Describes the discoverer.

# Arguments
- `discoverer_id`: The ID of the discoverer.

"""
function describe_discoverer(
    discovererId; aws_config::AbstractAWSConfig=global_aws_config()
)
    return schemas(
        "GET",
        "/v1/discoverers/id/$(discovererId)";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function describe_discoverer(
    discovererId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return schemas(
        "GET",
        "/v1/discoverers/id/$(discovererId)",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    describe_registry(registry_name)
    describe_registry(registry_name, params::Dict{String,<:Any})

Describes the registry.

# Arguments
- `registry_name`: The name of the registry.

"""
function describe_registry(registryName; aws_config::AbstractAWSConfig=global_aws_config())
    return schemas(
        "GET",
        "/v1/registries/name/$(registryName)";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function describe_registry(
    registryName,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return schemas(
        "GET",
        "/v1/registries/name/$(registryName)",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    describe_schema(registry_name, schema_name)
    describe_schema(registry_name, schema_name, params::Dict{String,<:Any})

Retrieve the schema definition.

# Arguments
- `registry_name`: The name of the registry.
- `schema_name`: The name of the schema.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"schemaVersion"`: Specifying this limits the results to only this schema version.
"""
function describe_schema(
    registryName, schemaName; aws_config::AbstractAWSConfig=global_aws_config()
)
    return schemas(
        "GET",
        "/v1/registries/name/$(registryName)/schemas/name/$(schemaName)";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function describe_schema(
    registryName,
    schemaName,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return schemas(
        "GET",
        "/v1/registries/name/$(registryName)/schemas/name/$(schemaName)",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    export_schema(registry_name, schema_name, type)
    export_schema(registry_name, schema_name, type, params::Dict{String,<:Any})

# Arguments
- `registry_name`: The name of the registry.
- `schema_name`: The name of the schema.
- `type`:

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"schemaVersion"`: Specifying this limits the results to only this schema version.
"""
function export_schema(
    registryName, schemaName, type; aws_config::AbstractAWSConfig=global_aws_config()
)
    return schemas(
        "GET",
        "/v1/registries/name/$(registryName)/schemas/name/$(schemaName)/export",
        Dict{String,Any}("type" => type);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function export_schema(
    registryName,
    schemaName,
    type,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return schemas(
        "GET",
        "/v1/registries/name/$(registryName)/schemas/name/$(schemaName)/export",
        Dict{String,Any}(mergewith(_merge, Dict{String,Any}("type" => type), params));
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    get_code_binding_source(language, registry_name, schema_name)
    get_code_binding_source(language, registry_name, schema_name, params::Dict{String,<:Any})

Get the code binding source URI.

# Arguments
- `language`: The language of the code binding.
- `registry_name`: The name of the registry.
- `schema_name`: The name of the schema.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"schemaVersion"`: Specifying this limits the results to only this schema version.
"""
function get_code_binding_source(
    language, registryName, schemaName; aws_config::AbstractAWSConfig=global_aws_config()
)
    return schemas(
        "GET",
        "/v1/registries/name/$(registryName)/schemas/name/$(schemaName)/language/$(language)/source";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function get_code_binding_source(
    language,
    registryName,
    schemaName,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return schemas(
        "GET",
        "/v1/registries/name/$(registryName)/schemas/name/$(schemaName)/language/$(language)/source",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    get_discovered_schema(events, type)
    get_discovered_schema(events, type, params::Dict{String,<:Any})

Get the discovered schema that was generated based on sampled events.

# Arguments
- `events`: An array of strings where each string is a JSON event. These are the events
  that were used to generate the schema. The array includes a single type of event and has a
  maximum size of 10 events.
- `type`: The type of event.

"""
function get_discovered_schema(
    Events, Type; aws_config::AbstractAWSConfig=global_aws_config()
)
    return schemas(
        "POST",
        "/v1/discover",
        Dict{String,Any}("Events" => Events, "Type" => Type);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function get_discovered_schema(
    Events,
    Type,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return schemas(
        "POST",
        "/v1/discover",
        Dict{String,Any}(
            mergewith(_merge, Dict{String,Any}("Events" => Events, "Type" => Type), params)
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    get_resource_policy()
    get_resource_policy(params::Dict{String,<:Any})

Retrieves the resource-based policy attached to a given registry.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"registryName"`: The name of the registry.
"""
function get_resource_policy(; aws_config::AbstractAWSConfig=global_aws_config())
    return schemas(
        "GET", "/v1/policy"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET
    )
end
function get_resource_policy(
    params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()
)
    return schemas(
        "GET", "/v1/policy", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET
    )
end

"""
    list_discoverers()
    list_discoverers(params::Dict{String,<:Any})

List the discoverers.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"discovererIdPrefix"`: Specifying this limits the results to only those discoverer IDs
  that start with the specified prefix.
- `"limit"`:
- `"nextToken"`: The token that specifies the next page of results to return. To request
  the first page, leave NextToken empty. The token will expire in 24 hours, and cannot be
  shared with other accounts.
- `"sourceArnPrefix"`: Specifying this limits the results to only those ARNs that start
  with the specified prefix.
"""
function list_discoverers(; aws_config::AbstractAWSConfig=global_aws_config())
    return schemas(
        "GET", "/v1/discoverers"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET
    )
end
function list_discoverers(
    params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()
)
    return schemas(
        "GET",
        "/v1/discoverers",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    list_registries()
    list_registries(params::Dict{String,<:Any})

List the registries.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"limit"`:
- `"nextToken"`: The token that specifies the next page of results to return. To request
  the first page, leave NextToken empty. The token will expire in 24 hours, and cannot be
  shared with other accounts.
- `"registryNamePrefix"`: Specifying this limits the results to only those registry names
  that start with the specified prefix.
- `"scope"`: Can be set to Local or AWS to limit responses to your custom registries, or
  the ones provided by AWS.
"""
function list_registries(; aws_config::AbstractAWSConfig=global_aws_config())
    return schemas(
        "GET", "/v1/registries"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET
    )
end
function list_registries(
    params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()
)
    return schemas(
        "GET",
        "/v1/registries",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    list_schema_versions(registry_name, schema_name)
    list_schema_versions(registry_name, schema_name, params::Dict{String,<:Any})

Provides a list of the schema versions and related information.

# Arguments
- `registry_name`: The name of the registry.
- `schema_name`: The name of the schema.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"limit"`:
- `"nextToken"`: The token that specifies the next page of results to return. To request
  the first page, leave NextToken empty. The token will expire in 24 hours, and cannot be
  shared with other accounts.
"""
function list_schema_versions(
    registryName, schemaName; aws_config::AbstractAWSConfig=global_aws_config()
)
    return schemas(
        "GET",
        "/v1/registries/name/$(registryName)/schemas/name/$(schemaName)/versions";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function list_schema_versions(
    registryName,
    schemaName,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return schemas(
        "GET",
        "/v1/registries/name/$(registryName)/schemas/name/$(schemaName)/versions",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    list_schemas(registry_name)
    list_schemas(registry_name, params::Dict{String,<:Any})

List the schemas.

# Arguments
- `registry_name`: The name of the registry.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"limit"`:
- `"nextToken"`: The token that specifies the next page of results to return. To request
  the first page, leave NextToken empty. The token will expire in 24 hours, and cannot be
  shared with other accounts.
- `"schemaNamePrefix"`: Specifying this limits the results to only those schema names that
  start with the specified prefix.
"""
function list_schemas(registryName; aws_config::AbstractAWSConfig=global_aws_config())
    return schemas(
        "GET",
        "/v1/registries/name/$(registryName)/schemas";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function list_schemas(
    registryName,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return schemas(
        "GET",
        "/v1/registries/name/$(registryName)/schemas",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    list_tags_for_resource(resource-arn)
    list_tags_for_resource(resource-arn, params::Dict{String,<:Any})

Get tags for resource.

# Arguments
- `resource-arn`: The ARN of the resource.

"""
function list_tags_for_resource(
    resource_arn; aws_config::AbstractAWSConfig=global_aws_config()
)
    return schemas(
        "GET",
        "/tags/$(resource-arn)";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function list_tags_for_resource(
    resource_arn,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return schemas(
        "GET",
        "/tags/$(resource-arn)",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    put_code_binding(language, registry_name, schema_name)
    put_code_binding(language, registry_name, schema_name, params::Dict{String,<:Any})

Put code binding URI

# Arguments
- `language`: The language of the code binding.
- `registry_name`: The name of the registry.
- `schema_name`: The name of the schema.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"schemaVersion"`: Specifying this limits the results to only this schema version.
"""
function put_code_binding(
    language, registryName, schemaName; aws_config::AbstractAWSConfig=global_aws_config()
)
    return schemas(
        "POST",
        "/v1/registries/name/$(registryName)/schemas/name/$(schemaName)/language/$(language)";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function put_code_binding(
    language,
    registryName,
    schemaName,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return schemas(
        "POST",
        "/v1/registries/name/$(registryName)/schemas/name/$(schemaName)/language/$(language)",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    put_resource_policy(policy)
    put_resource_policy(policy, params::Dict{String,<:Any})

The name of the policy.

# Arguments
- `policy`: The resource-based policy.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"RevisionId"`: The revision ID of the policy.
- `"registryName"`: The name of the registry.
"""
function put_resource_policy(Policy; aws_config::AbstractAWSConfig=global_aws_config())
    return schemas(
        "PUT",
        "/v1/policy",
        Dict{String,Any}("Policy" => Policy);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function put_resource_policy(
    Policy, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()
)
    return schemas(
        "PUT",
        "/v1/policy",
        Dict{String,Any}(mergewith(_merge, Dict{String,Any}("Policy" => Policy), params));
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    search_schemas(keywords, registry_name)
    search_schemas(keywords, registry_name, params::Dict{String,<:Any})

Search the schemas

# Arguments
- `keywords`: Specifying this limits the results to only schemas that include the provided
  keywords.
- `registry_name`: The name of the registry.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"limit"`:
- `"nextToken"`: The token that specifies the next page of results to return. To request
  the first page, leave NextToken empty. The token will expire in 24 hours, and cannot be
  shared with other accounts.
"""
function search_schemas(
    keywords, registryName; aws_config::AbstractAWSConfig=global_aws_config()
)
    return schemas(
        "GET",
        "/v1/registries/name/$(registryName)/schemas/search",
        Dict{String,Any}("keywords" => keywords);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function search_schemas(
    keywords,
    registryName,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return schemas(
        "GET",
        "/v1/registries/name/$(registryName)/schemas/search",
        Dict{String,Any}(
            mergewith(_merge, Dict{String,Any}("keywords" => keywords), params)
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    start_discoverer(discoverer_id)
    start_discoverer(discoverer_id, params::Dict{String,<:Any})

Starts the discoverer

# Arguments
- `discoverer_id`: The ID of the discoverer.

"""
function start_discoverer(discovererId; aws_config::AbstractAWSConfig=global_aws_config())
    return schemas(
        "POST",
        "/v1/discoverers/id/$(discovererId)/start";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function start_discoverer(
    discovererId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return schemas(
        "POST",
        "/v1/discoverers/id/$(discovererId)/start",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    stop_discoverer(discoverer_id)
    stop_discoverer(discoverer_id, params::Dict{String,<:Any})

Stops the discoverer

# Arguments
- `discoverer_id`: The ID of the discoverer.

"""
function stop_discoverer(discovererId; aws_config::AbstractAWSConfig=global_aws_config())
    return schemas(
        "POST",
        "/v1/discoverers/id/$(discovererId)/stop";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function stop_discoverer(
    discovererId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return schemas(
        "POST",
        "/v1/discoverers/id/$(discovererId)/stop",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    tag_resource(resource-arn, tags)
    tag_resource(resource-arn, tags, params::Dict{String,<:Any})

Add tags to a resource.

# Arguments
- `resource-arn`: The ARN of the resource.
- `tags`: Tags associated with the resource.

"""
function tag_resource(resource_arn, tags; aws_config::AbstractAWSConfig=global_aws_config())
    return schemas(
        "POST",
        "/tags/$(resource-arn)",
        Dict{String,Any}("tags" => tags);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function tag_resource(
    resource_arn,
    tags,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return schemas(
        "POST",
        "/tags/$(resource-arn)",
        Dict{String,Any}(mergewith(_merge, Dict{String,Any}("tags" => tags), params));
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    untag_resource(resource-arn, tag_keys)
    untag_resource(resource-arn, tag_keys, params::Dict{String,<:Any})

Removes tags from a resource.

# Arguments
- `resource-arn`: The ARN of the resource.
- `tag_keys`: Keys of key-value pairs.

"""
function untag_resource(
    resource_arn, tagKeys; aws_config::AbstractAWSConfig=global_aws_config()
)
    return schemas(
        "DELETE",
        "/tags/$(resource-arn)",
        Dict{String,Any}("tagKeys" => tagKeys);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function untag_resource(
    resource_arn,
    tagKeys,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return schemas(
        "DELETE",
        "/tags/$(resource-arn)",
        Dict{String,Any}(mergewith(_merge, Dict{String,Any}("tagKeys" => tagKeys), params));
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    update_discoverer(discoverer_id)
    update_discoverer(discoverer_id, params::Dict{String,<:Any})

Updates the discoverer

# Arguments
- `discoverer_id`: The ID of the discoverer.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"CrossAccount"`: Support discovery of schemas in events sent to the bus from another
  account. (default: true)
- `"Description"`: The description of the discoverer to update.
"""
function update_discoverer(discovererId; aws_config::AbstractAWSConfig=global_aws_config())
    return schemas(
        "PUT",
        "/v1/discoverers/id/$(discovererId)";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function update_discoverer(
    discovererId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return schemas(
        "PUT",
        "/v1/discoverers/id/$(discovererId)",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    update_registry(registry_name)
    update_registry(registry_name, params::Dict{String,<:Any})

Updates a registry.

# Arguments
- `registry_name`: The name of the registry.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Description"`: The description of the registry to update.
"""
function update_registry(registryName; aws_config::AbstractAWSConfig=global_aws_config())
    return schemas(
        "PUT",
        "/v1/registries/name/$(registryName)";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function update_registry(
    registryName,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return schemas(
        "PUT",
        "/v1/registries/name/$(registryName)",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    update_schema(registry_name, schema_name)
    update_schema(registry_name, schema_name, params::Dict{String,<:Any})

Updates the schema definition Inactive schemas will be deleted after two years.

# Arguments
- `registry_name`: The name of the registry.
- `schema_name`: The name of the schema.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"ClientTokenId"`: The ID of the client token.
- `"Content"`: The source of the schema definition.
- `"Description"`: The description of the schema.
- `"Type"`: The schema type for the events schema.
"""
function update_schema(
    registryName, schemaName; aws_config::AbstractAWSConfig=global_aws_config()
)
    return schemas(
        "PUT",
        "/v1/registries/name/$(registryName)/schemas/name/$(schemaName)",
        Dict{String,Any}("ClientTokenId" => string(uuid4()));
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function update_schema(
    registryName,
    schemaName,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return schemas(
        "PUT",
        "/v1/registries/name/$(registryName)/schemas/name/$(schemaName)",
        Dict{String,Any}(
            mergewith(_merge, Dict{String,Any}("ClientTokenId" => string(uuid4())), params)
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end