text:
################################################################################
#
#  Infinite places for number fields
#
#
#  (C) 2017 Tommy Hofmann
#
################################################################################

export iscomplex, ispositive, istotally_positive, signs, sign, real_places,
       complex_places, infinite_places, infinite_place

################################################################################
#
#  Equality and hashing
#
################################################################################

function Base.:(==)(P::InfPlc, Q::InfPlc)
  P.K != Q.K && error("Places are of different number fields")
  return P.i == Q.i
end

function Base.hash(P::InfPlc, h::UInt)
  return xor(Base.hash(P.K, h), Base.hash(P.i, h))
end

################################################################################
#
#  Printing
#
################################################################################

function Base.show(io::IO, P::InfPlc)
  if P.isreal
    print(io, "Real ")
  else
    print(io, "Complex ")
  end

  print(io, "place of \n$(P.K)\n")
  print(io, "corresponding to the root $(P.r)")
end

################################################################################
#
#  Predicates
#
################################################################################

@doc Markdown.doc"""
    isreal(P::InfPlc) -> Bool

Returns whether the embedding into $\mathbf{C}$ defined by P is real or not.
"""
function Base.isreal(P::InfPlc)
  return P.isreal
end

@doc Markdown.doc"""
    iscomplex(P::InfPlc) -> Bool

Returns whether the embedding into $\mathbf{C}$ defined by P is complex or not.
"""
function iscomplex(P::InfPlc)
  return !isreal(P)
end

################################################################################
#
#  Construction
#
################################################################################

@doc Markdown.doc"""
    infinite_place(K::AnticNumberField, i::Int) -> InfPlc

This function returns the infinite place of $K$ corresponding to the root
`conjugates_arb(a)[i]`, where `a` is the primitive element of $K$.
"""
function infinite_place(K::AnticNumberField, i::Int)
  !(1 <= i <= degree(K)) && error("Index must be between 1 and $(degree(K))")
  return InfPlc(K, i)
end

@doc Markdown.doc"""
    infinite_places(K::AnticNumberField) -> Vector{InfPlc}

This function returns all infinite places of $K$.
"""
function infinite_places(K::AnticNumberField)
  r1, r2 = signature(K)
  return [ InfPlc(K, i) for i in 1:(r1 + r2)]
end

@doc Markdown.doc"""
    real_places(K::AnticNumberField) -> Vector{InfPlc}

This function returns all infinite real places of $K$.
"""
function real_places(K::AnticNumberField)
  r1, r2 = signature(K)
  return [ InfPlc(K, i) for i in 1:r1]
end

@doc Markdown.doc"""
    complex_places(K::AnticNumberField) -> Vector{InfPlc}

This function returns all infinite complex places of $K$.
"""
function complex_places(K::AnticNumberField)
  r1, r2 = signature(K)
  return [ InfPlc(K, i) for i in (r1 + 1):r1 + r2]
end

################################################################################
#
#  Signs at places
#
################################################################################

@doc Markdown.doc"""
    signs(a::nf_elem)          -> Dict{InfPlc, Int}
    signs(a::FacElem{nf_elem}) -> Dict{InfPlc, Int}

This function returns a dictionary of the signs of $a$ at all infinite places
of the ambient number field. The keys are infinite places of the ambient
number field. The value is $1$ if the sign is positive and $-1$ if the sign
is negative.
"""
function signs(a::Union{nf_elem, FacElem{nf_elem, AnticNumberField}})
  K = _base_ring(a)
  r1, r2 = signature(K)
  D = Dict{InfPlc, Int}()
  s = _signs(a)
  for i in 1:r1
    P = InfPlc(K, i)
    D[P] = s[i]
  end
  return D
end

@doc Markdown.doc"""
    sign(a::nf_elem, P::InfPlc)          -> Int
    sign(a::FacElem{nf_elem}, P::InfPlc) -> Int

This function returns the sign of $a$ at the place $P$. The value is $1$ if
the sign is positive and $-1$ if the sign is negative.

"""
function sign(a::Union{nf_elem, FacElem{nf_elem, AnticNumberField}}, P::InfPlc)
  !isreal(P) && error("Place must be real")
  return signs(a, [P])[P]
end

@doc Markdown.doc"""
    signs(a::nf_elem, l::Vector{InfPlc})          -> Dict{InfPlc, Int}
    signs(a::FacElem{nf_elem}, l::Vector{InfPlc}) -> Dict{InfPlc, Int}

This function returns a dictionary of the signs of $a$ at places in $l$. The
keys are the elements of $l$. The value is $1$ if the sign is positive and
$-1$ if the sign is negative. The result will contain as many signs as there
are real places contained in $l$.
"""
function signs(a::Union{nf_elem, FacElem{nf_elem, AnticNumberField}}, l::Array{InfPlc, 1})
  K = _base_ring(a)
  r1, r2 = signature(K)
  D = Dict{InfPlc, Int}()
  s = _signs(a)
  for i in 1:r1
    P = InfPlc(K, i)
    if P in l
      D[P] = s[i]
    end
  end
  return D
end

# extend functionality to elements of orders

function signs(a::NfOrdElem, args...)
  return signs(a.elem_in_nf, args...)
end

function sign(a::NfOrdElem, args...)
  return sign(a.elem_in_nf, args...)
end

################################################################################
#
#  Positivity
#
################################################################################

@doc Markdown.doc"""
    ispositive(a::nf_elem, P::InfPlc)          -> Bool
    ispositive(a::FacElem{nf_elem}, P::InfPlc) -> Bool

Returns whether the element $a$ is positive at the embedding corresponding to
$P$. The place $P$ must be real.
"""
function ispositive(a::Union{nf_elem, FacElem{nf_elem, AnticNumberField}}, P::InfPlc)
  !isreal(P) && error("Place must be real")
  return sign(a, P) > 0
end

@doc Markdown.doc"""
    isnegative(a::nf_elem, P::InfPlc)          -> Bool
    isnegative(a::FacElem{nf_elem}, P::InfPlc) -> Bool

Returns whether the element $a$ is negative at the embedding corresponding to
$P$. The place $P$ must be real.
"""
function isnegative(a::Union{nf_elem, FacElem{nf_elem, AnticNumberField}}, P::InfPlc)
  !isreal(P) && error("Place must be real")
  return sign(a, P) < 0
end

@doc Markdown.doc"""
    ispositive(a::nf_elem, l::Vector{InfPlc})          -> Bool
    ispositive(a::FacElem{nf_elem}, l::Vector{InfPlc}) -> Bool

Returns whether the element $a$ is positive at the embeddings corresponding to
the real places of $l$.
"""
function ispositive(a::Union{nf_elem, FacElem{nf_elem, AnticNumberField}}, l::Array{InfPlc, 1})
  return all(x -> ispositive(a, x), (y for y in l if isreal(y)))
end

@doc Markdown.doc"""
    istotally_positive(a::nf_elem)          -> Bool
    istotally_positive(a::FacElem{nf_elem}) -> Bool

Returns whether the element $a$ is totally positive, that is, whether it is
positive at all places of the ambient number field.
"""
function istotally_positive(a::Union{nf_elem, FacElem{nf_elem, AnticNumberField}})
  K = _base_ring(a)
  return ispositive(a, real_places(K))
end

# extend functionality to elements of orders

function ispositive(a::NfOrdElem, args...)
  return ispositive(a.elem_in_nf, args...)
end

function istotally_positive(a::NfOrdElem, args...)
  return istotally_positive(a.elem_in_nf, args...)
end

################################################################################
#
#  Action of a morphism on a infinite place
#
################################################################################

#The action of f on P is defined as f(P) = P\circ f^{-1} and not P\circ f
#In this way, (f\circ g)(P)= f(g(P)), otherwise it would fail.

@doc Markdown.doc"""
    induce_image(m::NfToNfMor, P::InfPlc) -> InfPlc
Find a place in the image of $P$ under $m$. If $m$ is an automorphism,
this is unique.
"""
function induce_image(m::NfToNfMor, P::InfPlc)
  k = number_field(P)
  @assert k == domain(m)
  Qx = parent(k.pol)
  if isdefined(m, :prim_preimg)
    h = Qx(m.prim_preimg)
  else
    # I need to invert the map.
    inv_img = _compute_preimg(m)
    h = Qx(inv_img)
  end
  im = h(P.r)
  lp = infinite_places(codomain(m))
  return lp[findfirst(x -> overlaps(lp[x].r, im), 1:length(lp))]
end

function number_field(P::InfPlc)
  return P.K
end


text:
pushfirst!(LOAD_PATH, joinpath(@__DIR__, ".."))

using Oceananigans
using Oceananigans.TimeSteppers: time_step!
using BenchmarkTools

N = 256

xy_grid = RegularRectilinearGrid(size = (N, N, 1), halo = (3, 3, 3), extent = (2π, 2π, 2π), topology = (Periodic, Periodic, Bounded))
xz_grid = RegularRectilinearGrid(size = (N, 1, N), halo = (3, 3, 3), extent = (2π, 2π, 2π), topology = (Periodic, Periodic, Bounded))
yz_grid = RegularRectilinearGrid(size = (1, N, N), halo = (3, 3, 3), extent = (2π, 2π, 2π), topology = (Periodic, Periodic, Bounded))

function ten_steps!(model)
    for _ = 1:10
        time_step!(model, 1e-6)
    end
    return nothing
end

for arch in (CPU(), GPU())

    for grid in (xy_grid,
                 xz_grid,
                 yz_grid)

        model = NonhydrostaticModel(architecture = arch,
                                    timestepper = :QuasiAdamsBashforth2,
                                    grid = grid,
                                    advection = nothing,
                                    closure = nothing,
                                    buoyancy = nothing,
                                    tracers = nothing)

        time_step!(model, 1e-6) # warmup

        @info "Benchmarking $arch model with $(summary(grid))..."
        @btime ten_steps!($model)
    end
end

ext: jl


text:
include("test_01_OneScalarSignal.jl")
include("test_02_OneScalarSignalWithUnit.jl")
include("test_03_OneVectorSignalWithUnit.jl")
include("test_04_ConstantSignalsWithUnit.jl")
include("test_05_ArraySignalsWithUnit.jl")

include("test_06_OneScalarMeasurementSignal.jl")
include("test_07_OneScalarMeasurementSignalWithUnit.jl")

include("test_20_SeveralSignalsInOneDiagram.jl")
include("test_21_VectorOfPlots.jl")
include("test_22_MatrixOfPlots.jl")
include("test_23_MatrixOfPlotsWithTimeLabelsInLastRow.jl")
include("test_24_Reuse.jl")
include("test_25_SeveralFigures.jl")
include("test_26_TooManyLegends.jl")

include("test_51_OneScalarMonteCarloMeasurementsSignal.jl")
include("test_52_MonteCarloMeasurementsWithDistributions.jl")

include("test_70_ResultDict.jl")
# include("test_71_Tables_Rotational_First.jl")    # deactivated, because "using CSV"
include("test_72_ResultDictWithMatrixOfPlots.jl")

include("test_80_Warnings.jl")
include("test_81_SaveFigure.jl")
include("test_82_AllExportedFunctions.jl")

# include("test_90_CompareOneScalarSignal.jl")
# include("test_91_CompareOneScalarSignalWithUnit.jl")

max_stars_repo_name: ModiaSim/ModiaResult

max_issues_repo_name: ModiaSim/ModiaResult

max_forks_repo_name: ModiaSim/ModiaResult


text:
# by Lazaro Alonso
using GeoMakie, Proj4, CairoMakie
CairoMakie.activate!()
let
    lons = -180:180
    lats = -90:90
    field = [exp(cosd(l)) + 3(y/90) for l in lons, y in lats]

    trans = Proj4.Transformation("+proj=longlat +datum=WGS84", "+proj=wintri",
        always_xy=true)
    # see https://proj.org/operations/projections/index.html for more options
    ptrans = Makie.PointTrans{2}(trans)

    fig = Figure(resolution = (1250,700), fontsize = 22)
    ax = Axis(fig[1,1], aspect = DataAspect(),
        title = "Projection: Winkel Tripel, Field")
    # all input data coordinates are projected using this function
    ax.scene.transformation.transform_func[] = ptrans
    # add some limits, still it needs to be manual

    points = [Point2f0(lon, lat) for lon in lons, lat in lats]
    rectLimits = FRect2D(Makie.apply_transform(ptrans, points))
    limits!(ax, rectLimits)
    # now the plot
    hm = surface!(ax, lons, lats, field, shading = false)
    Colorbar(fig[1,2], hm, label = "variable, color code", height = Relative(0.65))
    lines!(ax, GeoMakie.coastlines(), color = :black, overdraw = true)

    hidedecorations!(ax, ticks = false, label = false, grid=false)
    hidespines!(ax)
    fig
    save(joinpath(@__DIR__, "output", "geoCoastlinesField.png"), fig) # HIDE
end
using Pkg # HIDE
Pkg.status(["GeoMakie", "Proj4", "CairoMakie"]) # HIDE

max_stars_repo_name: MisterBiggs/BeautifulMakie

max_issues_repo_name: MisterBiggs/BeautifulMakie

max_forks_repo_name: MisterBiggs/BeautifulMakie


text:
using SplitDataset
using Documenter

makedocs(;
    modules=[SplitDataset],
    authors="vilim <vilim@neuro.mpg.de> and contributors",
    repo="https://github.com/portugueslab/SplitDataset.jl/blob/{commit}{path}#L{line}",
    sitename="SplitDataset.jl",
    format=Documenter.HTML(;
        prettyurls=get(ENV, "CI", "false") == "true",
        canonical="https://portugueslab.github.io/SplitDataset.jl",
        assets=String[],
    ),
    pages=[
        "Home" => "index.md",
    ],
)

deploydocs(;
    repo="github.com/portugueslab/SplitDataset.jl",
)


text:
cgal_base_dir = joinpath(@__DIR__, "cgal")
download_dir = joinpath(@__DIR__, "downloads")

if !ispath(cgal_base_dir)
    mkpath(download_dir)
    zipfile = download("https://github.com/CGAL/cgal/archive/master.zip", joinpath(download_dir, "master.zip"))

    cd(download_dir) do
        quiet_flag = "-q"
        run(`unzip $quiet_flag $zipfile`)
    end

    mv(joinpath(download_dir, "cgal-master"), cgal_base_dir)
end

# TODO this is a fragile way to find the include dirs for boost, same as what CGAL would find.

sys_include_dir = joinpath(@__DIR__, "usr/include")
mkpath(sys_include_dir)

# cmake makes a bunch of files
cmake_out = begin cd(mktempdir()) do
 read(pipeline(`cmake -L $(cgal_base_dir)`), String)
end
end

m = match(r"Boost include dirs: (?<boost_include_dir>[^\s]*)", cmake_out)
sys_boost_include_dir = joinpath(m[:boost_include_dir], "boost")
symlink(sys_boost_include_dir, joinpath(sys_include_dir, "boost"))


text:
using PkgTemplates

# Set up a template
t = Template(;
    user="rafaqz",             # Your github name
    dir="~/julia",             # Where you want the file
    authors="Rafael Schouten", # Your name
    julia=v"1.5",              # Minimum Julia version is 1.5
    plugins=[
        License(; name="MIT"),          # Use the MIT license
        Git(; manifest=true, ssh=true), # Initialise a git repository in the folder
        GitHubActions(; x86=true),      # Run GitHub Actions on x86 only to start
        Codecov(),                      # Set up code coverage
        Documenter{GitHubActions}(),    # Set up GitHub actions CI
        Develop(),                      # ] dev the package automatically
    ],
)

# Use the template to generate a package
t("TestPackage")

using TestPackage, Revise

# Write this function in TestPackage.jl, then run it!
TestPackage.hello_world()

max_stars_repo_name: EcoJulia/Julia-PhD-course-Copenhagen

max_issues_repo_name: EcoJulia/Julia-PhD-course-Copenhagen

max_forks_repo_name: EcoJulia/Julia-PhD-course-Copenhagen


text:
#Use only via ZMQSer package
# Using Julia's built-in serializer as the ZMQ protocol

function zmq_serialize(socket::ZMQSocket, x, flag::Integer)
    s = memio()
    serialize(s, x)
    # Having built s, we'd like to avoid a second copy operation when
    # we create the ZMQMessage. This is possible using the ZMQ library
    # C function zmq_msg_init_data(), but this function requires a
    # callback as one of its arguments, and hence a C-wrapper. This
    # also requires that we prevent s from being garbage-collected
    # until the callback is called. So the C wrapper should increase
    # the reference count on s, and the callback should decrease it.
    # Here, for simplicity we just make another copy.
    zmsg = ZMQMessage(takebuf_array(s))
    send(socket, zmsg, flag)
end
zmq_serialize(socket::ZMQSocket, x) = zmq_serialize(socket, x, 0)

function zmq_deserialize(socket::ZMQSocket)
    zmsg = recv(socket)
    s = convert(IOStream, zmsg)
    seek(s, 0)  # rewind to beginning
    xf = deserialize(s)
    if isa(xf, Function)
        x = xf()  # deserializer returns a thunk
    else
        x = xf
    end
    # Exceptions should be thrown to support transmission of errors
    # across the socket
    if isa(x, Exception)
        throw(x)
    elseif isa(x, Tuple)
        for i = 1:length(x)
            if isa(x[i], Exception)
                throw(x[i])
            end
        end
    end
    return x
end


text:
using ManifoldMeasures, Manifolds, MeasureTheory, Random
using Test
using ManifoldMeasures: mass, logmass
using Manifolds: ℝ

@testset "Hausdorff" begin
    @testset "basic" begin
        M = Sphere(2)
        d = Hausdorff(M)
        @test d isa Hausdorff{Sphere{2,ℝ},Nothing}
        @test base_manifold(d) === M
        @test d.atlas isa Nothing
        @test sprint(show, "text/plain", d) === "Hausdorff($M, nothing)"
        p = normalize(randn(3))
        @test iszero(logdensity(d, p))
    end

    @testset "manifolds" begin
        @testset "Circle" begin
            @test mass(Hausdorff(Circle(ℝ))) ≈ 2π
            @test mass(Hausdorff(Circle(ℂ))) ≈ 2π
        end

        @testset "Sphere" begin
            @test mass(Hausdorff(Sphere(0))) ≈ 2
            @test mass(Hausdorff(Sphere(1))) ≈ 2π
            @test mass(Hausdorff(Sphere(2))) ≈ 4π
            @test mass(Hausdorff(Sphere(3))) ≈ 2π^2
            for n in 0:10
                @test mass(Hausdorff(Sphere(n, ℂ))) ≈ mass(Hausdorff(Sphere(2n + 1)))
                @test mass(Hausdorff(Sphere(n, ℍ))) ≈ mass(Hausdorff(Sphere(4n + 3)))
            end
        end

        @testset "ProjectiveSpace" begin
            @testset "n=$n" for n in 0:10
                @test mass(Hausdorff(ProjectiveSpace(n))) ≈ mass(Hausdorff(Sphere(n))) / 2
                @test mass(Hausdorff(ProjectiveSpace(n, ℂ))) ≈
                      mass(Hausdorff(Sphere(n, ℂ))) / mass(Hausdorff(Sphere(0, ℂ)))
                @test mass(Hausdorff(ProjectiveSpace(n, ℍ))) ≈
                      mass(Hausdorff(Sphere(n, ℍ))) / mass(Hausdorff(Sphere(0, ℍ)))
            end
        end

        @testset "Stiefel" begin
            function mass_stiefel_recursive(::Stiefel{n,1,𝔽}) where {n,𝔽}
                return mass(Hausdorff(Sphere(n - 1, 𝔽)))
            end
            function mass_stiefel_recursive(::Stiefel{n,k,𝔽}) where {n,k,𝔽}
                return mass(Hausdorff(Sphere(n - 1, 𝔽))) *
                       mass_stiefel_recursive(Stiefel(n - 1, k - 1, 𝔽))
            end
            @testset "Stiefel($n, $k, $𝔽)" for n in 1:10, k in 1:2:n, 𝔽 in (ℝ, ℂ, ℍ)
                k == 1 && @test mass(Hausdorff(Stiefel(n, k, 𝔽))) ≈
                      mass(Hausdorff(Sphere(n - 1, 𝔽)))
                @test mass(Hausdorff(Stiefel(n, k, 𝔽))) ≈
                      mass_stiefel_recursive(Stiefel(n, k, 𝔽))
            end
        end

        @testset "Grassmann" begin
            @testset "Grassmann($n, $k, $𝔽)" for n in 1:10, k in 1:2:n, 𝔽 in (ℝ, ℂ, ℍ)
                k == 1 && @test mass(Hausdorff(Grassmann(n, k, 𝔽))) ≈
                      mass(Hausdorff(ProjectiveSpace(n - 1, 𝔽)))
                @test mass(Hausdorff(Grassmann(n, k, 𝔽))) ≈
                      mass(Hausdorff(Stiefel(n, k, 𝔽))) / mass(Hausdorff(Stiefel(k, k, 𝔽)))
            end
        end

        @testset "$MT" for MT in (Rotations, SpecialOrthogonal)
            @test mass(Hausdorff(MT(1))) ≈ 1
            @test mass(Hausdorff(MT(2))) ≈ 2π
            @test mass(Hausdorff(MT(3))) ≈ 8π^2
        end
    end
end


text:
using PyCall
tf = pyimport("tensorflow")
keras = pyimport("tensorflow.keras")

model = keras.Sequential([
    keras.layers.Dense(10, activation="relu"),
    keras.layers.Dense(1, activation="sigmoid")
])

model.compile(optimizer="adam", loss="mse")

X_train = tf.random.normal([1000, 3])
y_train = tf.random.uniform([1000, 1])
model.fit(X_train, y_train, epochs=100)

X_new = tf.random.normal([2, 3])
model.predict(X_new)


text:
using StemCellModels
using DataFrames
using ProgressMeter
using StatsBase
using Statistics
using Random
using StatsBase
using ArgParse
using CSV
using Distributions
using Dates

println("Starting simulations")

s = ArgParseSettings()
@add_arg_table s begin
    "--resultsfile"
        help = "File to save results"
    "--resultsfile2"
        help = "File to save results"
end

parsed_args = parse_args(ARGS, s)
print(parsed_args)

Random.seed!(123)

#function to simulate population of cells with different paramters
function simulatepopulation(;Δ = 0.0,
        tend = 20.0, Ncells = 1000, r = 0.5, λ = 1.0,
        sample = false, nsample = 10, Nits = 50,
        μp = 0.001, μd = 0.001)

    rangeN = 1:10^4
    Cntd = zeros(length(rangeN), Nits)
    Cntp = zeros(length(rangeN), Nits)
    freq_mut = Float64[]
    SMtog = StemCellModel(Ncells, Δmut = Δ, μp = μp, μd = μd, tend = tend, r = r, λ = λ)
    for i in 1:Nits
        scst = runsimulation(SMtog, progress = false, finish = "time", onedriver = true, restart = true, maxcells = 10^6)
        append!(freq_mut, filter!(x -> x > 0, scst.mutationsize_d))
    end

    return freq_mut
end

myDF = DataFrame([Float64, Float64, Float64, Float64, Float64, Int64, String, Float64], [:f, :delta, :t, :rlam, :mu, :Nsims, :gene, :N0], 0)

for Δ in [0.0, 0.025, 0.05, 0.1]
    for t in [20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0]
        println("$(Dates.format(now(), "HH:MM")  ): Δ = $Δ, t = $t")
        flush(stdout)
        flush(stderr)
        Nsims = 1000
        mu = rand(TruncatedNormal(0.001, 0.0005, 0.0, 10.0))
        N0 = 1000
        freq = simulatepopulation(;Δ = Δ, tend = t,
                                    λ = 0.5, r = 1.0,
                                    Nits = Nsims, μd = mu,
                                    μp = 0.0,
                                    Ncells = N0)
        DFtemp = DataFrame(f = freq, delta = Δ, t = t, rlam = 0.5, mu = mu, Nsims = Nsims, gene = "gene_$(randstring(5))", N0 = N0)
        append!(myDF, DFtemp)
    end
end
#CSV.write("file.csv", myDF)

CSV.write(parsed_args["resultsfile"], myDF)

#function to simulate population of cells with different paramters
function simulatepopulation(;Δ = 0.0,
        tend = 20.0, Ncells = 1000, r = 0.5, λ = 1.0,
        sample = false, nsample = 10, Nits = 50,
        μp = 0.001, μd = 0.001)

    rangeN = 1:10^4
    Cntd = zeros(length(rangeN), Nits)
    Cntp = zeros(length(rangeN), Nits)
    freq_mut = Float64[]
    Δvec = Float64[]
    for i in 1:Nits
        if Δ == 0.0
            Δsample = 0.0
        else
            #Δsample = rand(Beta(0.3, 0.3 * ((1 - Δ) / Δ)))
            Δtemp = rand([0.05])
            if Δtemp == 0.0
                Δsample = 0.0
            else
                Δsample = rand(Exponential(Δtemp))
                #Δsample = Δtemp
            end
        end
        println("Simulation $(i), Δ = $(Δsample)")
        flush(stdout)
        if Δsample > 0.7
            continue
        end
        SMtog = StemCellModel(Ncells, Δmut = Δsample, μp = μp, μd = μd, tend = tend, r = r, λ = λ)
        @time scst = runsimulation(SMtog, progress = false, finish = "time", onedriver = true, restart = true, maxcells = 5 * 10^6)
        append!(freq_mut, filter!(x -> x > 0, scst.mutationsize_d))
        push!(Δvec, Δsample)
    end

    return freq_mut, mean(Δvec)
end

myDF = DataFrame([Float64, Float64, Float64, Float64, Float64, Float64, Int64, String, Float64], [:f, :delta, :deltasample, :t, :rlam, :mu, :Nsims, :gene, :N0], 0)

for Δ in [0.0, 0.1]
    for t in [20.0, 30.0, 40.0, 50.0, 60.0, 70.0]
        println("$(Dates.format(now(), "HH:MM")  ): Δ = $Δ, t = $t\n")
        flush(stdout)
        flush(stderr)
        Nsims = 1000
        mu = rand(TruncatedNormal(0.001, 0.0005, 0.0, 10.0))
        N0 = 1000
        freq, del = simulatepopulation(;Δ = Δ, tend = t,
                                    λ = 0.5, r = 1.0,
                                    Nits = Nsims, μd = mu,
                                    μp = 0.0,
                                    Ncells = N0)
        DFtemp = DataFrame(f = freq, delta = Δ, deltasample = del, t = t, rlam = 0.5, mu = mu, Nsims = Nsims, gene = "gene_$(randstring(5))", N0 = N0)
        append!(myDF, DFtemp)
    end
end
#CSV.write("file.csv", myDF)

CSV.write(parsed_args["resultsfile2"], myDF)


text:
module BandedMatrices
using Base, FillArrays, LazyArrays

using LinearAlgebra, SparseArrays, Random
using LinearAlgebra.LAPACK
import Base: axes1, getproperty, iterate
import LinearAlgebra: BlasInt,
                    BlasReal,
                    BlasFloat,
                    BlasComplex,
                    axpy!,
                    copy_oftype,
                    checksquare,
                    adjoint,
                    transpose,
                    AdjOrTrans, HermOrSym
import LinearAlgebra.BLAS: libblas
import LinearAlgebra.LAPACK: liblapack, chkuplo, chktrans
import LinearAlgebra: cholesky, cholesky!, norm, diag, eigvals!, eigvals,
            qr, axpy!, ldiv!, mul!, lu, lu!, AbstractTriangular, has_offset_axes,
            chkstride1, kron, lmul!, rmul!
import SparseArrays: sparse

import Base: getindex, setindex!, *, +, -, ==, <, <=, >,
                >=, /, ^, \, transpose, showerror, reindex, checkbounds, @propagate_inbounds

import Base: convert, size, view, unsafe_indices,
                first, last, size, length, unsafe_length, step,
                to_indices, to_index, show, fill!, promote_op,
                MultiplicativeInverses, OneTo, ReshapedArray,
                               similar, copy, convert, promote_rule, rand,
                            IndexStyle, real, imag, Slice, pointer, unsafe_convert, copyto!

import Base.Broadcast: BroadcastStyle, AbstractArrayStyle, DefaultArrayStyle, Broadcasted, broadcasted

import LazyArrays: MemoryLayout, blasmul!, @lazymul, @lazylmul, @lazyldiv, @blasmatvec, @blasmatmat,
                    AbstractStridedLayout, AbstractColumnMajor, AbstractRowMajor,
                    _copyto!, MatMulVec, MatMulMat, transposelayout, triangulardata,
                    ConjLayout, conjlayout, SymmetricLayout, symmetriclayout, symmetricdata,
                    triangularlayout, InverseLayout, MatMulVec, MatLdivVec, TriangularLayout,
                    ArrayMulArrayStyle, HermitianLayout, hermitianlayout, hermitiandata
import FillArrays: AbstractFill

export BandedMatrix,
       bandrange,
       brand,
       bandwidth,
       BandError,
       band,
       Band,
       BandRange,
       bandwidths,
       colrange,
       rowrange,
       isbanded,
       Zeros,
       Fill,
       Ones,
       Eye

include("blas.jl")
include("lapack.jl")

include("generic/AbstractBandedMatrix.jl")
include("generic/broadcast.jl")
include("generic/matmul.jl")
include("generic/Band.jl")
include("generic/utils.jl")

include("banded/BandedMatrix.jl")
include("banded/BandedLU.jl")
include("banded/BandedQR.jl")
include("banded/gbmm.jl")
include("banded/linalg.jl")

include("symbanded/symbanded.jl")
include("symbanded/BandedCholesky.jl")

include("tribanded.jl")

include("interfaceimpl.jl")

@deprecate setindex!(A::BandedMatrix, v, b::Band) A[b] .= v
@deprecate setindex!(A::BandedMatrix, v, ::BandRangeType, j::Integer) A[BandRange,j] .= v
@deprecate setindex!(A::BandedMatrix, v, kr::Colon, j::Integer) A[:,j] .= v
@deprecate setindex!(A::BandedMatrix, v, kr::AbstractRange, j::Integer) A[kr,j] .= v
@deprecate setindex!(A::BandedMatrix, v, ::Colon, ::Colon) A[:,:] .= v
@deprecate setindex!(A::BandedMatrix, v, ::Colon) A[:] .= v
@deprecate setindex!(A::BandedMatrix, v, k::Integer, ::BandRangeType) A[k,BandRange] .= v
@deprecate setindex!(A::BandedMatrix, v, k::Integer, jr::AbstractRange) A[k,jr] .= v
@deprecate setindex!(A::BandedMatrix, v, kr::AbstractRange, jr::AbstractRange) A[kr,jr] .= v
@deprecate setindex!(A::BandedMatrix, v, ::BandRangeType) BandedMatrices.bandeddata(A) .= v

end #module


text:
#
# @description Defines the hash-function abstract type and implements helper methods that act on this abstract type.
#
# @author Alejandro Claro (alejandro.claro@gmail.com)
#
# Copyright 2015 All rights reserved.
# Use of this source code is governed by a MIT-style license that can be found in the LICENSE file.
#
export HashFunction
export digest, hexdigest, updater

# @description Defines the hash algorithms abstract type.
abstract type HashFunction end

# @description Continue hashing of a message by consuming the next chunk of data.
#
# @param  {HashFunction}   self The hash algorithm.
# @param  {AbstractString} text The next message chunk.
#
# @return The reference to the updated hash algorithm.
function update!(self::HashFunction, text::AbstractString)
  update!(self, Array{UInt8}(text))
end

# @description Computes the message digest of the given data.
#
# @param {HashFunction}   self The hash algorithm.
# @param {AbstractString} text The input message.
#
# @return {Vector{UInt8}} The message digest.
function digest(self::HashFunction, text::AbstractString)
  return digest(self, Array{UInt8}(text))
end

# @description Computes the message digest of the given data.
#
# @param {HashFunction}  self The hash algorithm.
# @param {Vector{UInt8}} data The input message.
#
# @return {Vector{UInt8}} The message digest.
function digest(self::HashFunction, data::Vector{UInt8})
  context = deepcopy(self)

  reset!(context)
  update!(context, data)

  return digest(context)
end

# @description Gets the digest of the data passed to the update!() method so far.
#
# @param {HashFunction} self The hash algorithm.
#
# @return {Vector{UInt8}} The message digest as a string of double length, containing only hexadecimal digits.
function hexdigest(self::HashFunction)
  return join([string(x, 16, 2) for x in digest(self)])
end

# @description Computes the message digest of the given data.
#
# @param {HashFunction} self The hash algorithm.
# @param {Vector{UInt8}} data The input message.
#
# @return {Vector{UInt8}} The message digest as a string of double length, containing only hexadecimal digits.
function hexdigest(self::HashFunction, data::Vector{UInt8})
  return join([string(x, 16, 2) for x in digest(self, data)])
end

# @description Computes the message digest of the given data.
#
# @param {HashFunction}  self The hash algorithm.
# @param {AbstractString} text The input message.
#
# @return {Vector{UInt8}} The message digest as a string of double length, containing only hexadecimal digits.
function hexdigest(self::HashFunction, data::AbstractString)
  return join([string(x, 16,  2) for x in digest(self, data)])
end

# @description Returns a update function linked to the given hash algorithm data structure.
#
# @param {HashFunction} self The hash algorithm.
#
# @return {Function} A function that only takes one {Vector{UInt8}} argument.
function updater(self::HashFunction)
  return data -> update!(self, data)
end


text:
using Oceananigans.Grids: Center, Face

linear(x) = 0.5x - 3
quadratic(x) = 0.5x^2 -3x + 5

@testset "Coarse Graining" begin
    @testset "Center" begin
        for func in [linear, quadratic]
            @testset "$func" begin
                x = range(0, 100, length=100)
                y = func.(x)

                N = 20
                y_coarse = coarse_grain(y, N, Center())

                @test length(y_coarse) == N
                @test mean(y_coarse) ≈ mean(y_coarse)

                if func == linear
                    @test all(diff(y_coarse) .≈ diff(y_coarse)[1])
                end
            end
        end
    end

    @testset "Face" begin
        for func in [linear, quadratic]
            @testset "$func" begin
                # 102 -> 22 tests the case where the interior can be easily coarse grained like `Center`.
                # 129 -> 33 tests the case where we need to interpolate between grid cells.
                lengths = [(102, 22), (129, 33)]

                for (n, N) in lengths
                    x = range(0, 100, length=n)
                    y = func.(x)

                    y_coarse = coarse_grain(y, N, Face())

                    y_interior = y[2:end-1]
                    y_coarse_interior = y_coarse[2:end-1]

                    @test length(y_coarse) == N
                    @test mean(y_interior) ≈ mean(y_coarse_interior)
                end
            end
        end
    end
end


text:
using Documenter, DrWatson
quickactivate(@__DIR__, "docs")
using BSON, DataFrames, Parameters, Dates

isdir(datadir()) && rm(datadir())

makedocs(modules = [DrWatson],
sitename= "DrWatson",
authors = "George Datseris and contributors.",
doctest = false,
format = Documenter.HTML(
    prettyurls = get(ENV, "CI", nothing) == "true",
    ),
pages = [
    "Introduction" => "index.md",
    "Project Setup" => "project.md",
    "Naming & Saving Simulations" => "name&save.md",
    "Running & Listing Simulations" => "run&list.md",
    "Real World Examples" => "real_world.md"
    ],
assets = ["assets/logo.ico"],
)

if get(ENV, "CI", nothing) == "true"
    deploydocs(repo = "github.com/JuliaDynamics/DrWatson.jl.git",
               target = "build")
end


text:
"""
Author: Eric Ford
Adapted from: https://github.com/eford/RvSpectraKitLearn.jl/blob/master/src/deriv_spectra_gp.jl

Uses brute-force, but could update GaussianProcesses.jl, Stheno.jl, TemporalGPs., KernelFunctions.jl, etc.
Note:  If make faster version using pacakge(s) that take advantage of specific kernels,
       please keep this around since it gets the job done with has minimal dependancies.
"""

"""
Module for interpolating via Gaussian Process Regression.
"""
module GPInterpolation
using PDMats
using LinearAlgebra
using RvSpectMLBase

export make_kernel_data, make_kernel_obs_pred, log_pdf_gp_posterior
#export predict_mean, predict_deriv, predict_deriv2, predict_mean_and_deriv, predict_mean_and_derivs

include("low_level.jl")
include("convenience.jl")
export interp_chunk_to_shifted_grid_gp_brute_force, interp_chunk_to_shifted_grid_gp_brute_force!
export interp_chunk_to_grid_gp_brute_force, interp_chunk_to_grid_gp_brute_force!

end


text:
# some type piracy ...
# TODO: hack like this make #27 important!!!
import Base: *
*(a::SArray{Tuple{L1,L2,L3}}, b::SVector{L3}) where {L1, L2, L3} =
      reshape( reshape(a, L1*L2, L3) * b, L1, L2)

@testset "SymmetricBasis"  begin

#---

using ACE
using StaticArrays, Random, Printf, Test, LinearAlgebra, ACE.Testing
using ACE: evaluate, evaluate_d, SymmetricBasis, NaiveTotalDegree, PIBasis
using ACE.Random: rand_rot, rand_refl
using ACEbase.Testing: fdtest

# Extra using Wigner for computing Wigner Matrix
using ACE.Wigner

# construct the 1p-basis
D = NaiveTotalDegree()
maxdeg = 6
ord = 3

B1p = ACE.Utils.RnYlm_1pbasis(; maxdeg=maxdeg, D = D)

# generate a configuration
nX = 10
Xs = rand(EuclideanVectorState, B1p.bases[1], nX)
cfg = ACEConfig(Xs)

#---

@info("SymmetricBasis construction and evaluation: Invariant Scalar")

φ = ACE.Invariant()
pibasis = PIBasis(B1p, ord, maxdeg; property = φ)
basis = SymmetricBasis(pibasis, φ)

BB = evaluate(basis, cfg)

# a stupid but necessary test
AA = evaluate(basis.pibasis, cfg)
BB1 = basis.A2Bmap * AA
println(@test isapprox(BB, BB1, rtol=1e-10))

for ntest = 1:30
      Xs1 = shuffle(rand_refl(rand_rot(Xs)))
      BB1 = evaluate(basis, ACEConfig(Xs1))
      print_tf(@test isapprox(BB, BB1, rtol=1e-10))
end
println()

## Testing derivatives

@info("  ... Derivatives")
tmpd = ACE.alloc_temp_d(basis, length(cfg))
dB = ACE.evaluate_d(basis, cfg)

for ntest = 1:30
   Us = randn(SVector{3, Float64}, length(Xs))
   c = randn(length(basis))
   F = t -> sum(c .* ACE.evaluate(basis, ACEConfig(Xs + t[1] * Us))).val
   dF = t -> [ Us' * sum(c .* ACE.evaluate_d(basis, ACEConfig(Xs + t[1] * Us)), dims=1)[:] ]
   print_tf(@test fdtest(F, dF, [0.0], verbose=false))
end
println()

#---
@info("SymmetricBasis construction and evaluation: Spherical Vector")

__L2syms = [:s, :p, :d, :f, :g, :h, :i, :k]
__syms2L = Dict( [sym => L-1 for (L, sym) in enumerate(__L2syms)]... )
get_orbsym(L::Integer)  = __L2syms[L+1]

for L = 0:3
      @info "Tests for L = $L ⇿ $(get_orbsym(0))-$(get_orbsym(L)) block"
      φ = ACE.SphericalVector(L; T = ComplexF64)
      pibasis = PIBasis(B1p, ord, maxdeg; property = φ, isreal = false)
      basis = SymmetricBasis(pibasis, φ)
      BB = evaluate(basis, cfg)

      for ntest = 1:10
         Q, D = ACE.Wigner.rand_QD(L)
         cfg1 = ACEConfig( shuffle(Ref(Q) .* Xs) )
         BB1 = evaluate(basis, cfg1)
         DtxBB1 = Ref(D') .* BB1
         print_tf(@test isapprox(DtxBB1, BB, rtol=1e-10))
      end
      println()

      @info(" .... derivatives")
      for ntest = 1:30
         Us = randn(SVector{3, Float64}, length(Xs))
         C = randn(typeof(φ.val), length(basis))
         F = t -> sum( sum(c .* b.val)
                       for (c, b) in zip(C, ACE.evaluate(basis, ACEConfig(Xs + t[1] * Us))) )
         dF = t -> [ sum( sum(c .* db)
                          for (c, db) in zip(C, ACE.evaluate_d(basis, ACEConfig(Xs + t[1] * Us)) * Us) ) ]
         print_tf(@test fdtest(F, dF, [0.0], verbose=false))
      end
      println()
end

#---
@info("SymmetricBasis construction and evaluation: Spherical Matrix")

for L1 = 0:3, L2 = 0:3
   @info "Tests for L₁ = $L1, L₂ = $L2 ⇿ $(get_orbsym(L1))-$(get_orbsym(L2)) block"
   φ = ACE.SphericalMatrix(L1, L2; T = ComplexF64)
   pibasis = PIBasis(B1p, ord, maxdeg; property = φ, isreal = false)
   basis = SymmetricBasis(pibasis, φ)
   BB = evaluate(basis, cfg)

   for ntest = 1:10
      Q, D1, D2 = ACE.Wigner.rand_QD(L1, L2)
      cfg1 = ACEConfig( shuffle(Ref(Q) .* Xs) )
      BB1 = evaluate(basis, cfg1)
      D1txBB1xD2 = Ref(D1') .* BB1 .* Ref(D2)
      print_tf(@test isapprox(D1txBB1xD2, BB, rtol=1e-10))
   end
   println()

   @info(" .... derivatives")
   for ntest = 1:30
      Us = randn(SVector{3, Float64}, length(Xs))
      C = randn(typeof(φ.val), length(basis))
      F = t -> sum( sum(c .* b.val)
                    for (c, b) in zip(C, ACE.evaluate(basis, ACEConfig(Xs + t[1] * Us))) )
      dF = t -> [ sum( sum(c .* db)
                       for (c, db) in zip(C, ACE.evaluate_d(basis, ACEConfig(Xs + t[1] * Us)) * Us) ) ]
      print_tf(@test fdtest(F, dF, [0.0], verbose=false))
   end
   println()
end

#---
@info("Consistency between SphericalVector & SphericalMatrix")

for L = 0:3
   @info "L = $L"
   φ1 = ACE.SphericalVector(L; T = ComplexF64)
   pibasis1 = PIBasis(B1p, ord, maxdeg; property = φ1, isreal = false)
   basis1 = SymmetricBasis(pibasis1, φ1)
   φ2 = ACE.SphericalMatrix(L, 0; T = ComplexF64)
   pibasis2 = PIBasis(B1p, ord, maxdeg; property = φ2, isreal = false)
   basis2 = SymmetricBasis(pibasis2, φ2)

   for ntest = 1:10
      Xs = rand(EuclideanVectorState, B1p.bases[1], nX)
      cfg = ACEConfig(Xs)
      BBvec = evaluate(basis1, cfg)
      value1 = [reshape(BBvec[i].val, 2L+1, 1) for i in 1:length(BBvec)]
      BBmat = evaluate(basis2, cfg)
      value2 = [BBmat[i].val for i in 1:length(BBvec)]
      print_tf(@test isapprox(value1, value2, rtol=1e-10))
   end
   println()
end

#---
@info("Consistency between Invariant Scalar & SphericalMatrix")

φ = ACE.Invariant()
pibasis = PIBasis(B1p, ord, maxdeg; property = φ)
basis = SymmetricBasis(pibasis, φ)
φ2 = ACE.SphericalMatrix(0, 0; T = ComplexF64)
pibasis2 = PIBasis(B1p, ord, maxdeg; property = φ2, isreal = false)
basis2 = SymmetricBasis(pibasis2, φ2)

for ntest = 1:10
   Xs = rand(EuclideanVectorState, B1p.bases[1], nX)
   cfg = ACEConfig(Xs)
   BB = evaluate(basis, cfg)
   BBsca = [BB[i].val for i in 1:length(BB)]
   BB2 =  evaluate(basis2, cfg)
   BBCFlo = [ComplexF64(BB2[i].val...) for i in 1:length(BB2)]
   print_tf(@test isapprox(BBsca, BBCFlo, rtol=1e-10))
end
println()

#---

end


text:
module CUDA

const platform_name = "cuda"
const augment = """
    using Libdl
    using Base: thisminor

    #
    # Augmentation for selecting the CUDA toolkit
    #

    # NOTE: we set the 'cuda' platform tag to the actual CUDA Toolkit version we'll be using
    #       and not to the version that this driver supports (letting Pkg select an artifact
    #       via a comparison strategy). This to simplify dependent packages; otherwise they
    #       would need to know which toolkits are available to additionaly bound selection.

    # provided by caller: `augment_cuda_toolkit!(platform)` method calling the version below
    #                     with the available toolkit versions passed along

    function driver_version()
        libcuda_path = if Sys.iswindows()
            Libdl.find_library("nvcuda")
        else
            Libdl.find_library(["libcuda.so.1", "libcuda.so"])
        end
        if libcuda_path == ""
            return nothing
        end

        libcuda = Libdl.dlopen(libcuda_path)
        try
            function_handle = Libdl.dlsym(libcuda, "cuDriverGetVersion")
            version_ref = Ref{Cint}()
            status = ccall(function_handle, UInt32, (Ptr{Cint},), version_ref)
            if status != 0
                # TODO: warn here about the error?
                return nothing
            end
            major, ver = divrem(version_ref[], 1000)
            minor, patch = divrem(ver, 10)
            return VersionNumber(major, minor, patch)
        finally
            Libdl.dlclose(libcuda)
        end
    end

    function toolkit_version(cuda_toolkits)
        cuda_driver = driver_version()
        if cuda_driver === nothing
            return nothing
        end

        cuda_version_override = get(ENV, "JULIA_CUDA_VERSION", nothing)
        # TODO: support for Preferences.jl-based override?

        # "[...] applications built against any of the older CUDA Toolkits always continued
        #  to function on newer drivers due to binary backward compatibility"
        filter!(cuda_toolkits) do toolkit
            if cuda_version_override !== nothing
                toolkit == cuda_version_override
            elseif cuda_driver >= v"11.1"
                # enhanced compatibility
                #
                # "From CUDA 11 onwards, applications compiled with a CUDA Toolkit release
                #  from within a CUDA major release family can run, with limited feature-set,
                #  on systems having at least the minimum required driver version"
                # TODO: check this minimum required driver version?
                toolkit.major <= cuda_driver.major
            else
                thisminor(toolkit) <= thisminor(cuda_driver)
            end
        end
        if isempty(cuda_toolkits)
            return nothing
        end

        last(cuda_toolkits)
    end

    function augment_cuda_toolkit!(platform::Platform, cuda_toolkits::Vector{VersionNumber})
        haskey(platform, "cuda") && return platform

        cuda_toolkit = toolkit_version(cuda_toolkits)
        platform["cuda"] = if cuda_toolkit !== nothing
            "\$(cuda_toolkit.major).\$(cuda_toolkit.minor)"
        else
            # don't use an empty string here, because Pkg will then load *any* artifact
            "none"
        end

        return platform
    end

    #
    # Augmentation for selecting artifacts that depend on the CUDA toolkit
    #

    # imported by caller: CUDA_Runtime_jll

    function cuda_comparison_strategy(a::String, b::String, a_requested::Bool, b_requested::Bool)
        a = VersionNumber(a)
        b = VersionNumber(b)

        # If both b and a requested, then we fall back to equality:
        if a_requested && b_requested
            return a == b
        end

        # Otherwise, do the comparison between the the single version cap and the single version:
        function is_compatible(artifact::VersionNumber, host::VersionNumber)
            if host >= v"11.0"
                # enhanced compatibility, semver-style
                artifact.major == host.major
            else
                artifact.major == host.major &&
                artifact.minor == host.minor
            end
        end
        if a_requested
            is_compatible(b, a)
        else
            is_compatible(a, b)
        end
    end

    function augment_cuda_dependent!(platform::Platform)
        set_compare_strategy!(platform, "cuda", cuda_comparison_strategy)
        haskey(platform, "cuda") && return platform
        CUDA_Runtime_jll.augment_cuda_toolkit!(platform)
    end"""

function platform(cuda::VersionNumber)
    return "$(cuda.major).$(cuda.minor)"
end

end

max_stars_repo_name: MichelJuillard/Yggdrasil

max_issues_repo_name: MichelJuillard/Yggdrasil

max_forks_repo_name: MichelJuillard/Yggdrasil


text:
mutable struct RenderPass
    mVkDevice::vk.VkDevice
    mInfo::RenderPassCreateInfo
    mClearValues::Vector{vk.VkClearValue}

    mHandleRef::Ref{vk.VkRenderPass}

    function RenderPass(device::vk.VkDevice, info::RenderPassCreateInfo)
        this = new()
        this.mVkDevice = device
        this.mInfo = info
        this.mClearValues = Vector{vk.VkClearValue}()

        this.mHandleRef = Ref{vk.VkRenderPass}()
        if (vk.vkCreateRenderPass(this.mVkDevice, handleRef(this.mInfo), C_NULL, this.mHandleRef) != vk.VK_SUCCESS)
            error("Failed to create render pass!")
        end

        attachments = this.mInfo.mAttachments
        for a in attachments
            if aspectsOf(getFormat(a)) & vk.VK_IMAGE_ASPECT_COLOR_BIT != 0
                push!(this.mClearValues, VkExt.ClearValue(vk.VkClearColorValue((0, 0, 0, 0))))
            elseif aspectsOf(getFormat(a)) & (vk.VK_IMAGE_ASPECT_DEPTH_BIT | vk.VK_IMAGE_ASPECT_STENCIL_BIT) != 0
                push!(this.mClearValues, VkExt.ClearValue(vk.VkClearDepthStencilValue(0, 0)))
            else
                error("RenderPass attachments should have a color or a depth/stencil aspect.")
            end
        end

        return this
    end
end

@class RenderPass

function destroy(this::RenderPass)
    vk.vkDestroyRenderPass(this.mVkDevice, this.mHandleRef[], C_NULL)
    this.mHandleRef = C_NULL
end

function handleRef(this::RenderPass)::Ref{vk.VkRenderPass}
    return this.mHandleRef
end

function getVkDevice(this::RenderPass)::vk.VkDevice
    return this.mVkDevice
end

function getClearValues(this::RenderPass)::Vector{vk.VkClearValue}
    return this.mClearValues
end

function setClearColor(this::RenderPass, color::vk.VkClearColorValue)
    attachments = this.mInfo.getAttachments()
    for i = 1 : length(this.mClearValues)
        if (aspectsOf(attachments[i].getFormat()) &
            vk.VK_IMAGE_ASPECT_COLOR_BIT != 0)
            this.mClearValues[i] = VkExt.ClearValue(color)
        end
    end
end

function setClearColors(this::RenderPass, colors::Vector{vk.VkClearColorValue})
    colorsIdx = 1
    attachments = this.mInfo.getAttachments()
    for i = 1 : length(this.mClearValues)
        if (aspectsOf(attachments[i].getFormat()) &
            vk.VK_IMAGE_ASPECT_COLOR_BIT != 0)
            @assert colorsIdx <= length(colors) "You need to provide as many clear colors as there are " *
                                               "color attachments in your RenderPass."
            this.mClearValues[i] = VkExt.ClearValue(colors[colorsIdx])
            colorsIdx += 1
        end
    end
end

function setClearDepthStencil(this::RenderPass, depthStencil::vk.VkClearDepthStencilValue)
    attachments = this.mInfo.getAttachments()
    for i = 1 : length(this.mClearValues)
        if (aspectsOf(attachments[i].getFormat()) &
           (vk.VK_IMAGE_ASPECT_DEPTH_BIT | vk.VK_IMAGE_ASPECT_STENCIL_BIT) != 0)
            this.mClearValues[i] = VkExt.ClearValue(depthStencil)
        end
    end
end


text:
struct LatLonSeparableDriver{A} <: DriverModel{A}
    mlat::LateralDriverModel
    mlon::LaneFollowingDriver
end

LatLonSeparableDriver(mlat::LateralDriverModel, mlon::LaneFollowingDriver) = LatLonSeparableDriver{LatLonAccel}(mlat, mlon)

get_name(model::LatLonSeparableDriver) = @sprintf("%s + %s", get_name(model.mlat), get_name(model.mlon))
function set_desired_speed!(model::LatLonSeparableDriver, v_des::Float64)
    set_desired_speed!(model.mlon, v_des)
    model
end
function observe!(model::LatLonSeparableDriver, scene::Frame{Entity{S, D, I}}, roadway::Roadway, egoid::I) where {S, D, I}
    observe!(model.mlat, scene, roadway, egoid)
    observe!(model.mlon, scene, roadway, egoid)
    model
end
function Base.rand(rng::AbstractRNG, model::LatLonSeparableDriver{A}) where A
    action_lat = rand(rng, model.mlat)
    action_lon = rand(rng, model.mlon)
    A(action_lat, action_lon)
end
Distributions.pdf(model::LatLonSeparableDriver{A}, a::A) where A = pdf(model.mlat, a.a_lat) * pdf(model.mlon, a.a_lon)
Distributions.logpdf(model::LatLonSeparableDriver{A}, a::A) where A = logpdf(model.mlat, a.a_lat) + logpdf(model.mlon, a.a_lon)


text:
using AbstractPlotting

@testset "draw3d" begin
    mol = sdftomol(joinpath(@__DIR__, "..", "..", "assets", "test", "aspirin_3d.sdf"))
    # These are just tests to see if the call succeeds; they do not test the output
    @test isa(spacefilling(mol), Scene)
    @test isa(spacefilling(mol; radius="covalent"), Scene)
    @test isa(spacefilling(mol; H=false), Scene)
    @test isa(spacefilling(mol; tform=x->2x), Scene)

    @test isa(ballstick(mol), Scene)
    @test isa(ballstick(mol; H=false), Scene)
    @test isa(ballstick(mol; tform=x->2x), Scene)
    @test isa(ballstick(mol; tform=x->2x, markersize=2), Scene)
end


text:
function WeightedMinMaxModel(A,b,C,d,XLB,XUB,VariableDef,YR)

    const RO = 1e-6
    m,n = size(A);
    nObj = size(C)[1];
    MyModel = Model();
    @variable(MyModel,XLB[i] <= X[i=1:n] <= XUB[i],category = VariableType(VariableDef,i))#
    @variable(MyModel,Z)

    @objective(MyModel,Min,Z + RO* sum(sum(C[j,i]*X[i] for i = 1:n) + d[j] for j =1:nObj) )
    # @constraintref Ucons[1:m];
    # @constraintref LAMBDAcons[1:nObj];
    for i = 1:m
         @constraint(MyModel,sum(A[i,j]*X[j] for j = 1:n) >= b[i] )
    end
    for j = 1:nObj
         @constraint(MyModel,sum(C[j,i]*X[i] for i = 1:n) + d[j] - Z <= YR[j] )
    end
    for j = 1:nObj
         @constraint(MyModel,sum(C[j,i]*X[i] for i = 1:n) + d[j] >= YR[j])
    end
    return MyModel;

end


text:
export colvec2vec, colvec,  FuncT, <|
export @todo, @require_impl, @asserteq, @unzip
export FixedQueue, pushpop!, constant_queue, @get!
export °, rotation2D, to_matrix
export HVec
export @kwdef, @_, @set

import DataStructures
using Base: @kwdef
using Underscores: @_
using Setfield: @set
using QuadGK: quadgk
using Parameters: @unpack
using StaticArrays
using AxisArrays
using MacroTools: @capture

Optional{T} = Union{T, Missing}

"A placeholder for unimplmeneted code."
macro todo()
    :(error("TODO: Not implemented."))
end

macro require_impl()
    :(error("Abstract method requires implementation."))
end

macro asserteq(left, right, msgs...)
    msg = isempty(msgs) ? "assertqe failed" : msgs[1]
    ex = string(:($left == $right))
    quote
        @assert(
            (l = $(esc(left))) == (r = $(esc(right))),
            $(esc(msg)) * " | `$l != $r` in assertion `$($ex)`")
    end
end

"""
A typed function with annotated input and output type.
If `a` has type `FuncT{X,Y,F}`, then `a(x)` is equivalent to `a.f(x::X)::Y`.
"""
struct FuncT{X,Y,F} <: Function
    f::F

    FuncT(f::F, ::Type{X}, ::Type{Y}) where {X,Y,F} = new{X,Y,F}(f)
end

@inline function (f::FuncT{X,Y})(x::X)::Y where {X,Y}
    f.f(x)
end

"Convert a 2-D column vector to a 1-D vector.\n"
colvec2vec(x::AbstractMatrix) = begin
    @assert size(x, 2) == 1
    reshape(x, :)
end

colvec2vec(x::AbstractVector) = x

"""
Make a 2-D column vector from a vector.
"""
colvec(x::AbstractVector) = reshape(x, :, 1)

"""
Caller should annotate the return type to help the compiler's type inference
"""
function unzip_impl(a)
    map(x -> getfield.(a, x), fieldnames(eltype(a)))
end

function type_transpose(ty::Expr)::Expr
    @capture(ty, h1_{h2_{elems__}})
    rs = map(x -> :($h1{$x}), elems)
    :($h2{$(rs...)})
end

"""
    @unzip(xs, xs_type)
Unzip a list of tuples into tuples of lists. `xs_type` should match xs's type and must be
provided as a type literal. The macro then use `xs_type` to compute the correct return
type and annotate the result. (This type annotation is usually crucial for the compiler
to perform type inference and generate efficient code.)

```jldoctest
julia> using OneVision: @unzip
       @unzip([(1,"a"),(2,"b")],Vector{Tuple{Int, String}})
([1, 2], ["a", "b"])

julia> @macroexpand @unzip([(1, "a"),(2, "b")],Vector{Tuple{Int,String}})
:(OneVision.unzip_impl([(1, "a"), (2, "b")]::Vector{Tuple{Int, String}})::Tuple{Vector{Int}, Vector{String}})
```
"""
macro unzip(xs, xs_type::Expr)
    result_t = type_transpose(xs_type)
    :(unzip_impl($(esc(xs))::$(esc(xs_type)))::$(esc(result_t)))
    # :(unzip_impl($xs::$xs_type)::$result_t) |> esc
end

macro get!(collection, key, default)
    quote
        col = $(esc(collection))
        k = $(esc(key))
        r = get(col, k, nothing)
        if r === nothing
            col[k] = $(esc(default))
        else
            r
        end
    end
end

"""
A first-in-first-out queue with fixed length. Supporting a `push!` operation that
simultaneously push a value to the end of the queue and pop the value at the head
of the queue.

Implemented using an array with a head pointer.

# Examples
```jldoctest
julia> fq = FixedQueue(1:5)
FixedQueue(len=5, queue=[1, 2, 3, 4, 5])

julia> pushpop!(fq, 10), fq
(1, FixedQueue(len=5, queue=[3, 4, 5, 10, 10]))

julia> collect(fq)
5-element Array{Int64,1}:
  2
  3
  4
  5
 10

julia> foreach(11:20) do x
    pushpop!(fq, x); println(fq)
end
FixedQueue(len=5, queue=[3, 4, 5, 10, 11])
FixedQueue(len=5, queue=[4, 5, 10, 11, 12])
FixedQueue(len=5, queue=[5, 10, 11, 12, 13])
FixedQueue(len=5, queue=[10, 11, 12, 13, 14])
FixedQueue(len=5, queue=[11, 12, 13, 14, 15])
FixedQueue(len=5, queue=[12, 13, 14, 15, 16])
FixedQueue(len=5, queue=[13, 14, 15, 16, 17])
FixedQueue(len=5, queue=[14, 15, 16, 17, 18])
FixedQueue(len=5, queue=[15, 16, 17, 18, 19])
FixedQueue(len=5, queue=[16, 17, 18, 19, 20])
```

"""
mutable struct FixedQueue{T}
    len::Int
    head::Int
    vec::Vector{T}

    function FixedQueue(init::AbstractVector{T}) where T
        vec = convert(Vector{T}, init)
        new{T}(length(vec), 1, vec)
    end
end

function Base.iterate(q::FixedQueue{T}, state::Int = 0) where T
    if state < q.len
        i = mod1(q.head + state, q.len)
        q.vec[i], state+1
    else
        nothing
    end
end

function constant_queue(value::T, q_size; eltype::Type{E} = T)::FixedQueue{E} where {T,E}
    FixedQueue(convert(Vector{E}, fill(value, q_size)))
end

Base.length(q::FixedQueue) = q.len

Base.lastindex(q::FixedQueue) = q.len

Base.eltype(::FixedQueue{T}) where T = T

Base.first(q::FixedQueue) = q.vec[q.head]

Base.getindex(q::FixedQueue, i::Integer) = q.vec[mod1(q.head + i-1, q.len)]
Base.getindex(q::FixedQueue, range::UnitRange) =
    (q.vec[mod1(q.head + i-1, q.len)] for i in range)

# push x to the end of the queue(stack?)
function pushpop!(q::FixedQueue{T}, x)::T where T
    (q.len==0) && return x
    v = q.vec[q.head]
    q.vec[q.head] = x
    q.head = mod1(q.head + 1, q.len)
    v
end

function Base.show(io::IO, q::FixedQueue)
    seq = [i for i in q]
    print(io, "FixedQueue(len=$(q.len), queue=$seq)")
end

module NumericalIntegration
    export integrate_forward, integrate_forward_invariant
    export Euler, RK38

    """
    Numerical integration for differential equation systems.
    """
    @inline function integrate_forward(f, x0::X, tspan::Tuple{T,T}, method, N) where {X,T}
        t0, t1 = tspan
        dt = (t1 - t0)/N
        x::X = x0
        t::T = t0
        for _ in 1:N
            x += method(f, x, dt, t)
            t += dt
        end
        x
    end

    """
    Numerical integration for time-invariant differential equation systems.
    """
    @inline function integrate_forward_invariant(f, x0::X, dt::AbstractFloat, method, N) where {X}
        x::X = x0
        for _ in 1:N
            x += method(f, x, dt)
        end
        x
    end

    @inline function Euler(f, x::X, dt::AbstractFloat)::X where X
        f(x)::X * dt
    end

    @inline function Euler(f, x::X, dt::AbstractFloat, t)::X where X
        f(x, t)::X * dt
    end

    """
    Runge–Kutta 3/8 rule. (4th order method)
    """
    @inline function RK38(f, x::X, dt::AbstractFloat)::X where X
        k1 = f(x)::X
        k2 = f(x+(1/3)k1*dt)::X
        k3 = f(x+dt*((-1/3)k1+k2))::X
        k4 = f(x+dt*(k1-k2+k3))::X
        dt * ((1/8)k1 + (3/8)k2 + (3/8)k3 + (1/8)k4)
    end

    @inline function RK38(f, x::X, dt::AbstractFloat, t)::X where X
        k1 = f(x, t)::X
        k2 = f(x+(1/3)k1*dt, t+(1/3)dt)::X
        k3 = f(x+dt*((-1/3)k1+k2), t+(2/3)dt)::X
        k4 = f(x+dt*(k1-k2+k3), t+dt)::X
        dt * ((1/8)k1 + (3/8)k2 + (3/8)k3 + (1/8)k4)
    end

end

"""
    f <| x = f(x)
"""
<|(f, x) = f(x)

const ° = pi/180

rotation2D(α) =
    @SMatrix [cos(α) -sin(α)
              sin(α)  cos(α)]

to_matrix(xs::AbstractVector{X}) where X =
    [x[i] for x in xs, i in 1:length(X)]

"""
Hybrid Vector with both continuous and discrete parts.
"""
struct HVec{C, D}
    c::C
    d::D
end


text:
module Tournament

  using JSON, HTTP, Dates, TimeZones

  include("Utils.jl")
  include("BaseAPI.jl")

  export TournamentAPI,
          get_account,
          check_new_round,
          daily_submissions_performances,
          daily_user_performances,
          download_current_dataset,
          download_latest_data,
          get_account,
          get_models,
          get_current_round,
          get_account_transactions,
          get_competitions,
          get_dataset_url,
          get_latest_data_url,
          get_leaderboard,
          get_payments,
          get_submission_filenames,
          get_tournaments,
          get_user_activities,
          public_user_profile,
          round_details,
          stake_change,
          stake_decrease,
          stake_drain,
          stake_get,
          stake_increase,
          stake_set,
          submission_status,
          tournament_name2number,
          tournament_number2name,
          upload_predictions

  const PUBLIC_DATASETS_URL = "https://numerai-public-datasets.s3-us-west-2.amazonaws.com"
  const TOURNAMENT = 8

  struct TournamentAPI <: BaseAPI
    public_id::Union{String,Nothing}
    secret_key::Union{String,Nothing}
    tournament::Int
    public_dataset_url::String
  end

  TournamentAPI() = TournamentAPI(nothing, nothing, TOURNAMENT, PUBLIC_DATASETS_URL)

  function TournamentAPI(public_id::String,
                        secret_key::String;
                        tournament::Int=TOURNAMENT)
    return TournamentAPI(public_id, secret_key, tournament, PUBLIC_DATASETS_URL)
  end

  """
    get_account(api::TournamentAPI)::Dict{String,Any}

  Get all information about your account
  """
  get_account(api::TournamentAPI)::Dict{String,Any} = _get_account(api)

  """
    get_models(api::TournamentAPI)::Dict{String,String}

  Get mapping of account model names to model ids for convenience
  """
  get_models(api::TournamentAPI)::Dict{String,String} = _get_models(api)

  """
    get_current_round(api::TournamentAPI)::Union{Real,Nothing}

  Get number of the current active round
  """
  get_current_round(api::TournamentAPI)::Union{Real,Nothing} = _get_current_round(api)

  """
    get_account_transactions(api::TournamentAPI)::Dict{String,Vector}

  Get all your account deposits and withdrawals
  """
  get_account_transactions(api::TournamentAPI)::Dict{String,Vector} = _get_account_transactions(api)

  """
      get_dataset_url(api::TournamentAPI)::String

  Fetch url of the current dataset
  """
  function get_dataset_url(api::TournamentAPI)::String
    query = """
      query(\$tournament: Int!) {
          dataset(tournament: \$tournament)
      }"""

    variables = Dict( "tournament" => api.tournament )

    url = raw_query(api, query, variables=variables)["data"]["dataset"]

    return url
  end

  """
      download_current_dataset(api::TournamentAPI,
                                dest_path::String=".",
                                dest_filename::Union{String,Nothing}=nothing,
                                unzip::Bool=true,
                                show_progress_bar::Bool=true)::String

  Download dataset for the current active round
  """
  function download_current_dataset(api::TournamentAPI;
                                      dest_path::String=".",
                                      dest_filename::Union{String,Nothing}=nothing,
                                      unzip::Bool=true,
                                      show_progress_bar::Bool=true)::String

    if isnothing(dest_filename)
      round_number = get_current_round(api)
      dest_filename = "numerai_dataset_$(round_number).zip"
    else
      if unzip & !endswith(dest_filename, ".zip")
        dest_filename *= ".zip"
      end
    end
    dataset_path = joinpath(dest_path, dest_filename)

    if ispath(dataset_path)
      @warn "target file already exists"
      return dataset_path
    end

    ensure_directory_exists(dest_path)

    url = get_dataset_url(api)
    download_file(url, dataset_path, show_progress_bar=show_progress_bar)

    if unzip
      dataset_name = dest_filename[1:end-4]
      unzip_file(dataset_path, dest_path, dataset_name)
    end

    return dataset_path
  end

  """
      get_latest_data_url(api::TournamentAPI,
                          data_type::String,
                          extension::String)::String

  Fetch url of the latest data url for a specified data type
  """
  function get_latest_data_url(api::TournamentAPI, data_type::String, extension::String)::String
    valid_extensions = ["csv", "csv.xz", "parquet"]
    valid_data_types = [
        "live",
        "training",
        "validation",
        "test",
        "max_test_era",
        "tournament",
        "tournament_ids",
        "example_predictions"
    ]

    # Allow extension to have a "." as the first character
    extension = lstrip(extension, '.')

    # Validate arguments
    if extension ∉ valid_extensions
      msg = "extension must be set to one of $valid_extensions"
      throw(ArgumentError(msg))
    end

    if data_type ∉ valid_data_types
      msg = "data_type must be set to one of $valid_data_types"
      throw(ArgumentError(msg))
    end

    url = "$(api.public_dataset_url)/latest_numerai_$(data_type)_data.$(extension)"

    return url
  end

  function download_latest_data(api::TournamentAPI,
                                data_type::String,
                                extension::String;
                                dest_path::String=".",
                                dest_filename::Union{String,Nothing}=nothing,
                                show_progress_bar::Bool=true)::Nothing
    # set up download path
    if isnothing(dest_filename)
      dest_filename = "latest_numerai_$(data_type)_data.$(extension)"
    end

    dataset_path = joinpath(dest_path, dest_filename)

    # create parent folder if necessary
    ensure_directory_exists(dest_path)

    url = get_latest_data_url(api, data_type, extension)

    download_file(url, dataset_path, show_progress_bar=show_progress_bar)

    return nothing
  end

  """
      get_competitions(api::TournamentAPI)::Vector{Dict}

  Retrieves information about all competitions
  """
  function get_competitions(api::TournamentAPI)::Vector{Dict}
    query = """
      query(\$tournament: Int!) {
        rounds(tournament: \$tournament) {
          number
          resolveTime
          datasetId
          openTime
          resolvedGeneral
          resolvedStaking
          participants
          prizePoolNmr
          prizePoolUsd
          ruleset
        }
      }
    """
    variables = Dict("tournament" => api.tournament)
    result = raw_query(api, query, variables=variables)
    rounds = result["data"]["rounds"]
    for round in rounds
        round["openTime"] = parse_datetime_string(round["openTime"])
        round["resolveTime"] = parse_datetime_string(round["resolveTime"])
        round["prizePoolNmr"] = parse_float_string(round["prizePoolNmr"])
        round["prizePoolUsd"] = parse_float_string(round["prizePoolUsd"])
    end

    return rounds
  end

  """
      get_tournaments(api::TournamentAPI; only_active::Bool=true)::Vector{Dict}

  Retrieves information about all competitions
  """
  function get_tournaments(api::TournamentAPI; only_active::Bool=true)::Vector{Dict}
    query = """
      query {
        tournaments {
          id
          name
          tournament
          active
        }
      }
    """
    data = raw_query(api, query)["data"]["tournaments"]
    if only_active
      data = filter(d -> d["active"], data)
    end
    return data
  end

  """
      get_user_activities(api::TournamentAPI,
                          username::String)::Vector{Dict}

  Get user activities (works for all users!)
  """
  function get_user_activities(api::TournamentAPI, username::String)::Vector{Dict}
    query = """
        query(\$tournament: Int!
              \$username: String!) {
          userActivities(tournament: \$tournament username: \$username) {
            resolved
            roundNumber
            tournament
            submission {
                concordance
                consistency
                date
                liveLogloss
                liveAuroc
                liveCorrelation
                validationLogloss
                validationAuroc
                validationCorrelation
            }
            stake {
                confidence
                date
                nmrEarned
                staked
                usdEarned
                value
                burned
            }
          }
        }
    """
    variables = Dict( "tournament" => api.tournament, "username" => username )
    data = raw_query(api, query, variables=variables)["data"]["userActivities"]
    # filter rounds with no activity
    data = filter(item -> !isnothing(item["submission"]["date"]), data)
    for item in data
        if isnothing(item["stake"])
          delete!(item, "stake")
        elseif isnothing(item["stake"]["date"])
          delete!(item, "stake")
        else
          item["stake"]["date"] = parse_datetime_string(item["stake"]["date"])
          for col in ["confidence", "value", "nmrEarned", "usdEarned"]
            item["stake"][col] = parse_float_string(item["stake"][col])
          end
        end
      item["submission"]["date"] = parse_datetime_string(item["submission"]["date"])
    end
    return data
  end

  """
      get_submission_filenames(api::TournamentAPI;
                                round_num::Union{Int,Nothing}=nothing,
                                model_id::Union{String,Nothing}=nothing)::Vector{Dict}

  Get filenames of the submission of the user
  """
  function get_submission_filenames(api::TournamentAPI;
                                      round_num::Union{Int,Nothing}=nothing,
                                      model_id::Union{String,Nothing}=nothing)::Vector{Dict}
    query = """
      query(\$modelId: String) {
        model(modelId: \$modelId) {
          submissions {
            filename
            selected
            round {
                tournament
                number
            }
          }
        }
      }
    """
    variables = Dict( "modelId" =>  model_id )
    data = raw_query(api, query, variables=variables, authorization=true)["data"]["model"]

    data = filter(item -> item["selected"], data["submissions"])
    filenames = map(item -> Dict(
      "round_num" => item["round"]["number"],
      "tournament" => item["round"]["tournament"],
      "filename" => item["filename"],
    ), data)

    filenames = filter(f -> f["tournament"] == api.tournament, filenames)

    if !isnothing(round_num)
      filenames = filter(f -> f["round_num"] == round_num, filenames)
    end

    sort!(filenames, by=f -> f["round_num"])

    return filenames
  end

  """
      get_payments(api::TournamentAPI;
                    model_id::Union{String,Nothing}=nothing)::Dict{String,Array}

  Get all your payments
  """
  function get_payments(api::TournamentAPI; model_id::Union{String,Nothing}=nothing)::Dict{String,Array}
    # Todo add stakeBonusPayments?
    query = """
      query(\$modelId: String) {
        model(modelId: \$modelId) {
          reputationPayments {
            insertedAt
            nmrAmount
          }
          otherUsdIssuances {
            insertedAt
            usdAmount
          }
          payments {
            nmrAmount
            usdAmount
            tournament
            round {
              number
              openTime
              resolveTime
              resolvedGeneral
              resolvedStaking
            }
          }
        }
      }
    """
    variables = Dict("modelId" => model_id)
    data = raw_query(api, query, variables=variables, authorization=true)["data"]
    payments = data["model"]
    # convert strings to python objects
    for payment in payments["payments"]
      payment["round"]["openTime"] = parse_datetime_string(payment["round"]["openTime"])
      payment["round"]["resolveTime"] = parse_datetime_string(payment["round"]["resolveTime"])
      payment["usdAmount"] = parse_float_string(payment["usdAmount"])
      payment["nmrAmount"] = parse_float_string(payment["nmrAmount"])
    end

    for payment in payments["reputationPayments"]
      payment["nmrAmount"] = parse_float_string(payment["nmrAmount"])
      payment["insertedAt"] = parse_float_string(payment["insertedAt"])
    end

    for payment in payments["otherUsdIssuances"]
      payment["usdAmount"] = parse_float_string(payment["usdAmount"])
      payment["insertedAt"] = parse_float_string(payment["insertedAt"])
    end
    return payments
  end

  """
      submission_status(api::TournamentAPI,
                        model_id::Union{String,Nothing}=nothing)::Union{Dict,Nothing}

  Submission status of the last submission associated with the account
  """
  function submission_status(api::TournamentAPI; model_id::Union{String,Nothing}=nothing)::Union{Dict,Nothing}
    query = """
      query(\$modelId: String) {
          model(modelId: \$modelId) {
            latestSubmission {
              concordance {
                pending
                value
              }
              consistency
              filename
              corrWithExamplePreds
              validationCorrelation
              validationSharpe
              validationFeatureExposure
              validationCorrelation
              validationCorrelationRating
              validationSharpe
              validationSharpeRating
              validationFeatureNeutralMean
              validationFeatureNeutralMeanRating
              validationStd
              validationStdRating
              validationMaxFeatureExposure
              validationMaxFeatureExposureRating
              validationMaxDrawdown
              validationMaxDrawdownRating
              validationCorrPlusMmcSharpe
              validationCorrPlusMmcSharpeRating
              validationMmcMean
              validationMmcMeanRating
              validationCorrPlusMmcSharpeDiff
              validationCorrPlusMmcSharpeDiffRating
            }
          }
        }
    """
    variables = Dict( "modelId" => model_id )
    data = raw_query(api, query, variables=variables, authorization=true)
    latestSubmission = data["data"]["model"]["latestSubmission"]
    if isempty(latestSubmission)
      return nothing
    end
    return latestSubmission[1]
  end

  """
      upload_predictions(api::TournamentAPI, file_path::String, model_id::Union{String,Nothing}=nothing) -> String

  Upload predictions from file
  """
  function upload_predictions(api::TournamentAPI, file_path::String;
                                model_id::Union{String,Nothing}=nothing)::String
    @info "uploading predictions..."
    auth_query = """
      query(\$filename: String! \$tournament: Int! \$modelId: String) {
        submission_upload_auth(filename: \$filename
                              tournament: \$tournament
                              modelId: \$modelId) {
            filename
            url
        }
      }
    """
    variables = Dict(
      "filename" => basename(file_path),
      "tournament" => api.tournament,
      "modelId" => model_id
    )
    submission_resp = raw_query(api, auth_query, variables=variables, authorization=true)
    submission_auth = submission_resp["data"]["submission_upload_auth"]
    headers = haskey(ENV, "NUMERAI_COMPUTE_ID") ? ["x_compute_id"=>ENV["NUMERAI_COMPUTE_ID"],] : []

    open(file_path, "r") do io
      body = read(io)
      HTTP.request("PUT", submission_auth["url"], headers, body)
    end

    create_query = """
      mutation(\$filename: String! \$tournament: Int! \$modelId: String) {
        create_submission(filename: \$filename
                          tournament: \$tournament
                          modelId: \$modelId) {
          id
        }
      }
    """
    variables = Dict(
      "filename" => submission_auth["filename"],
      "tournament" => api.tournament,
      "modelId" => model_id
    )
    create = raw_query(api, create_query, variables=variables, authorization=true)
    submission_id = create["data"]["create_submission"]["id"]

    return submission_id
  end

  """
      check_new_round(api::TournamentAPI; hours::Int=24)

  Check if a new round has started within the last `hours`
  """
  function check_new_round(api::TournamentAPI; hours::Int=24)::Bool
    query = """
      query(\$tournament: Int!) {
        rounds(tournament: \$tournament number: 0) {
          number
          openTime
        }
      }
    """
    variables = Dict("tournament" => api.tournament)
    rounds = raw_query(api, query, variables=variables)["data"]["rounds"]
    if isempty(rounds)
      return false
    end
    round = rounds[1]
    open_time = parse_datetime_string(round["openTime"])
    now_ = now(tz"UTC")
    is_new_round = open_time > DateTime(now_,UTC) - Dates.Hour(hours)
    return is_new_round
  end

  function tournament_number2name(api::TournamentAPI, number::Int)::Union{String,Nothing}
    tournaments = get_tournaments(api, only_active=false)
    dict = Dict(tournament["tournament"] => tournament["name"] for tournament in tournaments)
    return get(dict, number, nothing)
  end

  function tournament_name2number(api::TournamentAPI, name::String)::Union{Int,Nothing}
    tournaments = get_tournaments(api, only_active=false)
    dict = Dict(tournament["name"] => tournament["tournament"] for tournament in tournaments)
    return get(dict, name, nothing)
  end

  """
      get_leaderboard(api::TournamentAPI; limit::Int=50, offset::Int=0)::Vector{Dict}

  Get the current leaderboard
  """
  function get_leaderboard(api::TournamentAPI; limit::Int=50, offset::Int=0)::Vector{Dict}
    query = """
      query(\$limit: Int! \$offset: Int!) {
        v2Leaderboard(limit: \$limit offset: \$offset) {
          bonusPerc
          nmrStaked
          oldStakeValue
          prevRank
          prevStakedRank
          rank
          stakedRank
          reputation
          rolling_score_rep
          tier
          username
          leaderboardBonus
          averageCorrelationPayout
          payoutPending
          payoutSettled
          badges
        }
      }
    """
    variables = Dict( "limit" => limit, "offset" => offset )
    data = raw_query(api, query, variables=variables)["data"]["v2Leaderboard"]
    for item in data
      item["nmrStaked"] = parse_float_string(item["nmrStaked"])
    end
    return data
  end

  """
      stake_set(api::TournamentAPI, username::String, nmr::Union{Float64,String})::Union{Dict,Nothing}

  Set stake to value by decreasing or increasing your current stake
  """
  function stake_set(api::TournamentAPI, username::String, nmr::Union{Float64,String})::Union{Dict,Nothing}
    # fetch current stake
    current = stake_get(api, username)

    # convert everything to decimals
    if isnothing(current)
      current = 0.
    end

    if nmr isa String
      nmr = parse(Float64, nmr)
    end

    if nmr === current
      @info "Stake already at desired value. Nothing to do."
      return nothing
    elseif nmr < current
      return stake_decrease(api, current - nmr)
    elseif nmr > current
      return stake_increase(api, nmr - current)
    end
  end

  """
      stake_get(api::TournamentAPI, username::String)::Float64

  Get your current stake amount
  """
  function stake_get(api::TournamentAPI, username::String)::Float64
    query = """
      query(\$username: String!) {
        v2UserProfile(username: \$username) {
          dailyUserPerformances {
            stakeValue
          }
        }
      }
    """
    variables = Dict("username" => username)

    data = raw_query(api, query, variables=variables)["data"]["v2UserProfile"]["dailyUserPerformances"]

    stake = isempty(data) ? 0.0 : parse_float_string(data[1]["stakeValue"])

    return stake
  end

  """
      stake_change(api::TournamentAPI,
                    nmr::Union{Float64,String};
                    action::String="decrease",
                    model_id::Union{String,Nothing}=nothing)::Dict

  Change stake by `value` NMR
  """
  function stake_change(api::TournamentAPI, nmr::Union{Float64,String};
                        action::String="decrease",
                        model_id::Union{String,Nothing}=nothing)::Dict
    query = """
      mutation(\$value: String! \$type: String! \$tournamentNumber: Int! \$modelId: String) {
          v2ChangeStake(value: \$value type: \$type modelId: \$modelId tournamentNumber: \$tournamentNumber) {
            dueDate
            requestedAmount
            status
            type
          }
      }
    """
    variables = Dict(
      "value" => string(nmr),
      "type" => action,
      "modelId" => model_id,
      "tournamentNumber" => api.tournament
    )
    result = raw_query(api, query, variables=variables, authorization=true)
    stake = result["data"]["v2ChangeStake"]
    stake["requestedAmount"] = parse_float_string(stake["requestedAmount"])
    stake["dueDate"] = parse_datetime_string(stake["dueDate"])
    return stake
  end

  """
      stake_drain(api::TournamentAPI;
                  model_id::Union{String,Nothing}=nothing)::Dict

  Completely remove your stake
  """
  function stake_drain(api::TournamentAPI;
                        model_id::Union{String,Nothing}=nothing)::Dict
    return stake_decrease(api, 11000000, model_id=model_id)
  end

  """
      stake_decrease(api::TournamentAPI, nmr::Union{Float64,String};
                      model_id::Union{String,Nothing}=nothing)::Dict

  Decrease your stake by `value` NMR
  """
  function stake_decrease(api::TournamentAPI, nmr::Union{Float64,String};
                          model_id::Union{String,Nothing}=nothing)::Dict
    return stake_change(api, nmr, action="decrease", model_id=model_id)
  end

  """
      stake_increase(api::TournamentAPI, nmr::Union{Float64,String};
                      model_id::Union{String,Nothing}=nothing)::Dict

  Increase your stake by `value` NMR
  """
  function stake_increase(api::TournamentAPI, nmr::Union{Float64,String};
                          model_id::Union{String,Nothing}=nothing)::Dict
    return stake_change(api, nmr, action="increase", model_id=model_id)
  end

  """
      public_user_profile(api::TournamentAPI, username::String)::Dict

  Fetch the public profile of a user
  """
  function public_user_profile(api::TournamentAPI, username::String)::Dict
    query = """
      query(\$username: String!) {
        v2UserProfile(username: \$username) {
          badges
          historicalNetNmrEarnings
          historicalNetUsdEarnings
          id
          netEarnings
          startDate
          username
          bio
          totalStake
        }
      }
    """
    variables = Dict("username" => username)
    data = raw_query(api, query, variables=variables)["data"]["v2UserProfile"]
    data["startDate"] = parse_datetime_string(data["startDate"])

    return data
  end

  """
      daily_user_performances(api::TournamentAPI, username::String)::Vector{Dict}

  Fetch daily performance of a user
  """
  function daily_user_performances(api::TournamentAPI, username::String)::Vector{Dict}
    query = """
      query(\$username: String!) {
        v2UserProfile(username: \$username) {
          dailyUserPerformances {
            averageCorrelation
            averageCorrelationPayout
            sumDeltaCorrelation
            finalCorrelation
            payoutPending
            payoutSettled
            date
            leaderboardBonus
            rank
            reputation
            rolling_score_rep
            stakeValue
            tier
          }
        }
      }
    """
    variables = Dict("username" => username)
    data = raw_query(api, query, variables=variables)["data"]["v2UserProfile"]
    performances = data["dailyUserPerformances"]

    for perf in performances
      perf["date"] = parse_datetime_string(perf["date"])
    end

    return performances
  end

  """
      round_details(api::TournamentAPI, round_num::Int)::Vector{Dict}

  Fetch all correlation scores of a round
  """
  function round_details(api::TournamentAPI, round_num::Int)::Vector{Dict}
    query = """
      query(\$roundNumber: Int!) {
        v2RoundDetails(roundNumber: \$roundNumber) {
          userPerformances {
            date
            correlation
            username
          }
        }
      }
    """
    variables = Dict("roundNumber" => round_num)
    data = raw_query(api, query, variables=variables)["data"]["v2RoundDetails"]
    performances = data["userPerformances"]

    for perf in performances
      perf["date"] = DateTime(perf["date"], "yyyy-mm-dd")
    end
    return performances
  end

  """
      daily_submissions_performances(api::TournamentAPI, username::String)::Vector{Dict}

  Fetch daily performance of a user's submissions
  """
  function daily_submissions_performances(api::TournamentAPI, username::String)::Vector{Dict}
    query = """
      query(\$username: String!) {
        v2UserProfile(username: \$username) {
          dailySubmissionPerformances {
            date
            correlation
            roundNumber
            mmc
            correlationWithMetamodel
          }
        }
      }
    """
    variables = Dict("username" => username)
    data = raw_query(api, query, variables=variables)["data"]["v2UserProfile"]
    performances = data["dailySubmissionPerformances"]

    for perf in performances
      perf["date"] = parse_datetime_string(perf["date"])
    end

    performances = filter(perf -> !isnothing(perf["date"]), performances)

    sort!(performances, by=x -> (x["roundNumber"], x["date"]), rev=true)

    return performances
  end

end # module


text:
export
	Backend,
	CPU,
	OpenCL,
	CUDA

abstract Backend

immutable CPU <: Backend end

immutable OpenCL <: Backend end

immutable CUDA <: Backend end

max_stars_repo_name: unbornchikken/julia-ml-proto

max_issues_repo_name: unbornchikken/julia-ml-proto

max_forks_repo_name: unbornchikken/julia-ml-proto


text:
"""
   `interp_chunk_to_shifted_grid_sinc!( flux_out, var_out, chunk_of_spectrum, wavelengths, boost_factor )`
Return spectra interpolated onto a grid of points using sinc interpolation.
# Arguments:
- flux_out: (results stored into this array)
- var_out: (results stored into this array)
- chunk_of_spectrum
- wavelengths: AbstractRange or AbstractArray of locations where chunk is to be interpolated to
- boost_factor: divide wavelengths by boost_factor
Optional Arguments:
- Filter: Vector with pre-allocated workspace (if length>=1)
# Returns
- flux_out
"""
function interp_chunk_to_shifted_grid_sinc!( flux_out::AbstractArray{T1,1}, var_out::AbstractArray{T2,1}, chunk::AC, grid::AR, boost_factor::Real; Filter::AbstractVector = zeros(0) ) where {
    T1<:Real, T2<:Real, AC<:AbstractChunkOfSpectrum, AR<:Union{AbstractRange,AbstractArray{T2,1}} }
    @assert size(flux_out) == size(var_out)
    @assert size(flux_out) == size(grid)
    if length(Filter) >= 1
        flux_out .= SincInterpolation.spectra_interpolate(grid./ boost_factor,chunk.λ,chunk.flux, Filter=Filter)
        var_out .= SincInterpolation.spectra_interpolate(grid./ boost_factor,chunk.λ ,chunk.var, Filter=Filter)
    else
        flux_out .= SincInterpolation.spectra_interpolate(grid./ boost_factor,chunk.λ ,chunk.flux)
        var_out .= SincInterpolation.spectra_interpolate(grid ./ boost_factor,chunk.λ,chunk.var)
    end
    return flux_out
end

"""
   `interp_chunk_to_shifted_grid_sinc( chunk_of_spectrum, wavelengths, boost_factor )`
Return spectra interpolated onto a grid of points using sinc interpolation.
# Arguments:
- chunk_of_spectrum
- wavelengths: AbstractRange or AbstractArray of locations where chunk is to be interpolated to
- boost_factor: divide wavelengths by boost_factor
Optional Arguments:
- Filter: Vector with pre-allocated workspace (if length>=1)
# Returns
- flux_out
"""
function interp_chunk_to_shifted_grid_sinc( chunk::AC, grid::AR, boost_factor::Real; Filter::AbstractVector = zeros(0) ) where {  AC<:AbstractChunkOfSpectrum, T2<:Real, AR<:Union{AbstractRange,AbstractArray{T2,1}} }
    flux_out = Array{Float64,1}(undef,length(grid))
    var_out = Array{Float64,1}(undef,length(grid))
    if length(Filter) >= 1
        interp_chunk_to_shifted_grid_sinc!(flux_out, var_out, chunk, grid, boost_factor, Filter=Filter)
    else
        interp_chunk_to_shifted_grid_sinc!(flux_out, var_out, chunk, grid, boost_factor)
    end
    return (flux=flux_out, var=var_out)
end

"""
   `interp_chunk_to_grid_sinc!( flux_out, var_out, chunk_of_spectrum, wavelengths )`
Return spectra interpolated onto a grid of points using sinc interpolation.
# Arguments:
- flux_out: (results stored into this array)
- var_out: (results stored into this array)
- chunk_of_spectrum
- wavelengths: AbstractRange or AbstractArray of locations where chunk is to be interpolated to
Optional Arguments:
- Filter: Vector with pre-allocated workspace (if length>=1)
# Returns
- flux_out
"""
function interp_chunk_to_grid_sinc!( flux_out::AbstractArray{T1,1}, var_out::AbstractArray{T2,1}, chunk::AC, grid::AR; Filter::AbstractVector = zeros(0) ) where {
    T1<:Real, T2<:Real, AC<:AbstractChunkOfSpectrum, AR<:Union{AbstractRange,AbstractArray{T2,1}} }
    @assert size(flux_out) == size(var_out)
    @assert size(flux_out) == size(grid)
    if length(Filter) >= 1
        flux_out .= SincInterpolation.spectra_interpolate(grid,chunk.λ,chunk.flux,Filter=Filter)
        var_out .= SincInterpolation.spectra_interpolate(grid,chunk.λ,chunk.var,Filter=Filter)
    else
        flux_out .= SincInterpolation.spectra_interpolate(grid,chunk.λ,chunk.flux)
        var_out .= SincInterpolation.spectra_interpolate(grid,chunk.λ,chunk.var)
    end
    return flux_out
end

"""
   `interp_chunk_to_grid_sinc( chunk_of_spectrum, wavelengths )`
Return spectra interpolated onto a grid of points using sinc interpolation.
# Arguments:
- chunk_of_spectrum
- wavelengths: AbstractRange or AbstractArray of locations where chunk is to be interpolated to
# Returns
- flux_out
"""
function interp_chunk_to_grid_sinc( chunk::AC, grid::AR ) where {  AC<:AbstractChunkOfSpectrum, T2<:Real, AR<:Union{AbstractRange,AbstractArray{T2,1}} }
    flux_out = Array{Float64,1}(undef,length(grid))
    var_out = Array{Float64,1}(undef,length(grid))
    interp_chunk_to_grid_sinc!(flux_out, var_out, chunk, grid)
    return (flux=flux_out, var=var_out)
end


text:
abstract type AutomataHistory end

struct AutomataBinaryHistory <: AutomataHistory
    states::Vector{AbstractArray{Bool, 1}}
    uncomputed::Vector{Bool}
end
AutomataBinaryHistory() = AutomataBinaryHistory([], [])
function Base.push!(history::AutomataBinaryHistory, state::AbstractArray{Bool, 1}, uncomputed::Bool)
    push!(history.states, state)
    push!(history.uncomputed, uncomputed)
end
Base.length(history::AutomataBinaryHistory) = length(history.states)
Base.iterate(history::AutomataBinaryHistory, state=1) = state > length(history) ? nothing : ((history.states[state], history.uncomputed[state]), state + 1)
Base.getindex(history::AutomataBinaryHistory, idx::Int) = (history.states[idx], history.uncomputed[idx])
Base.firstindex(history::AutomataBinaryHistory) = 1
Base.lastindex(history::AutomataBinaryHistory) = length(history.states)

struct AutomataColorHistory <: AutomataHistory
    states::Vector{Vector{UInt8}}
    uncomputed::Vector{UInt8}
    colors::UInt8
end
AutomataColorHistory(colors::UInt8=0x3) = AutomataColorHistory([], [], colors)
function Base.push!(history::AutomataColorHistory, state::Vector{UInt8}, uncomputed::UInt8)
    push!(history.states, state)
    push!(history.uncomputed, uncomputed)
end
Base.length(history::AutomataColorHistory) = length(history.states)
Base.iterate(history::AutomataColorHistory, state=1) = state > length(history) ? nothing : ((history.states[state], history.uncomputed[state]), state + 1)
Base.getindex(history::AutomataColorHistory, idx::Int) = (history.states[idx], history.uncomputed[idx])
Base.firstindex(history::AutomataColorHistory) = 1
Base.lastindex(history::AutomataColorHistory) = length(history.states)

struct AutomataContinuousHistory <: AutomataHistory
    states::Vector{Vector{Float32}}
    uncomputed::Vector{Float32}
end
AutomataContinuousHistory() = AutomataContinuousHistory([], [])
function Base.push!(history::AutomataContinuousHistory, state::Vector{Float32}, uncomputed::Float32)
    push!(history.states, state)
    push!(history.uncomputed, uncomputed)
end
Base.length(history::AutomataContinuousHistory) = length(history.states)
Base.iterate(history::AutomataContinuousHistory, state=1) = state > length(history) ? nothing : ((history.states[state], history.uncomputed[state]), state + 1)
Base.getindex(history::AutomataContinuousHistory, idx::Int) = (history.states[idx], history.uncomputed[idx])
Base.firstindex(history::AutomataContinuousHistory) = 1
Base.lastindex(history::AutomataContinuousHistory) = length(history.states)


text:
# Type Definitions and Conversions

#Abstract Type Definitions

abstract type AbstractGeometry{T <: Real, N} end
abstract type AbstractPoint{T, N} <: AbstractGeometry{T, N} end
abstract type AbstractLine{T, N} <: AbstractGeometry{T, N} end
abstract type AbstractPlane{T, N} <: AbstractGeometry{T, N} end

# Specific Types
"""
    Point{T, N}
A point in `N` dimensional space stored with the datatype `T`. Has a single field
coordinates which is stored as an `NTuple{N, T}`.
"""
struct Point{T, N} <: AbstractPoint{T, N}
    coordinates::Array{T}
end

Point{T}(args...) where T = Point{T, length(args)}(Array{T}([args...]))
Point(args...) = Point{typeof(args[1])}(args...)

"""
    Line{T, N}
A line which passes through the point `p` and extended using a basis vector `v`
"""
struct Line{T, N} <: AbstractLine{T, N}
    p::Point{T, N}
    v::Array{T}
end

Line(p1::Point{T, N}, p2::Point{T, N}) where N where T = Line{T, N}(p1, p1.coordinates .- p2.coordinates)

"""
    Plane{T, N}
A plane which passes through point `p` and is perpendicular to the normal vector `n`.
"""
struct Plane{T, N} <: AbstractPlane{T, N}
    p::Point{T, N}
    n::Vector{T}
end


text:
# Line plots

function PlotLine(x::AbstractArray{T,1}, y::AbstractArray{T,1};
                  count::Integer = min(length(x), length(y)),
                  xscale::Real = 1.0, x0::Real = 0.0,
                  offset::Integer = 0, stride::Integer = 1,
                  label::String = "") where {T}

    if eltype(x) == Float64
        LibCImPlot.PlotLinedoublePtrdoublePtr(label, x, y, Cint(count),  Float64(xscale), Float64(x0), Cint(offset),
                                          Cint(stride * sizeof(Float64)))
    elseif eltype(x) == Float32
        LibCImPlot.PlotLineFloatPtrFloatPtr(label, x, y, Cint(count),  Float64(xscale), Float64(x0), Cint(offset),
                                        Cint(stride * sizeof(Float32)))
    else
        x = convert.(Float32, x)
        y = convert.(Float32, y)
        LibCImPlot.PlotLineFloatPtrFloatPtr(label, x, y, Cint(count),  Float64(xscale), Float64(x0), Cint(offset),
                                        Cint(stride * sizeof(Float32)))
    end
end

function PlotLine(x::AbstractArray{T1,1}, y::AbstractArray{T2,1}; kwargs...) where {T1,T2}
    (x, y) = promote(x,y)
    PlotLine(x,y; kwargs...)
end

function PlotLine(y::AbstractArray{T,1}; label::String="", count::Integer=length(y),
                  xscale::Real = 1.0, x0::Real = 0.0,
                  offset::Integer=0, stride::Integer=1) where {T}
    if eltype(y) == Float32
        LibCImPlot.PlotLineFloatPtrInt(label, y, Cint(count),  Float64(xscale), Float64(x0), Cint(offset),
                                    Cint(stride * sizeof(Float32)))
    elseif eltype(y) == Float64
        LibCImPlot.PlotLinedoublePtrInt(label, y, Cint(count),  Float64(xscale), Float64(x0), Cint(offset),
                                    Cint(stride * sizeof(Float64)))
    else
        y = convert.(Float32, y)
        LibCImPlot.PlotLineFloatPtrInt(label, y, Cint(count), Float64(xscale), Float64(x0), Cint(offset),
                                    Cint(stride * sizeof(Float32)))
    end
end

function PlotLine(x::UnitRange{<:Integer}, y::AbstractArray{T,1};
                  xscale::Real = 1.0, x0::Real = 0.0,
                  label::String="") where {T}

        count::Cint = length(x)
        offset::Cint = x.start >= 1 ? x.start - 1 : throw("Range out of bounds")

    if eltype(y) == Float32
        stride = Cint(sizeof(Float32))
        LibCImPlot.PlotLineFloatPtrInt(label, y, count,  Float64(xscale), Float64(x0), offset, stride)
    elseif eltype(y) == Float64
        stride = Cint(sizeof(Float64))
        LibCImPlot.PlotLinedoublePtrInt(label, y, count,  Float64(xscale), Float64(x0), offset, stride)
    else
        y = convert.(Float32, y)
        stride = Cint(sizeof(Float32))
        LibCImPlot.PlotLineFloatPtrInt(label, y, count,  Float64(xscale), Float64(x0), offset, stride)
    end
end

function PlotLine(x::StepRange, y::AbstractArray{T,1};
                  xscale::Real = 1.0, x0::Real = 0.0,
                  label::String="") where {T}

    x.stop < 1 && throw("Range out of bounds")
    count::Cint = length(x)
    offset::Cint = x.start >= 1 ? x.start - 1 : throw("Range out of bounds")

    if eltype(y) == Float64
        stride = Cint(x.step * sizeof(Float64))
        LibCImPlot.PlotLinedoublePtrInt(label, y, count, Float64(xscale), Float64(x0), offset, stride)
    elseif eltype(y) == Float32
        stride = Cint(x.step * sizeof(Float32))
        LibCImPlot.PlotLineFloatPtrInt(label, y, count,  Float64(xscale), Float64(x0), offset, stride)
    else
        y = convert.(Float32, y)
        stride = Cint(x.step * sizeof(Float32))
        LibCImPlot.PlotLineFloatPtrInt(label, y, count,  Float64(xscale), Float64(x0), offset, stride)
    end
end


text:
using Surrogates

lb = 0.1
ub = 1.0
n = 100
s = sample(n,lb,ub,GridSample(0.1))
sample(n,lb,ub,UniformSample())
sample(n,lb,ub,SobolSample())
sample(n,lb,ub,LatinHypercubeSample())
sample(20,lb,ub,LowDiscrepancySample(10))
f(x) = x^2
f.(s)

lb = [0.1,-0.5]
ub = [1.0,20.0]
n = 100
s = sample(n,lb,ub,GridSample([0.1,0.5]))
sample(n,lb,ub,UniformSample())
sample(n,lb,ub,SobolSample())
sample(n,lb,ub,LatinHypercubeSample())

f(x) = x[1]+x[2]^2
f.(s)

lb = [1.2,1.2]
ub = [2.0,2.0]
n = 5
sample(n,lb,ub,LatinHypercubeSample())
sample(n,lb,ub,LowDiscrepancySample([10,3]))


text:
module RealNeuralNetworks

include("Utils/include.jl");
include("SWCs.jl");
include("NodeNets.jl");
include("Manifests.jl");
include("Neurons.jl")
include("NeuralNets.jl")
include("NBLASTs.jl")

using .SWCs
using .NodeNets
using .Manifests
using .Neurons
using .NeuralNets
using .NBLASTs

end # end of module


text:
slim = 200

ht = IntegerTriangle[]

for a in 1:slim, b in a:slim, c in b:slim
    isprimheronian(a, b, c) || continue
    push!(ht, IntegerTriangle(a, b, c))
end

sort!(ht, by=x->(x.σ, x.p, x.c))

print("The number of primitive Hernonian triangles having sides ≤ ")
println(slim, " is ", length(ht))

tlim = 10
tlim = min(tlim, length(ht))

println()
println("Tabulating the first (by σ, p, c) ", tlim, " of these:")
println("    a   b   c    σ    p")
for t in ht[1:tlim]
    println(@sprintf "%6d %3d %3d %4d %4d" t.a t.b t.c t.σ t.p)
end

tlim = 210
println()
println("Tabulating those having σ = ", tlim, ":")
println("    a   b   c    σ    p")
for t in ht
    t.σ == tlim || continue
    t.σ == tlim || break
    println(@sprintf "%6d %3d %3d %4d %4d" t.a t.b t.c t.σ t.p)
end

max_stars_repo_name: ethansaxenian/RosettaDecode

max_issues_repo_name: ethansaxenian/RosettaDecode

max_forks_repo_name: ethansaxenian/RosettaDecode


text:
# # `findminmax`

using Transducers
using CUDA
using FoldsCUDA
using FLoops

function findminmax(xs, ex = xs isa CuArray ? CUDAEx() : ThreadedEx())
    xtypemax = typemax(eltype(xs))
    xtypemin = typemin(eltype(xs))
    @floop ex for (i, x) in pairs(xs)
        @reduce() do (imin = -1; i), (xmin = xtypemax; x)
            if xmin > x
                xmin = x
                imin = i
            end
        end
        @reduce() do (imax = -1; i), (xmax = xtypemin; x)
            if xmax < x
                xmax = x
                imax = i
            end
        end
    end
    return (; imin, xmin, imax, xmax)
end

function findminmax_base(xs)
    xmin, imin = findmin(xs)
    xmax, imax = findmax(xs)
    return (; imin, xmin, imax, xmax)
end
nothing  # hide
#-

xs = [700, 900, 500, 200, 700, 700, 900, 300, 600, 400, 900, 600, 900, 800, 600]
if has_cuda_gpu()
    xs = CuArray(xs)
end

result = findminmax(xs)
#-

@assert result == findminmax_base(xs)