text:
# copied from Pkg.jl/src/GitTools.jl

module GitTools

using SHA
import Base: SHA1

@enum GitMode mode_dir=0o040000 mode_normal=0o100644 mode_executable=0o100755 mode_symlink=0o120000 mode_submodule=0o160000
Base.string(mode::GitMode) = string(UInt32(mode); base=8)
Base.print(io::IO, mode::GitMode) = print(io, string(mode))

function gitmode(path::AbstractString)
    # Windows doens't deal with executable permissions in quite the same way,
    # `stat()` gives a different answer than we actually want, so we use
    # `isexecutable()` which uses `uv_fs_access()` internally.  On other
    # platforms however, we just want to check via `stat()`.
    function isexec(p)
        @static if Sys.iswindows()
            return Sys.isexecutable(p)
        end
        return !iszero(filemode(p) & 0o100)
    end
    if islink(path)
        return mode_symlink
    elseif isdir(path)
        return mode_dir
    elseif isexec(path)
        return mode_executable
    else
        return mode_normal
    end
end

"""
    blob_hash(HashType::Type, path::AbstractString)

Calculate the git blob hash of a given path.
"""
function blob_hash(::Type{HashType}, path::AbstractString) where HashType
    ctx = HashType()
    if islink(path)
        datalen = length(readlink(path))
    else
        datalen = filesize(path)
    end

    # First, the header
    SHA.update!(ctx, Vector{UInt8}("blob $(datalen)\0"))

    # Next, read data in in chunks of 4KB
    buff = Vector{UInt8}(undef, 4*1024)

    try
        if islink(path)
            update!(ctx, Vector{UInt8}(readlink(path)))
        else
            open(path, "r") do io
                while !eof(io)
                    num_read = readbytes!(io, buff)
                    update!(ctx, buff, num_read)
                end
            end
        end
    catch e
        if isa(e, InterruptException)
            rethrow(e)
        end
        @warn("Unable to open $(path) for hashing; git-tree-sha1 likely suspect")
    end

    # Finish it off and return the digest!
    return SHA.digest!(ctx)
end
blob_hash(path::AbstractString) = blob_hash(SHA1_CTX, path)

"""
    contains_files(root::AbstractString)

Helper function to determine whether a directory contains files; e.g. it is a
direct parent of a file or it contains some other directory that itself is a
direct parent of a file. This is used to exclude directories from tree hashing.
"""
function contains_files(path::AbstractString)
    st = lstat(path)
    ispath(st) || throw(ArgumentError("non-existent path: $(repr(path))"))
    isdir(st) || return true
    for p in readdir(path)
        contains_files(joinpath(path, p)) && return true
    end
    return false
end

"""
    tree_hash(HashType::Type, root::AbstractString)

Calculate the git tree hash of a given path.
"""
function tree_hash(::Type{HashType}, root::AbstractString) where HashType
    entries = Tuple{String, Vector{UInt8}, GitMode}[]
    for f in readdir(root)
        # Skip `.git` directories
        if f == ".git"
            continue
        end

        filepath = abspath(root, f)
        mode = gitmode(filepath)
        if mode == mode_dir
            # git skips emtpy directories, this doesn't
            hash = tree_hash(HashType, filepath)
        else
            hash = blob_hash(HashType, filepath)
        end
        push!(entries, (f, hash, mode))
    end

    # Sort entries by name (with trailing slashes for directories)
    sort!(entries, by = ((name, hash, mode),) -> mode == mode_dir ? name*"/" : name)

    content_size = 0
    for (n, h, m) in entries
        content_size += ndigits(UInt32(m); base=8) + 1 + sizeof(n) + 1 + sizeof(h)
    end

    # Return the hash of these entries
    ctx = HashType()
    SHA.update!(ctx, Vector{UInt8}("tree $(content_size)\0"))
    for (name, hash, mode) in entries
        SHA.update!(ctx, Vector{UInt8}("$(mode) $(name)\0"))
        SHA.update!(ctx, hash)
    end
    return SHA.digest!(ctx)
end
tree_hash(root::AbstractString) = tree_hash(SHA.SHA1_CTX, root)

end # module

max_stars_repo_name: StefanKarpinski/Tar


text:
logscale(params::AbstractVector{T}) where T <: Real = /(extrema(params)...) < 2e-2 && minimum(params) > 0

logscale(params) = false

@recipe function plot(ho::Hyperoptimizer)
    N = length(ho.params)
    layout --> N
    for i = 1:N
        params = getindex.(ho.history, i)
        perm = sortperm(params)
        yguide --> "Function value"
        seriestype --> :scatter
        @series begin
            xguide --> ho.params[i]
            subplot --> i
            label --> "Sampled points"
            legend --> false
            xscale --> (logscale(params) ? :log10 : :identity)
            yscale --> (logscale(ho.results) ? :log10 : :identity)
            params[perm], ho.results[perm]
        end

    end
end

ext: jl


text:
# General case - to be used with bc::NoBC or m::PrescribedXModels
function soil_boundary_flux!(
    nf,
    bc::AbstractBoundaryConditions,
    m::AbstractSoilComponentModel,
    land::LandModel,
    state⁺::Vars,
    diff⁺::Vars,
    aux⁺::Vars,
    nM,
    state⁻::Vars,
    diff⁻::Vars,
    aux⁻::Vars,
    t,
    _...,
) end

function soil_boundary_state!(
    nf,
    bc::AbstractBoundaryConditions,
    m::AbstractSoilComponentModel,
    land::LandModel,
    state⁺::Vars,
    aux⁺::Vars,
    nM,
    state⁻::Vars,
    aux⁻::Vars,
    t,
    _...,
)

end

# Dirichlet Methods for SoilHeat and SoilWater

"""
    function soil_boundary_state!(
        nf,
        bc::Dirichlet,
        water::SoilWaterModel,
        land::LandModel,
        state⁺::Vars,
        aux⁺::Vars,
        nM,
        state⁻::Vars,
        aux⁻::Vars,
        t,
    )

The Dirichlet-type method for `soil_boundary_state!` for the
`SoilWaterModel`.
"""
function soil_boundary_state!(
    nf,
    bc::Dirichlet,
    water::SoilWaterModel,
    land::LandModel,
    state⁺::Vars,
    aux⁺::Vars,
    nM,
    state⁻::Vars,
    aux⁻::Vars,
    t,
    _...,
)
    bc_function = bc.state_bc
    state⁺.soil.water.ϑ_l = bc_function(aux⁻, t)

end

"""
    function soil_boundary_state!(
        nf,
        bc::Dirichlet,
        heat::SoilHeatModel,
        land::LandModel,
        state⁺::Vars,
        aux⁺::Vars,
        nM,
        state⁻::Vars,
        aux⁻::Vars,
        t,
    )

The Dirichlet-type method for `soil_boundary_state!` for the
`SoilHeatModel`.
"""
function soil_boundary_state!(
    nf,
    bc::Dirichlet,
    heat::SoilHeatModel,
    land::LandModel,
    state⁺::Vars,
    aux⁺::Vars,
    nM,
    state⁻::Vars,
    aux⁻::Vars,
    t,
    _...,
)
    bc_function = bc.state_bc
    param_set = parameter_set(land)
    ϑ_l, θ_i = get_water_content(land.soil.water, aux⁻, state⁻, t)
    θ_l = volumetric_liquid_fraction(ϑ_l, land.soil.param_functions.porosity)
    ρc_s = volumetric_heat_capacity(
        θ_l,
        θ_i,
        land.soil.param_functions.ρc_ds,
        param_set,
    )

    ρe_int_bc =
        volumetric_internal_energy(θ_i, ρc_s, bc_function(aux⁻, t), param_set)

    state⁺.soil.heat.ρe_int = ρe_int_bc
end

# Neumann conditions for SoilHeat and SoilWater

"""
    function soil_boundary_flux!(
        nf,
        bc::Neumann,
        water::SoilWaterModel,
        land::LandModel,
        state⁺::Vars,
        diff⁺::Vars,
        aux⁺::Vars,
        n̂,
        state⁻::Vars,
        diff⁻::Vars,
        aux⁻::Vars,
        t,
    )

The Neumann method for `soil_boundary_flux!` for the
`SoilWaterModel`.
"""
function soil_boundary_flux!(
    nf,
    bc::Neumann,
    water::SoilWaterModel,
    land::LandModel,
    state⁺::Vars,
    diff⁺::Vars,
    aux⁺::Vars,
    n̂,
    state⁻::Vars,
    diff⁻::Vars,
    aux⁻::Vars,
    t,
    _...,
)
    bc_function = bc.scalar_flux_bc
    # See documentation for `Neumann`. The user supplies f = scalar_flux_bc
    # such that F⃗ = -K∇h = -f n̂.
    # Since the BC is on K∇h, no minus sign is needed.
    diff⁺.soil.water.K∇h = n̂ * bc_function(aux⁻, t)
end

"""
    function soil_boundary_flux!(
        nf,
        bc::Neumann,
        heat::SoilHeatModel,
        land::LandModel,
        state⁺::Vars,
        diff⁺::Vars,
        aux⁺::Vars,
        n̂,
        state⁻::Vars,
        diff⁻::Vars,
        aux⁻::Vars,
        t,
    )

The Neumann method for `soil_boundary_flux!` for the
`SoilHeatModel`.
"""
function soil_boundary_flux!(
    nf,
    bc::Neumann,
    heat::SoilHeatModel,
    land::LandModel,
    state⁺::Vars,
    diff⁺::Vars,
    aux⁺::Vars,
    n̂,
    state⁻::Vars,
    diff⁻::Vars,
    aux⁻::Vars,
    t,
    _...,
)
    bc_function = bc.scalar_flux_bc
    # See documentation for `Neumann`. The user supplies f = scalar_flux_bc
    # such that F⃗ = -κ∇T = -f n̂.
    # Since the BC is on κ∇T, no minus sign is needed.
    diff⁺.soil.heat.κ∇T = n̂ * bc_function(aux⁻, t)
end

# SurfaceDriven conditions for for SoilHeat and SoilWater

"""
    function soil_boundary_flux!(
        nf,
        bc::SurfaceDrivenWaterBoundaryConditions,
        water::SoilWaterModel,
        land::LandModel,
        state⁺::Vars,
        diff⁺::Vars,
        aux⁺::Vars,
        n̂,
        state⁻::Vars,
        diff⁻::Vars,
        aux⁻::Vars,
        t,
    )

The Surface Driven BC method for `soil_boundary_flux!` for the
`SoilWaterModel`.
"""
function soil_boundary_flux!(
    nf,
    bc::SurfaceDrivenWaterBoundaryConditions,
    water::SoilWaterModel,
    land::LandModel,
    state⁺::Vars,
    diff⁺::Vars,
    aux⁺::Vars,
    n̂,
    state⁻::Vars,
    diff⁻::Vars,
    aux⁻::Vars,
    t,
    _...,
)

    diff⁺.soil.water.K∇h = compute_surface_grad_bc(
        land.soil,
        bc.runoff_model,
        bc.precip_model,
        n̂,
        state⁻,
        diff⁻,
        aux⁻,
        t,
    )

end

"""
    soil_boundary_flux!(
        nf,
        bc::SurfaceDrivenHeatBoundaryConditions,
        heat::SoilHeatModel,
        land::LandModel,
        state⁺::Vars,
        diff⁺::Vars,
        aux⁺::Vars,
        n̂,
        state⁻::Vars,
        diff⁻::Vars,
        aux⁻::Vars,
        t,
    )

The Surface Driven BC method for `soil_boundary_flux!` for the
`SoilHeatModel`.
"""
function soil_boundary_flux!(
    nf,
    bc::SurfaceDrivenHeatBoundaryConditions,
    heat::SoilHeatModel,
    land::LandModel,
    state⁺::Vars,
    diff⁺::Vars,
    aux⁺::Vars,
    n̂,
    state⁻::Vars,
    diff⁻::Vars,
    aux⁻::Vars,
    t,
    _...,
)

    net_surface_flux = compute_net_radiative_energy_flux(bc.nswf_model, t)
    diff⁺.soil.heat.κ∇T = n̂ * (-net_surface_flux)
end


text:
"""
    solve_decomposition_by_id(manager::ExperimentManager, instance_name, added_edges; resolve=false)

Retrieve the data from the database and solve one decomposition.
"""
function solve_decomposition(manager::ExperimentManager,
                             instance_name::String,
                             oid::Union{UUID,AbstractString},
                             set_cholesky_time_limit::Bool=true,
                             mpi_infos::AbstractDict=Dict();
                             time_limit::Float64=100000.)
    paths = db.getOPFpath_one(manager.instances, instance_name)
    path_opf_ctr = paths["ctr"]
    path_opf_mat = paths["mat"]
    solve_decomposition(manager,
                        instance_name,
                        oid,
                        path_opf_ctr,
                        path_opf_mat,
                        set_cholesky_time_limit,
                        mpi_infos;
                        time_limit=time_limit)
end

"""
    solve_decomposition(manager::ExperimentManager, instance_name, added_edges, path_opf_ctr, path_opf_mat; resolve=false)

Solve one decomposition.
"""
function solve_decomposition(manager::ExperimentManager,
                             instance_name::String,
                             oid::Union{UUID,AbstractString},
                             path_opf_ctr::String,
                             path_opf_mat::String,
                             set_cholesky_time_limit::Bool=true,
                             mpi_infos::AbstractDict=Dict();
                             path_mosek::AbstractString=joinpath("data", "mosek_logs", instance_name, "$instance_name.log"),
                             time_limit::Float64=100000.)
    decomposition = db.getdecomposition(manager.decompositions, instance_name, oid)
    instance_name = decomposition["_id"]["instance_name"]
    if decomposition["nb_added_edges"] != 0 && set_cholesky_time_limit
        time_cholesky = db.getcholeskytime(manager.decompositions, instance_name)
        if !isnothing(time_cholesky)
            time_limit = time_cholesky * 2.
            @info "Computing time limit: $instance_name: $time_limit"
        end
    end
    cliques = decomposition["cliques"]
    cliquetree = decomposition["cliquetree"]
    time, nb_iter, path_mosek, objective, m, nlc = slv.solve_sdp(instance_name,
                                                                 cliques,
                                                                 cliquetree,
                                                                 path_opf_ctr,
                                                                 path_opf_mat;
                                                                 time_limit=time_limit)
    #time = parse(Float64, time)
    features = Mongoc.BSON("solver" => Mongoc.BSON("solving_time" => time,
                                                   "nb_iter" => nb_iter,
                                                   "nonzerosfactor" => readf.get_nonzeros_factor(path_mosek),
                                                   "objective" => objective,
                                                   "m" => m,
                                                   "nlc" => nlc,
                                                   "molzahn_heuristic" => compute_molzahn_heuristic(cliques, m, nlc)))
    fields = Mongoc.BSON("paths.mosek_log" => path_mosek)
    db.setfields_decomposition!(manager.decompositions, instance_name, oid, fields)
    db.setfeatures_decomposition!(manager.decompositions, instance_name, oid, features)
    !isempty(mpi_infos) && db.setMPIinfos(manager.decompositions, instance_name, oid, mpi_infos)
end

max_stars_repo_name: charlyalizadeh/OPFdecgen

max_issues_repo_name: charlyalizadeh/OPFdecgen

max_forks_repo_name: charlyalizadeh/OPFdecgen


text:
"""
    FullBernsteinForm{T, PT<:AbstractPolynomialLike{T},
                      D, N, MC} <: AbstractBernsteinForm{T}

Type defining a full (i.e. explicit) Bernstein form of a polynomial over a
hyperrectangular domain.

### Fields

- `pol`         -- polynomial in one or several variables
- `dom`         -- hyperrectangular set of type `IntervalBox` representing the
                   domain of the expansion
- `numvars`     -- number of variables in the polynomial
- `coeffs`      -- multi-dimensional array that holds the Bernstein coefficients
- `numcoeffs`   -- integer holding the number of Bernstein coefficients that are
                   implicitly defined
- `degs`        -- vector of degrees of the Bernstein polynomial for each variables

### Examples
"""
struct FullBernsteinForm{T, PT<:AbstractPolynomialLike{T},
                         D, N, MC, VD<:AbstractVector{Int}} <: AbstractBernsteinForm{T}
    pol::PT
    dom::IntervalBox{D, N}
    numvars::Int
    coeffs::MC
    numcoeffs::Int
    degs::VD
end

# univariate case is not special cased
function FullBernsteinForm(pol::PT, dom::Interval, args...) where {T, PT<:AbstractPolynomialLike}
    FullBernsteinForm(pol, IntervalBox(dom), args...)
end

#=
# constructor from
function FullBernsteinForm(pol::PT, dom::IntervalBox, args...) where {T, PT<:AbstractPolynomialLike}
    numvars = nvariables(pol)

end
=#

max_stars_repo_name: JuliaReach/BernsteinExpansions

max_issues_repo_name: JuliaReach/BernsteinExpansions

max_forks_repo_name: JuliaReach/BernsteinExpansions


text:
"""
Zalgo.jl does two things.

- It adds pointless diacritics to text: `zalgo("Cthulhu")`

- It converts an input ASCII string to equivalent characters found in the darkest recesses of the Unicode charts:

```
blackboard("Hello World")              # "ℍ𝕖𝕝𝕝𝕠 𝕎𝕠𝕣𝕝𝕕"
boldfraktur("Hello World")             # "𝕳𝖊𝖑𝖑𝖔 𝖂𝖔𝖗𝖑𝖉"
bolditalic("Hello World")              # "𝑯𝒆𝒍𝒍𝒐 𝑾𝒐𝒓𝒍𝒅"
bolditalicsans("Hello World")          # "𝙃𝙚𝙡𝙡𝙤 𝙒𝙤𝙧𝙡𝙙"
boldroman("Hello World")               # "𝐇𝐞𝐥𝐥𝐨 𝐖𝐨𝐫𝐥𝐝"
boldsans("Hello World")                # "𝗛𝗲𝗹𝗹𝗼 𝗪𝗼𝗿𝗹𝗱"
boldscript("Hello World")              # "𝓗𝓮𝓵𝓵𝓸 𝓦𝓸𝓻𝓵𝓭"
fraktur("Hello World")                 # "ℌ𝖊𝖑𝖑𝖔 𝔚𝖔𝖗𝖑𝖉"
italic("Hello World")                  # "𝐻𝑒𝑙𝑙𝑜 𝑊𝑜𝑟𝑙𝑑"
italicsans("Hello World")              # "𝘏𝘦𝘭𝘭𝘰 𝘞𝘰𝘳𝘭𝘥"
sans("Hello World")                    # "𝖧𝖾𝗅𝗅𝗈 𝖶𝗈𝗋𝗅𝖽"
script("Hello World")                  # "ℋℯ𝓁𝓁ℴ 𝒲ℴ𝓇𝓁𝒹"
teletype("Hello World")                # "𝙷𝚎𝚕𝚕𝚘 𝚆𝚘𝚛𝚕𝚍"
upsidedown("Hello World")              # "Hǝןןo Moɹןp"
circled("HELLO WORLD")                 # "ⒽⒺⓁⓁⓄ ⓌⓄⓇⓁⒹ"
boxed("hello world")                   # "🅷🅴🅻🅻🅾 🆆🅾🆁🅻🅳"
segmented("0123456789")                # "🯰🯱🯲🯰🯱🯲🯰🯱🯲"
```
"""
module Zalgo

export zalgo, boldfraktur, bolditalic, bolditalicsans,
boldroman, boldsans, boldscript, fraktur, italic,
italicsans, sans, script, teletype, upsidedown, blackboard,
boxed, circled, segmented

const updc = vcat('\u0300':'\u0315', '\u031A', '\u033D',
    '\u034A':'\u034C', '\u0350':'\u0352',
    '\u0357':'\u0358', '\u035B', '\u035D', '\u035E',
    '\u0360':'\u0361', '\u0363':'\u036F',
    '\uFE20':'\uFE22')

const middledc = vcat('\u031B', '\u0334':'\u0338')

const downdc = vcat('\u0316':'\u0319', '\u031C':'\u0333',
    '\u0339':'\u033C', '\u0347':'\u0349',
    '\u034D':'\u034E', '\u0353':'\u0356', '\u0359',
    '\u035A', '\u035C', '\u035F','\u0362')

const upsidedowndict = Dict{String, String}("a" => "ɐ",
    "b" => "q", "c" => "ɔ", "d" => "p", "e" => "ǝ", "f" => "ɟ", "g" => "ƃ",
    "h" => "ɥ", "i" => "ı", "j" => "ɾ", "k" => "ʞ", "l" => "ן", "m" => "ɯ",
    "n" => "u", "o" => "o", "p" => "d", "q" => "b", "r" => "ɹ", "s" => "s",
    "t" => "ʇ", "u" => "n", "v" => "ʌ", "w" => "ʍ", "x" => "x", "y" => "ʎ",
    "z" => "z", "A" => "∀", "B" => "𐐒", "C" => "Ɔ", "D" => "◖", "E" => "Ǝ",
    "F" => "Ⅎ", "G" => "⅁", "H" => "H", "I" => "I", "J" => "ſ", "K" => "⋊",
    "L" => "˥", "M" => "W", "N" => "N", "O" => "O", "P" => "Ԁ", "Q" => "Ό",
    "R" => "ᴚ", "S" => "S", "T" => "⊥", "U" => "∩", "V" => "Λ", "W" => "M",
    "X" => "X", "Y" => "⅄", "Z" => "Z", "0" => "0", "1" => "Ɩ", "2" => "ᄅ",
    "3" => "Ɛ", "4" => "ㄣ", "5" => "ϛ", "6" => "9", "7" => "ㄥ", "8" => "8",
    "9" => "6", " " => " ")

# These are a shambles, Unicode Consortium!
# build the fraktur dict
frakturdict = Dict{String, Char}()
[frakturdict[string(Char(i + 64))] = vcat(
    '\U1D504',  # A
    '\U1D505',  # B
    '\u212d',   # C !
    '\U1D507',  # D
    '\U1D508',  # E
    '\U1D509',  # F
    '\U1D50a',  # G
    '\u210c',   # H !
    '\u2111',   # I !
    '\U1D50d',  # J
    '\U1D50e',  # K
    '\U1D50f',  # L
    '\U1D510',  # M
    '\U1D511',  # N
    '\U1D512',  # O
    '\U1D513',  # P
    '\U1D514',  # Q
    '\u211c',   # R !
    '\U1D516',  # S
    '\U1D517',  # T
    '\U1D518',  # U
    '\U1D519',  # V
    '\U1D51a',  # W
    '\U1D51b',  # X
    '\U1D51c',  # Y
    '\u2128'    # Z !
    )[i] for i = 1:26]
[frakturdict[string(Char(i + 96))] = vcat('\U1D586':'\U1D59F')[i] for i = 1:26]
frakturdict[" "] = ' '

# build the blackboard dict
blackboarddict = Dict{String, Char}()
[blackboarddict[string(Char(i + 64))] = vcat(
    '\U1D538',  # A
    '\U1D539',  # B
    '\u2102',   # C !
    '\U1D53B',  # D
    '\U1D53c',  # E
    '\U1D53d',  # F
    '\U1D53e',  # G
    '\u210D',   # H !
    '\U1D540',  # I !
    '\U1D541',  # J
    '\U1D542',  # K
    '\U1D543',  # L
    '\U1D544',  # M
    '\u2115',   # N !
    '\U1D546',  # O
    '\u2119',   # P !
    '\u211a',   # Q !
    '\u211d',   # R
    '\U1D54A',  # S
    '\U1D54B',  # T
    '\U1D54C',  # U
    '\U1D54D',  # V
    '\U1D54E',  # W
    '\U1D54f',  # X
    '\U1D550',  # Y
    '\u2124'    # Z !
    )[i] for i = 1:26]
[blackboarddict[string(Char(i + 96))] = vcat('\U1D552':'\U1D56B')[i] for i = 1:26]
blackboarddict[" "] = ' '

# build the Script dict
scriptdict = Dict{String, Char}()
[scriptdict[string(Char(i + 64))] = vcat('\U1D49C':'\U1D4B5')[i] for i = 1:26]
[scriptdict[string(Char(i + 96))] = vcat('\U1D4b6':'\U1D4cf')[i] for i = 1:26]
scriptdict["B"] = '\u212c'
scriptdict["E"] = '\u2130'
scriptdict["F"] = '\u2131'
scriptdict["H"] = '\u210b'
scriptdict["I"] = '\u2110'
scriptdict["L"] = '\u2112'
scriptdict["M"] = '\u2133'
scriptdict["R"] = '\u211B'
scriptdict["e"] = '\u212f'
scriptdict["g"] = '\u210a'
scriptdict["o"] = '\u2134'
scriptdict[" "] = ' '

# build the boldroman dict
boldromandict = Dict{String, Char}()
[boldromandict[string(Char(i + 64))] = vcat('\U1D400':'\U1D419')[i] for i = 1:26]
[boldromandict[string(Char(i + 96))] = vcat('\U1D41a':'\U1D433')[i] for i = 1:26]
boldromandict[" "] = ' '

# build the italic dict
italicdict = Dict{String, Char}()
[italicdict[string(Char(i + 64))] = vcat('\U1D434':'\U1D44d')[i] for i = 1:26]
[italicdict[string(Char(i + 96))] = vcat('\U1D44e':'\U1D467')[i] for i = 1:26]
italicdict[" "] = ' '

# build the bolditalic dict
bolditalicdict = Dict{String, Char}()
[bolditalicdict[string(Char(i + 64))] = vcat('\U1D468':'\U1D481')[i] for i = 1:26]
[bolditalicdict[string(Char(i + 96))] = vcat('\U1D482':'\U1D49b')[i] for i = 1:26]
bolditalicdict[" "] = ' '

# build the boldscript dict
boldscriptdict = Dict{String, Char}()
[boldscriptdict[string(Char(i + 64))] = vcat('\U1D4D0':'\U1D4E9')[i] for i = 1:26]
[boldscriptdict[string(Char(i + 96))] = vcat('\U1D4ea':'\U1D503')[i] for i = 1:26]
boldscriptdict[" "] = ' '

# build the boldfraktur dict
boldfrakturdict = Dict{String, Char}()
[boldfrakturdict[string(Char(i + 64))] = vcat('\U1D56c':'\U1D585')[i] for i = 1:26]
[boldfrakturdict[string(Char(i + 96))] = vcat('\U1D586':'\U1D59f')[i] for i = 1:26]
boldfrakturdict[" "] = ' '

# build the sans dict
sansdict = Dict{String, Char}()
[sansdict[string(Char(i + 64))] = vcat('\U1D5A0':'\U1D5B9')[i] for i = 1:26]
[sansdict[string(Char(i + 96))] = vcat('\U1D5ba':'\U1D5d3')[i] for i = 1:26]
sansdict[" "] = ' '

# build the boldsans dict
boldsansdict = Dict{String, Char}()
[boldsansdict[string(Char(i + 64))] = vcat('\U1D5d4':'\U1D5ed')[i] for i = 1:26]
[boldsansdict[string(Char(i + 96))] = vcat('\U1D5ee':'\U1D607')[i] for i = 1:26]
boldsansdict[" "] = ' '

# build the italicsans dict
italicsansdict = Dict{String, Char}()
[italicsansdict[string(Char(i + 64))] = vcat('\U1D608':'\U1D621')[i] for i = 1:26]
[italicsansdict[string(Char(i + 96))] = vcat('\U1D622':'\U1D63b')[i] for i = 1:26]
italicsansdict[" "] = ' '

# build the bolditalicsans dict
bolditalicsansdict = Dict{String, Char}()
[bolditalicsansdict[string(Char(i + 64))] = vcat('\U1D63c':'\U1D655')[i] for i = 1:26]
[bolditalicsansdict[string(Char(i + 96))] = vcat('\U1D656':'\U1D66f')[i] for i = 1:26]
bolditalicsansdict[" "] = ' '

# build the teletype dict
ttdict = Dict{String, Char}()
[ttdict[string(Char(i + 64))] = vcat('\U1D670':'\U1D689')[i] for i = 1:26]
[ttdict[string(Char(i + 96))] = vcat('\U1D68a':'\U1D6a3')[i] for i = 1:26]
ttdict[" "] = ' '

# build the boxed dict
boxeddict = Dict{String, Char}()
[boxeddict[string(Char(i + 64))] = vcat('\U1F130':'\U1F14A')[i] for i = 1:26]
[boxeddict[string(Char(i + 96))] = vcat('\U1F170':'\U1F18A')[i] for i = 1:26]
boxeddict[" "] = ' '

# build the circled dict
circleddict = Dict{String, Char}()
[circleddict[string(Char(i + 64))] = vcat('\u24b6':'\u24cf')[i] for i = 1:26]
[circleddict[string(Char(i + 96))] = vcat('\u24d0':'\u24e9')[i] for i = 1:26]
[circleddict[string(Char(i + 0x30))] = vcat('\u2460':'\u2468')[i] for i = 1:9]
# 24EA 0 CIRCLED DIGIT ZERO is separate
circleddict[string(Char(0x30))] = '\u24ea'
circleddict[" "] = ' '

# negativecircled dict
# build the circled dict
negativecircleddict = Dict{String, Char}()
[negativecircleddict[string(Char(i + 64))] = vcat('\U1F150':'\U1F169')[i] for i = 1:26]
[negativecircleddict[string(Char(i + 96))] = vcat('\U1F170':'\U1F189')[i] for i = 1:26]
negativecircleddict[" "] = ' '

# build the segmented dict
segmenteddict = Dict{String, Char}()
[segmenteddict[string(Char(i + 0x2f))] = vcat('\U1FBF0':'\U1FBF9')[i] for i = 1:10]
segmenteddict[" "] = ' '

function adddc(letter, dc)
    return string(letter) * string(dc[rand(1:end)])
end

"""
    zalgo(str::String, upmarks = 1:4, middlemarks = 1:4,
        downmarks = 1:4, maxmarks = 6)

Randomly add up to `maxmarks` diacritic marks to each letter of `str`. The `upmarks`,
`middlemarks`, and `downmarks` ranges determine the minimum and maximum number of
diacritic marks added to the letter at that position.
"""
function zalgo(text::String;
        upmarks = 1:4,
        middlemarks = 1:4,
        downmarks = 1:4,
        maxmarks = 6)
    letters = split(text, "")
    zalgostring = String[]
    for letter in letters
        # can't add a diacritic mark to some letters
        if !all(isletter, letter)
            push!(zalgostring, letter)
            continue
        end
        upmarks_added     = rand(upmarks.start:upmarks.stop)
        downmarks_added   = rand(downmarks.start:downmarks.stop)
        middlemarks_added = rand(middlemarks.start:middlemarks.stop)
        newletter = letter
        for i in 1:maxmarks
            randint = rand(1:2)
            if randint == 1
                if upmarks_added > 0
                    newletter = adddc(newletter, updc)
                    upmarks_added -= 1
                end
            elseif randint == 2
                if downmarks_added > 0
                    newletter = adddc(newletter, downdc)
                    downmarks_added -= 1
                end
            else
                if middlemarks_added > 0
                    newletter = adddc(newletter, middledc)
                    middlemarks_added -= 1
                end
            end
        end
        push!(zalgostring, newletter)
    end
    return join(zalgostring)
end

"""
    upsidedown(str)

Return a version of string `str` with upside down letters from the Unicode table.
"""
function upsidedown(str)
    asciistr = filter!(c -> haskey(upsidedowndict, c), split(str, ""))
    return join(map(c -> upsidedowndict[c], asciistr))
end

"""
    fraktur(str)

Return a version of string `str` with Fraktur letters from the Unicode table.
"""
function fraktur(str)
    asciistr = filter!(c -> haskey(frakturdict, c), split(str, ""))
    return join(map(c -> frakturdict[c], asciistr))
end

"""
    script(str)

Return a version of string `str` with script letters from the Unicode table.
"""
function script(str)
    asciistr = filter!(c -> haskey(scriptdict, c), split(str, ""))
    return join(map(c -> scriptdict[c], asciistr))
end

"""
    boldroman(str)

Return a version of string `str` with boldroman letters from the Unicode table.
"""
function boldroman(str)
    asciistr = filter!(c -> haskey(boldromandict, c), split(str, ""))
    return join(map(c -> boldromandict[c], asciistr))
end

"""
    italic(str)

Return a version of string `str` with italic letters from the Unicode table.
"""
function italic(str)
    asciistr = filter!(c -> haskey(italicdict, c), split(str, ""))
    return join(map(c -> italicdict[c], asciistr))
end

"""
    bolditalic(str)

Return a version of string `str` with bolditalic letters from the Unicode table.
"""
function bolditalic(str)
    asciistr = filter!(c -> haskey(bolditalicdict, c), split(str, ""))
    return join(map(c -> bolditalicdict[c], asciistr))
end

"""
    boldscript(str)

Return a version of string `str` with boldscript letters from the Unicode table.
"""
function boldscript(str)
    asciistr = filter!(c -> haskey(boldscriptdict, c), split(str, ""))
    return join(map(c -> boldscriptdict[c], asciistr))
end

"""
    boldfraktur(str)

Return a version of string `str` with boldfraktur letters from the Unicode table.
"""
function boldfraktur(str)
    asciistr = filter!(c -> haskey(boldfrakturdict, c), split(str, ""))
    return join(map(c -> boldfrakturdict[c], asciistr))
end

"""
    sans(str)

Return a version of string `str` with sans serif letters from the Unicode table.
"""
function sans(str)
    asciistr = filter!(c -> haskey(sansdict, c), split(str, ""))
    return join(map(c -> sansdict[c], asciistr))
end

"""
    boldsans(str)

Return a version of string `str` with bold sans serif letters from the Unicode table.
"""
function boldsans(str)
    asciistr = filter!(c -> haskey(boldsansdict, c), split(str, ""))
    return join(map(c -> boldsansdict[c], asciistr))
end

"""
    italicsans(str)

Return a version of string `str` with italic sans serif letters from the Unicode table.
"""
function italicsans(str)
    asciistr = filter!(c -> haskey(italicsansdict, c), split(str, ""))
    return join(map(c -> italicsansdict[c], asciistr))
end

"""
    bolditalicsans(str)

Return a version of string `str` with bold italic sans serif letters from the Unicode table.
"""
function bolditalicsans(str)
    asciistr = filter!(c -> haskey(bolditalicsansdict, c), split(str, ""))
    return join(map(c -> bolditalicsansdict[c], asciistr))
end

"""
    teletype(str)

Return a version of string `str` with teletype (monospaced) letters from the Unicode table.
"""
function teletype(str)
    asciistr = filter!(c -> haskey(ttdict, c), split(str, ""))
    return join(map(c -> ttdict[c], asciistr))
end

"""
    blackboard(str)

Return a version of string `str` with blackboard (double-struck) letters from the Unicode table.
"""
function blackboard(str)
    asciistr = filter!(c -> haskey(blackboarddict, c), split(str, ""))
    return join(map(c -> blackboarddict[c], asciistr))
end

"""
    boxed(str)

Return a version of string `str` with boxed letters from the Unicode table.

```
boxed("A") -> "🄰"
boxed("a") -> "🅰"
```
"""
function boxed(str)
    asciistr = filter!(c -> haskey(boxeddict, c), split(str, ""))
    return join(map(c -> boxeddict[c], asciistr))
end

"""
    circled(str)

Return a version of string `str` with circled/boxed letters from the Unicode table.

```
A-Z             \u24b6:\u24cf       "A" -> "Ⓐ"
a-z             \u24d0:\u24e9       "a" -> "ⓐ"
0-9             \u2460:\u2468       "0" -> "⓪"
A-Z negative    \U1F150:\U1F169     "A" -> "🅐"
a-z negative    \U1F170:\U1F189     "a" -> "🅰"
```
"""
function circled(str;
        negative=false)
    if negative
        asciistr = filter!(c -> haskey(negativecircleddict, c), split(str, ""))
        return join(map(c -> negativecircleddict[c], asciistr))
    else
        asciistr = filter!(c -> haskey(circleddict, c), split(str, ""))
        return join(map(c -> circleddict[c], asciistr))
    end
end

"""
    segmented(str)

Return a version of string `str` with LED-style digits from the Unicode table.
"""
function segmented(str)
    asciistr = filter!(c -> haskey(segmenteddict, c), split(str, ""))
    return join(map(c -> segmenteddict[c], asciistr))
end

end # module


text:
# ---
# title: 168. Excel Sheet Column Title
# id: problem168
# author: Tian Jun
# date: 2020-10-31
# difficulty: Easy
# categories: Math
# link: <https://leetcode.com/problems/excel-sheet-column-title/description/>
# hidden: true
# ---
#
# Given a positive integer, return its corresponding column title as appear in
# an Excel sheet.
#
# For example:
#
#
#
#         1 -> A
#         2 -> B
#         3 -> C
#         ...
#         26 -> Z
#         27 -> AA
#         28 -> AB
#         ...
#
#
# **Example 1:**
#
#
#
#     Input: 1
#     Output: "A"
#
#
# **Example 2:**
#
#
#
#     Input: 28
#     Output: "AB"
#
#
# **Example 3:**
#
#
#
#     Input: 701
#     Output: "ZY"
#
#
#
## @lc code=start
using LeetCode

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


text:
using Test, CareerOneStop
# Documentation
@testset "Documentation" begin
    using Documenter, CareerOneStop

    prefix = ".."

    DocMeta.setdocmeta!(CareerOneStop,
                       :DocTestSetup,
                       :(using CareerOneStop, Documenter;
                         ENV["COLUMNS"] = 120;
                         ENV["LINES"] = 30;),
                       recursive = true)
    doctest(CareerOneStop, fix = true)
    makedocs(sitename = "CareerOneStop",
             modules = [CareerOneStop],
             pages = [
                 "Introduction" => "index.md",
                 "API" => "api.md",
                 ],
             source = joinpath(prefix, "docs", "src"),
             build = joinpath(prefix, "docs", "build"),
             )
    @test true
end


text:
# la variable de la boucle for est locale
# mais les bornes sont évaluées dans l'environnement global

function f(x)
    print(x, ".")
    x
end

n = 42
println(n)

for n = f(1) : f(n)
    print(n)
end
println()

println(n)

max_stars_repo_name: gabriel-doriath-dohler/pjulia

max_issues_repo_name: gabriel-doriath-dohler/pjulia

max_forks_repo_name: gabriel-doriath-dohler/pjulia


text:
# Demands that have no flexibility.

# Import packages.
using Dates, TimeSeries

# Timeseries of possibly mobile demands.

"""
Demands that vary with time.

# Type parameters
- `T <: TimeType`: timestamp

# Example
```
example = TimeArray(
    [Time(0), Time(8), Time(9), Time(17), Time(18)],
    [     0.,     10.,      0.,      11.,       0.]
) :: TemporalDemand{Time}
```
"""
const TemporalDemand{T <: TimeType} = TimeArray{Float64,1,T,Array{Float64,1}}

"""
Locations where demand moves.

# Type parameters
- `T <: TimeType`: timestamp
- `L`            : network location

# Example
```
example = TimeArray(
    [Time(0)   , Time(8)   , Time(9)       , Time(17) , Time(18)  ],
    ["Home #23", "Road #14", "Workplace #3", "Road #9", "Home #23"]
) :: MobileDemand{Time,String}
```
"""
const MobileDemand{T <: TimeType, L} = TimeArray{L,1,T,Array{L,1}}

"""
Demands that move.

# Type parameters
- `T <: TimeType`: timestamp
- `L`            : network location

# Example
```
example = TimeArray(
    [Time(0)         , Time(8)          , Time(9)             , Time(17)        , Time(18)        ],
    [("Home #23", 0.), ("Road #14", 10.), ("Workplace #3", 0.), ("Road #9", 11.), ("Home #23", 0.)]
) :: LocatedDemand{Time,String}
```
"""
const LocatedDemand{T <: TimeType, L} = TimeArray{Tuple{L,Float64},1,T,Array{Tuple{L,Float64},1}}

# Abstract inflexbile demands.

abstract type InflexibleDemand{T,L} <: Demand{T,L} end

"""
Time-varying demands and their locations.

This must be implemented by subtypes of `InflexibleDemand`.

# Arguments
- `demand :: InflexibleDemand{T,L}`: the demand
"""
function demands(demand :: InflexibleDemand{T,L}) :: LocatedDemand{T,L} where L where T <: TimeType
end

"""
The "envelope" of minimum and maximum allowable demands at each time pont, with a location for the demand.

# Arguments
- `demand :: InflexibleDemand{T,L}`: the demand
"""
function envelope(demand :: InflexibleDemand{T,L}) :: LocatedEnvelope{T,L} where L where T <: TimeType
    simple = demands(demand)
    TimeArray(
        timestamp(simple),
        map(x -> (x[1], x[2], x[2]), values(simple))
    )
end


text:
#=
BILINEAR INTERPOLATION
	Q1      Q2

	Q3      Q4
=#

function bilinear_distances( size )

	distances = Array{Tuple{Float32,Float32},1}(undef,size)
	delta     = 1/(size+1);

	d = delta
	for idx in 1:size
		distances[idx] = ( 1-d, d )
		d += delta
	end

	return distances
end

function discrete_bilinear( Q12, Q34, distances, id1, id2 )

	intp1 = sum( distances[id1] .* Q12 )
	intp2 = sum( distances[id1] .* Q34 )
	return  sum( distances[id2] .* (intp1,intp2) )
end

function bilinear_interpolation( img, grid; sz=4 )

	 h,  w = size(img);
	gh, gw = size(grid);

	startx, stepx = w/(gw+2)
	starty, stepy = h/(gh+2)

	for
end


text:
include("build_Zlib.v1.2.11.jl")
include("build_HDF5.v1.10.5.jl")


text:
@testset "utilities tests" begin
    @testset "sample_neighbors" begin
        @testset "sample_rate = 1. tests" begin
            points = collect(1:10)
            n_neighbors = 4

            # zero neighbors
            idxs = KNNGraphs.sample_neighbors(length(points), 0)
            @test length(idxs) == 0

            # k < n
            idxs = KNNGraphs.sample_neighbors(length(points), n_neighbors)
            @test length(idxs) == n_neighbors
            @test issubset(idxs, points)

            # k > n
            idxs = KNNGraphs.sample_neighbors(length(points), length(points)+5)
            @test length(idxs) == length(points)
        end
        @testset "sample_rate = .5 tests" begin
            points = collect(1:10)
            n_neighbors = 4
            ρ = .5

            # zero neighbors
            idxs = KNNGraphs.sample_neighbors(length(points), 0, ρ)
            @test length(idxs) == 0

            # k < n
            idxs = KNNGraphs.sample_neighbors(length(points), n_neighbors, ρ)
            @test ρ*n_neighbors ≥ length(idxs)
            @test issubset(idxs, points)

            # k > n
            idxs = KNNGraphs.sample_neighbors(length(points), 2*length(points), ρ)
            @test length(idxs) == length(points)
        end
        @testset "exclude set tests" begin
            points = collect(1:10)

            # exclude 1
            idxs = KNNGraphs.sample_neighbors(length(points),
                                              length(points),
                                              exclude=[1])
            @test idxs ⊊ points
            @test !(1 ∈ idxs)

            # exclude all
            idxs = KNNGraphs.sample_neighbors(length(points),
                                              length(points),
                                              exclude=points)
            @test length(idxs) == 0

        end
    end

    @testset "_heappush! tests" begin
        @testset "max_length tests" begin
            h = BinaryMaxHeap{HeapKNNGraphEdge{Int, Float64}}()
            e = HeapKNNGraphEdge(1, 2, 1.)
            KNNGraphs._heappush!(h, e, 0)
            @test length(h) == 0

            KNNGraphs._heappush!(h, e, 1)
            @test length(h) == 1
            @test first(h) == e

            e2 = HeapKNNGraphEdge(1, 3, 1.) # new point, heappush! just replaces
            KNNGraphs._heappush!(h, e2, 1)
            @test length(h) == 1
            @test first(h) == e2
        end
    end
end # end utilities tests


text:
if !@isdefined USE_GPU
    const USE_GPU = length(ARGS) > 0 && ARGS[1] == "gpu"
end

using DataFrames
using CSV
using ImplicitGlobalGrid
import MPI
using ParallelStencil
using ParallelStencil.FiniteDifferences3D
if !ParallelStencil.is_initialized()
    @static if USE_GPU
        @init_parallel_stencil(CUDA, Float64, 3)
    else
        @init_parallel_stencil(Threads, Float64, 3)
    end
end
include("part1_kernel_programming.jl")

const LOCATION_OF_INTEREST = (4.5, 4.5, 4.5)

const FILENAME = joinpath("benchmark-results", "error_vs_tolerance_experiment_results.csv")

MPI.Init()
for tol in 10. .^(-3:-1:-10)
    nx = ny = nz = 2^7
    X, H, _ = diffusion_3D_kernel_programming(nx=nx, ny=ny, nz=nz, tol=tol, ttot=2.0, init_and_finalize_MPI=false, verbose=false)

    dx = X[2] - X[1]

    interp_value = linear_interpolate_3D(H, dx)

    ix, iy, iz = round.(Int, (LOCATION_OF_INTEREST./ dx) .+ 1)

    df_row = (tol=tol, val=H[ix, iy, iz], interp_val=interp_value)

    # Note that this is potentially susceptible to a race condition
    res_df =
        if isfile(FILENAME)
            DataFrame(CSV.File(FILENAME))
        else
            DataFrame()
        end
    push!(res_df, df_row)

    open(FILENAME, "w") do io
        CSV.write(io, res_df)
    end
end

MPI.Finalize()


text:
using MatrixNetworks
using Base.Test
using Compat
#using Lint

all_tests = ["bfs",
             "bipartite_matching",
             "clustercoeffs",
             "corenums",
             "cosineknn",
             "csr_to_sparse",
             "dfs",
             "dijkstra",
             "dirclustercoeffs",
             "floydwarshall",
             "largest_component",
             "mst_prim",
             "scomponents",
             "sparse_to_csr"]

for t in all_tests
    test_name = join(["$(t)", "_test",".jl"])
    test_path = joinpath(Pkg.dir("MatrixNetworks"), "test", test_name)
    println("running $(test_path) ...")
    test_function = include(test_path)
    @test test_function() == true
end

#println("testing package with Lint...")
#msgs = lintpkg( "MatrixNetworks", returnMsgs = true )
#if isempty(msgs)
#    info("Lint package passed")
#else
#    warn("Lint package didn't pass")
#end


text:
@testset "Multiplication" begin
    v = [1,2,3]
    tv = v.'
    mat = diagm([1,2,3])

    @test (tv*v) === 14
    @test (tv*mat)::TransposedVector == [1 4 9]
    @test_throws Exception [1]*reshape([1],(1,1)) # no longer permitted
    @test_throws Exception tv*tv
    @test (v*tv)::Matrix == [1 2 3; 2 4 6; 3 6 9]
    @test_throws Exception v*v # Was previously a missing method error, now an error message
    @test_throws Exception mat*tv

    @test_throws Exception tv*v.'
    @test (tv*mat.')::TransposedVector == [1 4 9]
    @test_throws Exception [1]*reshape([1],(1,1)).' # no longer permitted
    @test tv*tv.' === 14
    @test_throws Exception v*tv.'
    @test (v*v.')::Matrix == [1 2 3; 2 4 6; 3 6 9]
    @test (mat*tv.')::Vector == [1,4,9]

    @test (tv.'*v.')::Matrix == [1 2 3; 2 4 6; 3 6 9]
    @test_throws Exception tv.'*mat.'
    @test (v.'*mat.')::TransposedVector == [1 4 9]
    @test_throws Exception tv.'*tv.'
    @test v.'*tv.' === 14
    @test_throws Exception v.'*v.'
    @test (mat.'*tv.')::Vector == [1,4,9]

    @test_throws Exception tv.'*v
    @test_throws Exception tv.'*mat
    @test (v.'*mat)::TransposedVector == [1 4 9]
    @test (tv.'*tv)::Matrix == [1 2 3; 2 4 6; 3 6 9]
    @test_throws Exception v.'*tv
    @test v.'*v === 14
    @test_throws Exception mat.'*tv

    z = [1+im,2,3]
    cz = z'
    mat = diagm([1+im,2,3])

    @test cz*z === 15 + 0im

    @test_throws Exception cz*z'
    @test (cz*mat')::TransposedVector == [-2im 4 9]
    @test_throws Exception [1]*reshape([1],(1,1))' # no longer permitted
    @test cz*cz' === 15 + 0im
    @test_throws Exception z*vz'
    @test (z*z')::Matrix == [2 2+2im 3+3im; 2-2im 4 6; 3-3im 6 9]
    @test (mat*cz')::Vector == [2im,4,9]

    @test (cz'*z')::Matrix == [2 2+2im 3+3im; 2-2im 4 6; 3-3im 6 9]
    @test_throws Exception cz'*mat'
    @test (z'*mat')::TransposedVector == [-2im 4 9]
    @test_throws Exception cz'*cz'
    @test z'*cz' === 15 + 0im
    @test_throws Exception z'*z'
    @test (mat'*cz')::Vector == [2,4,9]

    @test_throws Exception cz'*z
    @test_throws Exception cz'*mat
    @test (z'*mat)::TransposedVector == [2 4 9]
    @test (cz'*cz)::Matrix == [2 2+2im 3+3im; 2-2im 4 6; 3-3im 6 9]
    @test_throws Exception z'*cz
    @test z'*z === 15 + 0im
    @test_throws Exception mat'*cz

end


text:
Dict{Float32,String}(
400=>"N.A. San Andres y Providencia",
1=>"Halobioma Alta Guajira",
2=>"Halobioma Baja Guajira y alto Cesar",
3=>"Halobioma Cartagena y delta del Magdalena",
4=>"Halobioma Darién –Tacarcuna",
5=>"Halobioma Estribación norte Sierra Nevada de Santa Marta",
6=>"Halobioma Micay",
399=>"Halobioma Nechí-San Lucas",
7=>"Halobioma Pacífico nariñense-Tumaco",
8=>"Halobioma San Andrés y Providencia",
9=>"Halobioma San Juan",
10=>"Halobioma Sierra nevada de Santa Marta",
11=>"Halobioma Sinú",
12=>"Halobioma Truandó",
13=>"Helobioma Altillanura",
14=>"Helobioma Alto Caquetá",
15=>"Helobioma Alto Guayabero",
16=>"Helobioma Alto Murrí",
17=>"Helobioma Alto Putumayo",
18=>"Helobioma Altoandino cordillera oriental",
19=>"Helobioma Altoandino influencia llanera",
20=>"Helobioma Apaporis",
21=>"Helobioma Arauca",
22=>"Helobioma Ariguaní-Cesar",
23=>"Helobioma Baja Guajira y alto Cesar",
24=>"Helobioma Bajo Caquetá - Puré",
25=>"Helobioma Bajo Vaupés",
26=>"Helobioma Bita",
27=>"Helobioma Cartagena y delta del Magdalena",
28=>"Helobioma Casanare",
29=>"Helobioma Catatumbo",
30=>"Helobioma Cauca alto",
31=>"Helobioma Cauca medio",
32=>"Helobioma Chaparral",
33=>"Helobioma Cordillera central",
34=>"Helobioma Cordillera oriental Magdalena medio",
35=>"Helobioma Cúcuta",
36=>"Helobioma Darién –Tacarcuna",
39=>"Helobioma Estribación sur Sierra Nevada de Santa Marta",
37=>"Helobioma Estribaciones Pacífico norte",
38=>"Helobioma Estribaciones Pacífico sur",
40=>"Helobioma Guainía",
41=>"Helobioma Guane-Yariguíes",
42=>"Helobioma Guaviare – Guayabero",
43=>"Helobioma Huila-Caquetá",
44=>"Helobioma Huitoto-Cahuinarí",
45=>"Helobioma Inírida-Papunaua",
46=>"Helobioma Macarena",
47=>"Helobioma Magdalena medio y depresión momposina",
48=>"Helobioma Maipures",
49=>"Helobioma Matavén",
50=>"Helobioma Micay",
51=>"Helobioma Nechí-San Lucas",
52=>"Helobioma Nudo de los pastos",
53=>"Helobioma Pacífico nariñense-Tumaco",
54=>"Helobioma Patía",
55=>"Helobioma Picachos",
56=>"Helobioma Piedemonte Amazonas",
57=>"Helobioma Piedemonte Orinoquia",
58=>"Helobioma Puinawai",
59=>"Helobioma San Juan",
60=>"Helobioma Serranía del Naquén",
61=>"Helobioma Sierra nevada de Santa Marta",
62=>"Helobioma Sinú",
63=>"Helobioma Ticuna – Amacayacu",
64=>"Helobioma Tolima grande",
65=>"Helobioma Truandó",
66=>"Helobioma Uwa",
69=>"Helobioma Vertiente llanera cordillera oriental",
67=>"Helobioma Vertiente Pacífico-Cauca",
68=>"Helobioma Vertiente Pacífico-Chocó",
70=>"Helobioma Villavicencio",
71=>"Helobioma Yarí-Chiribiquete",
72=>"Helobioma Zulia",
73=>"Hidrobioma Alta Guajira",
74=>"Hidrobioma Altillanura",
75=>"Hidrobioma Alto Caquetá",
76=>"Hidrobioma Alto Guayabero",
77=>"Hidrobioma Alto Murrí",
78=>"Hidrobioma Alto Putumayo",
79=>"Hidrobioma Altoandino cordillera oriental",
80=>"Hidrobioma Altoandino influencia llanera",
81=>"Hidrobioma Apaporis",
82=>"Hidrobioma Arauca",
83=>"Hidrobioma Ariguaní-Cesar",
84=>"Hidrobioma Baja Guajira y alto Cesar",
85=>"Hidrobioma Bajo Caquetá - Puré",
86=>"Hidrobioma Bajo Vaupés",
87=>"Hidrobioma Bita",
88=>"Hidrobioma Cartagena y delta del Magdalena",
89=>"Hidrobioma Casanare",
90=>"Hidrobioma Catatumbo",
91=>"Hidrobioma Cauca alto",
92=>"Hidrobioma Cauca medio",
93=>"Hidrobioma Chaparral",
94=>"Hidrobioma Cordillera central",
95=>"Hidrobioma Cordillera oriental Magdalena medio",
96=>"Hidrobioma Cúcuta",
97=>"Hidrobioma Darién –Tacarcuna",
100=>"Hidrobioma Estribación norte Sierra Nevada de Santa Marta",
101=>"Hidrobioma Estribación sur Sierra Nevada de Santa Marta",
98=>"Hidrobioma Estribaciones Pacífico norte",
99=>"Hidrobioma Estribaciones Pacífico sur",
102=>"Hidrobioma Guainía",
103=>"Hidrobioma Guane-Yariguíes",
104=>"Hidrobioma Guaviare – Guayabero",
105=>"Hidrobioma Huila-Caquetá",
106=>"Hidrobioma Huitoto-Cahuinarí",
107=>"Hidrobioma Inírida-Papunaua",
108=>"Hidrobioma Macarena",
109=>"Hidrobioma Magdalena medio y depresión momposina",
110=>"Hidrobioma Maipures",
111=>"Hidrobioma Matavén",
112=>"Hidrobioma Micay",
113=>"Hidrobioma Nechí-San Lucas",
114=>"Hidrobioma Nudo de los pastos",
115=>"Hidrobioma Pacífico nariñense-Tumaco",
116=>"Hidrobioma Patía",
117=>"Hidrobioma Perijá",
118=>"Hidrobioma Perijá y montes de Oca",
119=>"Hidrobioma Picachos",
120=>"Hidrobioma Piedemonte Amazonas",
121=>"Hidrobioma Piedemonte Orinoquia",
122=>"Hidrobioma Puinawai",
123=>"Hidrobioma San Juan",
124=>"Hidrobioma Serranía del Naquén",
125=>"Hidrobioma Sierra nevada de Santa Marta",
126=>"Hidrobioma Sinú",
127=>"Hidrobioma Tamá",
128=>"Hidrobioma Ticuna – Amacayacu",
129=>"Hidrobioma Tolima grande",
130=>"Hidrobioma Truandó",
131=>"Hidrobioma Uwa",
134=>"Hidrobioma Vertiente llanera cordillera oriental",
132=>"Hidrobioma Vertiente Pacífico-Cauca",
133=>"Hidrobioma Vertiente Pacífico-Chocó",
135=>"Hidrobioma Villavicencio",
136=>"Hidrobioma Yarí-Chiribiquete",
137=>"Hidrobioma Zulia",
138=>"Litobioma Altillanura",
139=>"Litobioma Apaporis",
140=>"Litobioma Bajo Caquetá - Puré",
141=>"Litobioma Bajo Vaupés",
142=>"Litobioma Bita",
143=>"Litobioma Guainía",
144=>"Litobioma Guaviare – Guayabero",
145=>"Litobioma Huitoto-Cahuinarí",
146=>"Litobioma Inírida-Papunaua",
147=>"Litobioma Maipures",
148=>"Litobioma Matavén",
149=>"Litobioma Puinawai",
150=>"Litobioma Serranía del Naquén",
151=>"Litobioma Yarí-Chiribiquete",
152=>"Orobioma Andino Altoandino cordillera oriental",
153=>"Orobioma Andino Altoandino influencia llanera",
154=>"Orobioma Andino Caquetá influencia cordillera central",
155=>"Orobioma Andino Catatumbo",
156=>"Orobioma Andino Cauca alto",
157=>"Orobioma Andino Cauca medio",
158=>"Orobioma Andino Chaparral",
159=>"Orobioma Andino Cordillera central",
160=>"Orobioma Andino Cordillera oriental Magdalena medio",
163=>"Orobioma Andino Estribación sur Sierra Nevada de Santa Marta",
161=>"Orobioma Andino Estribaciones Pacífico norte",
162=>"Orobioma Andino Estribaciones Pacífico sur",
164=>"Orobioma Andino Guane-Yariguíes",
165=>"Orobioma Andino Huila-Caquetá",
166=>"Orobioma Andino Nechí-San Lucas",
167=>"Orobioma Andino Nudo de los pastos",
168=>"Orobioma Andino Pacífico nariñense-Tumaco",
169=>"Orobioma Andino Patía",
170=>"Orobioma Andino Perijá",
171=>"Orobioma Andino Perijá y montes de Oca",
172=>"Orobioma Andino Picachos",
173=>"Orobioma Andino Piedemonte Amazonas",
174=>"Orobioma Andino Piedemonte Orinoquia",
175=>"Orobioma Andino Sierra nevada de Santa Marta",
176=>"Orobioma Andino Tamá",
177=>"Orobioma Andino Tolima grande",
178=>"Orobioma Andino Uwa",
181=>"Orobioma Andino Vertiente llanera cordillera oriental",
179=>"Orobioma Andino Vertiente Pacífico-Cauca",
180=>"Orobioma Andino Vertiente Pacífico-Chocó",
182=>"Orobioma Andino Villavicencio",
183=>"Orobioma Azonal Andino Altoandino cordillera oriental",
184=>"Orobioma Azonal Andino Altoandino influencia llanera",
185=>"Orobioma Azonal Andino Catatumbo",
186=>"Orobioma Azonal Andino Cordillera central",
187=>"Orobioma Azonal Andino Cordillera oriental Magdalena medio",
188=>"Orobioma Azonal Andino Guane-Yariguíes",
189=>"Orobioma Azonal Andino Huila-Caquetá",
190=>"Orobioma Azonal Andino Nudo de los pastos",
191=>"Orobioma Azonal Andino Patía",
192=>"Orobioma Azonal Andino Perijá y montes de Oca",
193=>"Orobioma Azonal Andino Tamá",
194=>"Orobioma Azonal Andino Tolima grande",
195=>"Orobioma Azonal Andino Uwa",
196=>"Orobioma Azonal Subandino Altoandino cordillera oriental",
197=>"Orobioma Azonal Subandino Altoandino influencia llanera",
198=>"Orobioma Azonal Subandino Cartagena y delta del Magdalena",
199=>"Orobioma Azonal Subandino Catatumbo",
200=>"Orobioma Azonal Subandino Cauca alto",
201=>"Orobioma Azonal Subandino Cauca medio",
202=>"Orobioma Azonal Subandino Cordillera central",
203=>"Orobioma Azonal Subandino Cordillera oriental Magdalena medio",
204=>"Orobioma Azonal Subandino Cúcuta",
207=>"Orobioma Azonal Subandino Estribación sur Sierra Nevada de Santa Marta",
205=>"Orobioma Azonal Subandino Estribaciones Pacífico norte",
206=>"Orobioma Azonal Subandino Estribaciones Pacífico sur",
208=>"Orobioma Azonal Subandino Guane-Yariguíes",
209=>"Orobioma Azonal Subandino Huila-Caquetá",
210=>"Orobioma Azonal Subandino Nechí-San Lucas",
211=>"Orobioma Azonal Subandino Nudo de los pastos",
212=>"Orobioma Azonal Subandino Patía",
213=>"Orobioma Azonal Subandino Perijá",
214=>"Orobioma Azonal Subandino Perijá y montes de Oca",
215=>"Orobioma Azonal Subandino Sierra nevada de Santa Marta",
216=>"Orobioma Azonal Subandino Tamá",
217=>"Orobioma Azonal Subandino Tolima grande",
265=>"Orobioma de Paramo Altoandino cordillera oriental",
266=>"Orobioma de Paramo Altoandino influencia llanera",
267=>"Orobioma de Paramo Caquetá influencia cordillera central",
268=>"Orobioma de Paramo Catatumbo",
269=>"Orobioma de Paramo Cauca alto",
270=>"Orobioma de Paramo Cauca medio",
271=>"Orobioma de Paramo Chaparral",
272=>"Orobioma de Paramo Cordillera central",
273=>"Orobioma de Paramo Cordillera oriental Magdalena medio",
274=>"Orobioma de Paramo Estribaciones Pacífico norte",
275=>"Orobioma de Paramo Estribaciones Pacífico sur",
276=>"Orobioma de Paramo Guane-Yariguíes",
277=>"Orobioma de Paramo Huila-Caquetá",
278=>"Orobioma de Paramo Nechí-San Lucas",
279=>"Orobioma de Paramo Nudo de los pastos",
280=>"Orobioma de Paramo Patía",
281=>"Orobioma de Paramo Perijá",
282=>"Orobioma de Paramo Sierra nevada de Santa Marta",
283=>"Orobioma de Paramo Tamá",
284=>"Orobioma de Paramo Uwa",
285=>"Orobioma de Paramo Vertiente llanera cordillera oriental",
218=>"Orobioma Subandino Alto Caquetá",
219=>"Orobioma Subandino Alto Guayabero",
220=>"Orobioma Subandino Alto Murrí",
221=>"Orobioma Subandino Alto Putumayo",
222=>"Orobioma Subandino Altoandino cordillera oriental",
223=>"Orobioma Subandino Altoandino influencia llanera",
224=>"Orobioma Subandino Ariguaní-Cesar",
225=>"Orobioma Subandino Caquetá influencia cordillera central",
226=>"Orobioma Subandino Casanare",
227=>"Orobioma Subandino Catatumbo",
228=>"Orobioma Subandino Cauca alto",
229=>"Orobioma Subandino Cauca medio",
230=>"Orobioma Subandino Chaparral",
231=>"Orobioma Subandino Cordillera central",
232=>"Orobioma Subandino Cordillera oriental Magdalena medio",
233=>"Orobioma Subandino Cúcuta",
234=>"Orobioma Subandino Darién –Tacarcuna",
237=>"Orobioma Subandino Estribación norte Sierra Nevada de Santa Marta",
238=>"Orobioma Subandino Estribación sur Sierra Nevada de Santa Marta",
235=>"Orobioma Subandino Estribaciones Pacífico norte",
236=>"Orobioma Subandino Estribaciones Pacífico sur",
239=>"Orobioma Subandino Guane-Yariguíes",
240=>"Orobioma Subandino Huila-Caquetá",
241=>"Orobioma Subandino Macarena",
242=>"Orobioma Subandino Magdalena medio y depresión momposina",
243=>"Orobioma Subandino Micay",
244=>"Orobioma Subandino Nechí-San Lucas",
245=>"Orobioma Subandino Nudo de los pastos",
246=>"Orobioma Subandino Pacífico nariñense-Tumaco",
247=>"Orobioma Subandino Patía",
248=>"Orobioma Subandino Perijá",
249=>"Orobioma Subandino Perijá y montes de Oca",
250=>"Orobioma Subandino Picachos",
251=>"Orobioma Subandino Piedemonte Amazonas",
252=>"Orobioma Subandino Piedemonte Orinoquia",
253=>"Orobioma Subandino San Juan",
254=>"Orobioma Subandino Sierra nevada de Santa Marta",
255=>"Orobioma Subandino Tamá",
256=>"Orobioma Subandino Tolima grande",
257=>"Orobioma Subandino Truandó",
258=>"Orobioma Subandino Uwa",
261=>"Orobioma Subandino Vertiente llanera cordillera oriental",
259=>"Orobioma Subandino Vertiente Pacífico-Cauca",
260=>"Orobioma Subandino Vertiente Pacífico-Chocó",
262=>"Orobioma Subandino Villavicencio",
263=>"Orobioma Subandino Yarí-Chiribiquete",
264=>"Orobioma Subandino Zulia",
286=>"Peinobioma Altillanura",
287=>"Peinobioma Alto Guayabero",
288=>"Peinobioma Arauca",
289=>"Peinobioma Ariguaní-Cesar",
290=>"Peinobioma Bita",
291=>"Peinobioma Casanare",
292=>"Peinobioma Cordillera oriental Magdalena medio",
293=>"Peinobioma Cúcuta",
294=>"Peinobioma Estribación sur Sierra Nevada de Santa Marta",
295=>"Peinobioma Guainía",
296=>"Peinobioma Guaviare – Guayabero",
297=>"Peinobioma Inírida-Papunaua",
298=>"Peinobioma Macarena",
299=>"Peinobioma Magdalena medio y depresión momposina",
300=>"Peinobioma Maipures",
301=>"Peinobioma Matavén",
302=>"Peinobioma Nechí-San Lucas",
303=>"Peinobioma Perijá",
304=>"Peinobioma Piedemonte Orinoquia",
305=>"Peinobioma Puinawai",
306=>"Peinobioma Serranía del Naquén",
307=>"Peinobioma Sierra nevada de Santa Marta",
308=>"Peinobioma Sinú",
309=>"Peinobioma Tolima grande",
310=>"Peinobioma Villavicencio",
311=>"Peinobioma Yarí-Chiribiquete",
312=>"Peinobioma Zulia",
313=>"Zonobioma Alternohigrico Tropical Alta Guajira",
314=>"Zonobioma Alternohigrico Tropical Altoandino cordillera oriental",
315=>"Zonobioma Alternohigrico Tropical Arauca",
316=>"Zonobioma Alternohigrico Tropical Ariguaní-Cesar",
317=>"Zonobioma Alternohigrico Tropical Baja Guajira y alto Cesar",
318=>"Zonobioma Alternohigrico Tropical Cartagena y delta del Magdalena",
319=>"Zonobioma Alternohigrico Tropical Catatumbo",
320=>"Zonobioma Alternohigrico Tropical Cauca alto",
321=>"Zonobioma Alternohigrico Tropical Cauca medio",
322=>"Zonobioma Alternohigrico Tropical Chaparral",
323=>"Zonobioma Alternohigrico Tropical Cordillera oriental Magdalena medio",
324=>"Zonobioma Alternohigrico Tropical Cúcuta",
326=>"Zonobioma Alternohigrico Tropical Estribación norte Sierra Nevada de Santa Marta",
327=>"Zonobioma Alternohigrico Tropical Estribación sur Sierra Nevada de Santa Marta",
325=>"Zonobioma Alternohigrico Tropical Estribaciones Pacífico sur",
328=>"Zonobioma Alternohigrico Tropical Guane-Yariguíes",
329=>"Zonobioma Alternohigrico Tropical Huila-Caquetá",
330=>"Zonobioma Alternohigrico Tropical Magdalena medio y depresión momposina",
331=>"Zonobioma Alternohigrico Tropical Nechí-San Lucas",
332=>"Zonobioma Alternohigrico Tropical Pacífico nariñense-Tumaco",
333=>"Zonobioma Alternohigrico Tropical Patía",
334=>"Zonobioma Alternohigrico Tropical Perijá",
335=>"Zonobioma Alternohigrico Tropical Perijá y montes de Oca",
336=>"Zonobioma Alternohigrico Tropical Picachos",
337=>"Zonobioma Alternohigrico Tropical San Andrés y Providencia",
338=>"Zonobioma Alternohigrico Tropical Sierra nevada de Santa Marta",
339=>"Zonobioma Alternohigrico Tropical Sinú",
340=>"Zonobioma Alternohigrico Tropical Tolima grande",
341=>"Zonobioma Alternohigrico Tropical Zulia",
342=>"Zonobioma Humedo Tropical Altillanura",
343=>"Zonobioma Humedo Tropical Alto Caquetá",
344=>"Zonobioma Humedo Tropical Alto Guayabero",
345=>"Zonobioma Humedo Tropical Alto Murrí",
346=>"Zonobioma Humedo Tropical Alto Putumayo",
347=>"Zonobioma Humedo Tropical Apaporis",
348=>"Zonobioma Humedo Tropical Arauca",
349=>"Zonobioma Humedo Tropical Ariguaní-Cesar",
350=>"Zonobioma Humedo Tropical Bajo Caquetá - Puré",
351=>"Zonobioma Humedo Tropical Bajo Vaupés",
352=>"Zonobioma Humedo Tropical Bita",
353=>"Zonobioma Humedo Tropical Cartagena y delta del Magdalena",
354=>"Zonobioma Humedo Tropical Casanare",
355=>"Zonobioma Humedo Tropical Catatumbo",
356=>"Zonobioma Humedo Tropical Cauca alto",
357=>"Zonobioma Humedo Tropical Cauca medio",
358=>"Zonobioma Humedo Tropical Chaparral",
359=>"Zonobioma Humedo Tropical Cordillera central",
360=>"Zonobioma Humedo Tropical Cordillera oriental Magdalena medio",
361=>"Zonobioma Humedo Tropical Cúcuta",
362=>"Zonobioma Humedo Tropical Darién –Tacarcuna",
365=>"Zonobioma Humedo Tropical Estribación norte Sierra Nevada de Santa Marta",
366=>"Zonobioma Humedo Tropical Estribación sur Sierra Nevada de Santa Marta",
363=>"Zonobioma Humedo Tropical Estribaciones Pacífico norte",
364=>"Zonobioma Humedo Tropical Estribaciones Pacífico sur",
367=>"Zonobioma Humedo Tropical Guainía",
368=>"Zonobioma Humedo Tropical Guane-Yariguíes",
369=>"Zonobioma Humedo Tropical Guaviare – Guayabero",
370=>"Zonobioma Humedo Tropical Huila-Caquetá",
371=>"Zonobioma Humedo Tropical Huitoto-Cahuinarí",
372=>"Zonobioma Humedo Tropical Inírida-Papunaua",
373=>"Zonobioma Humedo Tropical Macarena",
374=>"Zonobioma Humedo Tropical Magdalena medio y depresión momposina",
375=>"Zonobioma Humedo Tropical Matavén",
376=>"Zonobioma Humedo Tropical Micay",
377=>"Zonobioma Humedo Tropical Nechí-San Lucas",
378=>"Zonobioma Humedo Tropical Pacífico nariñense-Tumaco",
379=>"Zonobioma Humedo Tropical Patía",
380=>"Zonobioma Humedo Tropical Perijá",
381=>"Zonobioma Humedo Tropical Perijá y montes de Oca",
382=>"Zonobioma Humedo Tropical Picachos",
383=>"Zonobioma Humedo Tropical Piedemonte Amazonas",
384=>"Zonobioma Humedo Tropical Piedemonte Orinoquia",
385=>"Zonobioma Humedo Tropical Puinawai",
386=>"Zonobioma Humedo Tropical San Juan",
387=>"Zonobioma Humedo Tropical Serranía del Naquén",
388=>"Zonobioma Humedo Tropical Sierra nevada de Santa Marta",
389=>"Zonobioma Humedo Tropical Sinú",
390=>"Zonobioma Humedo Tropical Ticuna – Amacayacu",
391=>"Zonobioma Humedo Tropical Tolima grande",
392=>"Zonobioma Humedo Tropical Truandó",
395=>"Zonobioma Humedo Tropical Vertiente llanera cordillera oriental",
393=>"Zonobioma Humedo Tropical Vertiente Pacífico-Cauca",
394=>"Zonobioma Humedo Tropical Vertiente Pacífico-Chocó",
396=>"Zonobioma Humedo Tropical Villavicencio",
397=>"Zonobioma Humedo Tropical Yarí-Chiribiquete",
398=>"Zonobioma Humedo Tropical Zulia")


text:
module BosonSampling

using Permanents
using Plots
using Test
using Combinatorics
using Random
using IterTools
using Statistics
using LinearAlgebra #removed so as to be able to use generic types such as BigFloats, can be put back if needed
using PolynomialRoots
using StatsBase
#using JLD
using CSV
using DataFrames
using Tables
using Plots#; plotly() #plotly allows to make "dynamic" plots where you can point the mouse and see the values, they can also be saved like that but note that this makes them heavy (and html instead of png)
using PrettyTables #to display large matrices
using Roots
using BenchmarkTools
using Optim
using ProgressMeter
using Parameters
using ArgCheck
using Distributions
using Luxor
# using Distributed
# using SharedArrays

const ATOL = 1e-10

include("special_matrices.jl")
include("matrix_tests.jl")
include("proba_tools.jl")
include("circuits/circuit_elements.jl")
include("types/type_functions.jl")
include("types/types.jl")
include("scattering.jl")

include("bunching/bunching.jl")
include("partitions/legacy.jl")
include("partitions/partition_expectation_values.jl")
include("partitions/partitions.jl")

include("boson_samplers/tools.jl")
include("boson_samplers/classical_sampler.jl")
include("boson_samplers/cliffords_sampler.jl")
include("boson_samplers/methods.jl")
include("boson_samplers/metropolis_sampler.jl")
include("boson_samplers/noisy_sampler.jl")

include("distributions/noisy_distribution.jl")
include("distributions/theoretical_distribution.jl")

include("permanent_conjectures/bapat_sunder.jl")
include("permanent_conjectures/counter_example_functions.jl")
include("permanent_conjectures/counter_example_numerical_search.jl")
include("permanent_conjectures/permanent_on_top.jl")

include("visual.jl")

permanent = ryser

for n in names(@__MODULE__; all=true)
    if Base.isidentifier(n) && n ∉ (Symbol(@__MODULE__), :eval, :include)
        @eval export $n
    end
end

end


text:
# Copyright 2015, 2016, 2017, 2018 Martin Holters
# See accompanying license file.

using ACME

function sallenkey(::Type{Circuit})
    @circuit begin
        j_in = voltagesource(), [-] ⟷ gnd
        r1 = resistor(10e3), [1] ⟷ j_in[+]
        r2 = resistor(10e3), [1] ⟷ r1[2]
        c1 = capacitor(10e-9), [1] ⟷ r1[2]
        u1 = opamp(), ["in+"] ⟷ r2[2], ["in-"] ⟷ ["out+"] ⟷ c1[2], ["out-"] ⟷ gnd
        #u1 = opamp(Val{:macak}, 1000, -4, 4)
        c2 = capacitor(10e-9), [1] ⟷ u1["in+"], [2] ⟷ gnd
        j_out = voltageprobe(), [-] ⟷ gnd, [+] ⟷ u1["out+"]
    end
end

sallenkey(::Type{DiscreteModel}=DiscreteModel; fs=44100, solver=nothing) =
    solver === nothing ?
        DiscreteModel(sallenkey(Circuit), 1//fs) :
        DiscreteModel(sallenkey(Circuit), 1//fs, solver)


text:
mutable struct Cart
    x::Int64
    y::Int64
    direction::Char
    next_turn::Char
end

import Base.isless
function isless(cart1::Cart, cart2::Cart)::Bool
    if cart1.y < cart2.y
        return true
    elseif cart1.y == cart2.y
        if cart1.x < cart2.x
            return true
        end
    end
    return false
end

function parse_map()::Tuple{Array{Char,2},Array{Cart,1}}
    lines = []
    for row in readlines(open("inputs/13.txt"))
        push!(lines, row)
    end
    carts = []
    longest_line = maximum(map(x->length(x), lines))
    grid = map(x->' ', zeros(length(lines),longest_line))
    for y in 1:length(lines)
        for x in 1:length(lines[y])
            c = lines[y][x]
            if lines[y][x] == '>'
                cart = Cart(x,y,'E','L')
                c = '-'
                push!(carts, cart)
            elseif lines[y][x] == '<'
                cart = Cart(x,y,'W','L')
                c = '-'
                push!(carts, cart)
            elseif lines[y][x] == 'v'
                cart = Cart(x,y,'S','L')
                c = '|'
                push!(carts, cart)
            elseif lines[y][x] == '^'
                cart = Cart(x,y,'N','L')
                c = '|'
                push!(carts, cart)
            end
            grid[y,x] = c
        end
    end
    return (grid, carts)
end

function check_for_crashes(grid, carts)
    occupied_coords = Set()
    for cart in carts
        if in((cart.x, cart.y), occupied_coords)
            return (true, cart.x-1, cart.y-1)
        end
        push!(occupied_coords, (cart.x, cart.y))
    end
    return (false, 0, 0)
end

function remove_crashed_carts(grid, carts)
    coords = [(cart.x, cart.y) for cart in carts]
    u = unique(coords)
    d=Dict([(i,count(x->x==i,coords)) for i in u])
    crashpoints = filter(x->x[2] > 1, collect(d))
    for point in crashpoints
        deleted = 0
        for cart in length(carts):-1:1
            if (carts[cart].x, carts[cart].y) == point[1]
                println(carts[cart])
                deleteat!(carts,cart)
                deleted += 1
            end
        end
        @assert deleted == 2
    end
end

function move_cart(grid::Array{Char,2}, cart::Cart)
    straight_track = '|'
    curve_right = '/'
    right_turn_new_dir = 'E'
    curve_left = '\\'
    left_turn_new_dir = 'W'
    next_x = cart.x
    next_y = cart.y-1

    if cart.direction == 'S'
        straight_track = '|'
        curve_right = '/'
        right_turn_new_dir = 'W'
        curve_left = '\\'
        left_turn_new_dir = 'E'
        next_x = cart.x
        next_y = cart.y+1
    elseif cart.direction == 'W'
        straight_track = '-'
        curve_right = '\\'
        right_turn_new_dir = 'N'
        curve_left = '/'
        left_turn_new_dir = 'S'
        next_x = cart.x-1
        next_y = cart.y
    elseif cart.direction == 'E'
        straight_track = '-'
        curve_right = '\\'
        right_turn_new_dir = 'S'
        curve_left = '/'
        left_turn_new_dir = 'N'
        next_x = cart.x+1
        next_y = cart.y
    end

    if grid[next_y,next_x] == straight_track
        cart.x = next_x
        cart.y = next_y
    elseif grid[next_y,next_x] == curve_right
        cart.x = next_x
        cart.y = next_y
        cart.direction = right_turn_new_dir
    elseif grid[next_y,next_x] == curve_left
        cart.x = next_x
        cart.y = next_y
        cart.direction = left_turn_new_dir
    elseif grid[next_y,next_x] == '+'
        cart.x = next_x
        cart.y = next_y
        if cart.next_turn == 'L'
            cart.direction = left_turn_new_dir
            cart.next_turn = 'S'
        elseif cart.next_turn == 'R'
            cart.direction = right_turn_new_dir
            cart.next_turn = 'L'
        elseif cart.next_turn == 'S'
            cart.direction = cart.direction
            cart.next_turn = 'R'
        end
    end
end

function run_tick(grid, carts)
    sorted_carts = sort(carts)
    for cart in sorted_carts
        result = move_cart(grid, cart)
        sorted_carts = sort(carts)
        remove_crashed_carts(aocmap...)
    end
    return check_for_crashes(grid,carts)
end

aocmap = parse_map()

while true
    crashes = run_tick(aocmap...)
    if crashes[1]
        println(crashes)
        break
    end
end

remove_crashed_carts(aocmap...)

while length(aocmap[2]) > 1
    run_tick(aocmap...)
end


text:
# OpenCL.Buffer

type Buffer{T} <: CLMemObject
    valid::Bool
    id::CL_mem
    len::Int
    mapped::Bool
    hostbuf::Ptr{T}

    function Buffer(mem_id::CL_mem, retain::Bool, len::Integer) #hostbuf
        @assert len > 0
        @assert mem_id != C_NULL
        if retain
            @check api.clRetainMemObject(mem_id)
        end
        nbytes = sizeof(T) * len
        buff = new(true, mem_id, len, false, C_NULL)
        finalizer(buff, mem_obj -> begin
            if !mem_obj.valid
                throw(CLMemoryError("Attempted to double free OpenCL.Buffer $mem_obj"))
            end
            _finalize(mem_obj)
            mem_obj.valid   = false
            mem_obj.mapped  = false
            mem_obj.hostbuf = C_NULL
        end)
        return buff
    end
end

Base.ndims(b::Buffer) = 1
Base.eltype{T}(b::Buffer{T}) = T
Base.length{T}(b::Buffer{T}) = Int(b.len)
Base.sizeof{T}(b::Buffer{T}) = Int(b.len * sizeof(T))

Base.show{T}(io::IO, b::Buffer{T}) = begin
    ptr_val = convert(UInt, Base.pointer(b))
    ptr_address = "0x$(hex(ptr_val, Sys.WORD_SIZE>>2))"
    print(io, "Buffer{$T}(@$ptr_address)")
end

# high level  Buffer constructors with symbol flags
function Buffer{T}(::Type{T}, ctx::Context, len::Integer=0; hostbuf=nothing)
    Buffer(T, ctx, (:rw, :null), len, hostbuf=hostbuf)
end

function Buffer{T}(::Type{T}, ctx::Context, mem_flag::Symbol, len::Integer=0; hostbuf=nothing)
    Buffer(T, ctx, (mem_flag, :null), len, hostbuf=hostbuf)
end

function Buffer{T}(::Type{T}, ctx::Context, mem_flags::NTuple{2, Symbol}, len::Integer=0; hostbuf=nothing)
    f_r  = :r  in mem_flags
    f_w  = :w  in mem_flags
    f_rw = :rw in mem_flags

    if f_r && f_w || f_r && f_rw || f_rw && f_w
        throw(ArgumentError("only one flag in {:r, :w, :rw} can be defined"))
    end

    local flags::CL_mem_flags
    if f_rw && !(f_r || f_w)
        flags = CL_MEM_READ_WRITE
    elseif f_r && !(f_w || f_rw)
        flags = CL_MEM_READ_ONLY
    elseif f_w && !(f_r || f_rw)
        flags = CL_MEM_WRITE_ONLY
    else
        # default buffer is read/write
        flags = CL_MEM_READ_WRITE
    end

    f_alloc = :alloc in mem_flags
    f_use   = :use   in mem_flags
    f_copy  = :copy  in mem_flags
    if f_alloc && f_use || f_alloc && f_copy || f_use && f_copy
        throw(ArgumentError("only one flag in {:alloc, :use, :copy} can be defined"))
    end

    if f_alloc && !(f_use || f_copy)
        flags |= CL_MEM_ALLOC_HOST_PTR
    elseif f_use && !(f_alloc || f_copy)
        flags |= CL_MEM_USE_HOST_PTR
    elseif f_copy && !(f_alloc || f_use)
        flags |= CL_MEM_COPY_HOST_PTR
    end
    return Buffer(T, ctx, flags, len, hostbuf=hostbuf)
end

# low level Buffer constructor with integer parameter flags
function Buffer{T}(::Type{T}, ctx::Context, flags::CL_mem_flags,
                           len::Integer=0; hostbuf::Union{Void,Array{T}}=nothing)

    if (hostbuf !== nothing &&
        (flags & (CL_MEM_USE_HOST_PTR | CL_MEM_COPY_HOST_PTR)) == 0)
        warn("'hostbuf' was passed, but no memory flags to make use of it")
    end

    if flags == (CL_MEM_USE_HOST_PTR | CL_MEM_ALLOC_HOST_PTR)
        ArgumentError("Use host pointer flag and alloc host pointer flag are mutually exclusive")
    end

    nbytes = 0
    retain_buf::Union{Void,Array{T}} = nothing

    if hostbuf !== nothing
        if (flags & CL_MEM_USE_HOST_PTR) != 0
            retain_buf = hostbuf
        end
        if len > length(hostbuf)
            ArgumentError("OpenCL.Buffer specified size greater than host buffer size")
        end
        if len == 0
            len = length(hostbuf)
            nbytes = sizeof(hostbuf)
        else
            nbytes = len * sizeof(T)
        end
    else
        if len <= 0
            ArgumentError("OpenCL.Buffer specified length is <= 0")
        end
        nbytes = len * sizeof(T)
    end

    err_code = Ref{CL_int}()
    mem_id = api.clCreateBuffer(ctx.id, flags, cl_uint(nbytes),
                                hostbuf !== nothing ? hostbuf : C_NULL,
                                err_code)
    if err_code[] != CL_SUCCESS
        throw(CLError(err_code[]))
    end

    try
        return Buffer{T}(mem_id, false, len)
    catch err
        api.clReleaseMemObject(mem_id)
        throw(err)
    end
end

# enqueue a read from buffer to hoast array from buffer, return an event
function enqueue_read_buffer{T}(q::CmdQueue,
                                        buf::Buffer{T},
                                        hostbuf::Array{T},
                                        dev_offset::Csize_t,
                                        wait_for::Union{Void,Vector{Event}},
                                        is_blocking::Bool)
    n_evts  = wait_for === nothing ? UInt(0) : length(wait_for)
    evt_ids = wait_for === nothing ? C_NULL  : [evt.id for evt in wait_for]
    ret_evt = Array(CL_event, 1)
    nbytes  = sizeof(hostbuf)
    @assert nbytes > 0
    @check api.clEnqueueReadBuffer(q.id, buf.id, cl_bool(is_blocking),
                                   dev_offset, nbytes, hostbuf,
                                   n_evts, evt_ids, ret_evt)
    @return_nanny_event(ret_evt[1], hostbuf)
end

# enqueue a write from host array to buffer, return an event
function enqueue_write_buffer{T}(q::CmdQueue,
                                         buf::Buffer{T},
                                         hostbuf::Array{T},
                                         byte_count::Csize_t,
                                         offset::Csize_t,
                                         wait_for::Union{Void,Vector{Event}},
                                         is_blocking::Bool)
    n_evts  = wait_for === nothing ? UInt(0) : length(wait_for)
    evt_ids = wait_for === nothing ? C_NULL  : [evt.id for evt in wait_for]
    ret_evt = Array(CL_event, 1)
    nbytes  = sizeof(hostbuf)
    @assert nbytes > 0
    @check api.clEnqueueWriteBuffer(q.id, buf.id, cl_bool(is_blocking),
                                    offset, nbytes, hostbuf,
                                    n_evts, evt_ids, ret_evt)
    @return_nanny_event(ret_evt[1], hostbuf)
end

# enqueue a copy from one buffer to another, return an event
function enqueue_copy_buffer{T}(q::CmdQueue,
                                        src::Buffer{T},
                                        dst::Buffer{T},
                                        byte_count::Csize_t,
                                        src_offset::Csize_t,
                                        dst_offset::Csize_t,
                                        wait_for::Union{Void,Vector{Event}})
    n_evts  = wait_for === nothing ? UInt(0) : length(wait_for)
    evt_ids = wait_for === nothing ? C_NULL  : [evt.id for evt in wait_for]
    ret_evt = Array(CL_event, 1)
    if byte_count < 0
        byte_count_src = Array(Csize_t, 1)
        byte_count_dst = Array(Csize_t, 1)
        @check api.clGetMemObjectInfo(src.id, CL_MEM_SIZE, sizeof(Csize_t),
                                      byte_count_src, C_NULL)
        @check api.clGetMemObjectInfo(src.id, CL_MEM_SIZE, sizeof(Csize_t),
                                      byte_count_dst, C_NULL)
        byte_count = min(byte_count_src[1], byte_count_dst[1])
    end
    @assert byte_count > 0
    @check api.clEnqueueCopyBuffer(q.id, src.id, dst.id,
                                   src_offset, dst_offset, byte_count,
                                   n_evts, evt_ids, ret_evt)
    @return_event ret_evt[1]
end

# return whether a given buffer is mapped
ismapped(b::Buffer) = b.mapped

# enqueue an unmap buffer op, return an event
function enqueue_unmap_mem{T}(q::CmdQueue,
                              b::Buffer{T},
                              a::Array{T};
                              wait_for=nothing)
    if b.hostbuf != pointer(a)
        throw(ArgumentError("array @$(pointer(a)) is not mapped to buffer $b"))
    end
    if b.mapped == false || b.hostbuf == C_NULL
        throw(CLMemoryError("$b has already been unmapped"))
    end
    n_evts  = 0
    evt_ids = C_NULL
    if wait_for !== nothing
        if isa(wait_for, Event)
            n_evts = 1
            evt_ids = [wait_for.id]
        else
            @assert all([isa(evt, Event) for evt in wait_for])
            n_evts = length(wait_for)
            evt_ids = [evt.id for evt in wait_for]
        end
    end
    ret_evt = Array(CL_event, 1)
    @check api.clEnqueueUnmapMemObject(q.id, b.id, a,
                                       n_evts, evt_ids, ret_evt)
    b.mapped  = false
    b.hostbuf = C_NULL
    @return_event ret_evt[1]
end

# (blocking) unmap a given buffer/array
function unmap!{T}(q::CmdQueue, b::Buffer{T}, a::Array{T})
    evt = enqueue_unmap_mem(q, b, a)
    return wait(evt)
end

# enqueue a memory mapping operation, returning a mapped (pinned) Array and an event
function enqueue_map_mem{T}(q::CmdQueue,
                            b::Buffer{T},
                            flags::Symbol,
                            offset::Integer,
                            dims::Dims,
                            wait_for=nothing,
                            is_blocking=false)
    local f::CL_map_flags
    if flags === :r
        f = CL_MAP_READ
    elseif flags === :w
        f = CL_MAP_WRITE
    elseif flags === :rw
        f = CL_MAP_READ | CL_MAP_WRITE
    else
        throw(ArgumentError("enqueue_unmap can have flags of :r, :w, or :rw, got :$flags"))
    end
    return enqueue_map_mem(q, b, f, offset, dims, wait_for, is_blocking)
end

# enqueue a memory mapping operation, returning a mapped (pinned) Array and an event
function enqueue_map_mem{T}(q::CmdQueue,
                            b::Buffer{T},
                            flags::CL_map_flags,
                            offset::Integer,
                            dims::Dims,
                            wait_for=nothing,
                            is_blocking=false)
    if length(b) < prod(dims) + offset
        throw(ArgumentError("Buffer length must be greater than or
                             equal to prod(dims) + offset"))
    end
    n_evts  = wait_for === nothing ? cl_uint(0) : cl_uint(length(wait_for))
    evt_ids = wait_for === nothing ? C_NULL  : [evt.id for evt in wait_for]
    flags   = cl_map_flags(flags)
    offset  = unsigned(offset)
    nbytes  = unsigned(prod(dims) * sizeof(T))
    ret_evt = Array(CL_event, 1)
    status  = Cint[0]
    mapped  = api.clEnqueueMapBuffer(q.id, b.id, cl_bool(is_blocking ? 1 : 0),
                                     flags, offset, nbytes,
                                     n_evts, evt_ids, ret_evt, status)
    if status[1] != CL_SUCCESS
        throw(CLError(status[1]))
    end
    mapped = Base.unsafe_convert(Ptr{T}, mapped)
    N = length(dims)
    local mapped_arr::Array{T, N}
    try
        # julia owns pointer to mapped memory
        mapped_arr = unsafe_wrap(Array{T, N}, mapped, dims, false)
        # when array is gc'd, unmap buffer
        b.mapped  = true
        b.hostbuf = mapped
        finalizer(mapped_arr, x -> begin
            if b.mapped && b.hostbuf != C_NULL
                unmap!(q, b, x)
            end
        end)
    catch err
        api.clEnqueueUnmapMemObject(q.id, b.id, mapped,
                                    unsigned(0), C_NULL, C_NULL)
        b.mapped  = false
        b.hostbuf = C_NULL
        rethrow(err)
    end
    return (mapped_arr, Event(ret_evt[1]))
end

@ocl_v1_2_only begin

    # low level enqueue fill operation, return event
    function enqueue_fill_buffer{T}(q::CmdQueue, buf::Buffer{T},
                                            pattern::T, offset::Csize_t,
                                            nbytes::Csize_t,
                                            wait_for::Union{Vector{Event},Void})

        if wait_for === nothing
            evt_ids = C_NULL
            n_evts = cl_uint(0)
        else
            evt_ids = [evt.id for evt in wait_for]
            n_evts  = cl_uint(length(evt_ids))
        end
        ret_evt = Array(CL_event, 1)
        nbytes_pattern = sizeof(pattern)
        @assert nbytes_pattern > 0
        @check api.clEnqueueFillBuffer(q.id, buf.id, [pattern],
                                       unsigned(nbytes_pattern), offset, nbytes,
                                       n_evts, evt_ids, ret_evt)
        @return_event ret_evt[1]
    end

    # enqueue a fill operation, return an event
    function enqueue_fill{T}(q::CmdQueue, buf::Buffer{T}, x::T)
        nbytes = sizeof(buf)
        evt = enqueue_fill_buffer(q, buf, x, unsigned(0),
                                  unsigned(nbytes), nothing)
        return evt
    end

    # (blocking) fill the contents of a buffer with with a given value
    function fill!{T}(q::CmdQueue, buf::Buffer{T}, x::T)
        evt = enqueue_fill(q, buf, x)
        wait(evt)
        return evt
    end
end

# copy the contents of a buffer into an array
function Base.copy!{T}(q::CmdQueue, dst::Array{T}, src::Buffer{T})
    if sizeof(dst) != sizeof(src)
        throw(ArgumentError("Buffer and Array to be copied must be the same size"))
    end
    evt = enqueue_read_buffer(q, src, dst, UInt(0), nothing, true)
    return evt
end

# copy the contents of an array into a buffer
function Base.copy!{T}(q::CmdQueue, dst::Buffer{T}, src::Array{T})
    if sizeof(dst) != sizeof(src)
        throw(ArgumentError("Array and Buffer to be copied must be the same size"))
    end
    nbytes = convert(Csize_t, sizeof(src))
    evt = enqueue_write_buffer(q, dst, src, nbytes, unsigned(0), nothing, true)
    return evt
end

# copy the contents of a buffer into another buffer
function Base.copy!{T}(q::CmdQueue, dst::Buffer{T}, src::Buffer{T})
    if sizeof(dst) != sizeof(src)
        throw(ArgumentError("Buffers to be copied must be the same size"))
    end
    nbytes = convert(Csize_t, sizeof(src))
    evt = enqueue_copy_buffer(q, src, dst, nbytes, unsigned(0),
                              unsigned(0), nothing)
    wait(evt)
    return evt
end

# copy bufer into identical buffer object
function Base.copy{T}(q::CmdQueue, src::Buffer{T})
    nbytes = sizeof(src)
    new_buff = empty_like(q[:context], src)
    copy!(q, new_buff, src)
    return new_buff
end

# create an empty buffer similar to the passed in buffer
function empty_like{T}(ctx::Context, b::Buffer{T})
    len = length(b)
    mf = info(b, :mem_flags)
    if :r in mf
        return Buffer(T, ctx, :r,  len)
    elseif :w in mf
        return Buffer(T, ctx, :w,  len)
    else
        return Buffer(T, ctx, :rw, len)
    end
end

# create an empty buffer similar to the passed in Array
function empty_like{T}(ctx::Context, a::Array{T}, flag::Symbol=:rw)
    len = length(a)
    return Buffer(T, ctx, flag, len)
end

# blocking write of contents of an array to a buffer
function write!{T}(q::CmdQueue, buf::Buffer{T}, hostbuf::Array{T})
    nbytes = unsigned(sizeof(hostbuf))
    enqueue_write_buffer(q, buf, hostbuf, nbytes, unsigned(0), nothing, true)
    return
end

# blocking read of the contents of a buffer into a new array
function read{T}(q::CmdQueue, buf::Buffer{T})
    hostbuf = Array(T, length(buf))
    enqueue_read_buffer(q, buf, hostbuf, unsigned(0), nothing, true)
    return hostbuf
end


text:
# Version of find_nth_prime() in Julia, for comparing speeds.
# This takes about 2.3 s on both Julia version 0.5.2 and 0.6.0.
#
# Please let me know if this can be optimized (in terms of Julia tricks,
# not the algorithm itself).

function find_nth_prime(i_max::Int64)
    n = 0
    i = -1

    while n < i_max
        i = i + 1

        if i <= 1
            continue  # nope
        elseif i == 2
            n = n + 1
        else
            gotit = 1
            for j in 2:(div(i, 2) + 1)  # note the integer division, // is rational!
                if i % j == 0
                    gotit = 0
                    break
                end
            end
            if gotit == 1
                n = n + 1
            end
        end
    end
    return i
end

# Let the JIT warm up
find_nth_prime(11)

tic()
i = find_nth_prime(10001)
toc()

println(i)

max_stars_repo_name: almarklein/pywasm

max_issues_repo_name: almarklein/wasmfun

max_forks_repo_name: almarklein/pywasm


text: abstract type CoStateInitializer end


text:
@polyvar x y
@variable(model, t)
S = @set x^2 == x && y^2 == y
@constraint(model, x - y >= t, domain = S, maxdegree=2)
@objective(model, Max, t)
optimize!(model)
println("Solution: $(value(t))")
# Returns t = -1

max_stars_repo_name: sums-of-squares/tools

max_issues_repo_name: sums-of-squares/tools

max_forks_repo_name: sums-of-squares/tools


text:
import Random
import PyPlot

using LinearAlgebra
import Interpolations

#include("../src/PatchMixtureKriging.jl")
import PatchMixtureKriging

PyPlot.close("all")

Random.seed!(25)

fig_num = 1

##### regression
#θ = Spline34KernelType(0.2)
θ = PatchMixtureKriging.BrownianBridge10(1.0)
#θ = BrownianBridge20(1.0)
#θ = BrownianBridge1ϵ(4.5)
#θ = BrownianBridge2ϵ(2.5)

σ² = 1e-5
N = 15

# if 0 and 1 are included, we have posdef error, or rank = N - 2.
x_range = LinRange(1e-5, 1.0-1e-5, N)

X = collect( [x_range[n]] for n = 1:N )
coordwrapper = xx->PatchMixtureKriging.convert2itpindex(xx, X[1], X[end], [length(X)])

f = xx->sinc(4*xx)*xx^3
y = f.(x_range)

# check posdef.
K = PatchMixtureKriging.constructkernelmatrix(X, θ)
println("rank(K) = ", rank(K))

println("isposdef = ", isposdef(K))

# fit RKHS.
η = PatchMixtureKriging.RKHSProblemType( zeros(Float64,length(X)),
                     X,
                     θ,
                     σ²)
                     PatchMixtureKriging.fitRKHS!(η, y)

# query.
Nq = 100
xq_range = LinRange(0.0, 1.0, Nq)
xq = collect( [xq_range[n]] for n = 1:Nq )

f_xq = f.(xq_range) # generating function.

yq = Vector{Float64}(undef, Nq)
PatchMixtureKriging.query!(yq,xq,η)

# Visualize regression result.
PyPlot.figure(fig_num)
fig_num += 1

PyPlot.plot(X, y, ".", label = "observed")
PyPlot.plot(xq, yq, label = "query - RKHS")

PyPlot.plot(xq, f_xq, label = "true")

title_string = "1-D RKHS demo"
PyPlot.title(title_string)
PyPlot.legend()
##### end of regression

max_stars_repo_name: RoyCCWang/PatchMixtureKriging

max_issues_repo_name: RoyCCWang/PatchMixtureKriging


text:
#==============================================================================#
# MediaStoreData.jl
#
# This file is generated from:
# https://github.com/aws/aws-sdk-js/blob/master/apis/mediastore-data-2017-09-01.normal.json
#==============================================================================#

__precompile__()

module MediaStoreData

using AWSCore

"""
    using AWSSDK.MediaStoreData.delete_object
    delete_object([::AWSConfig], arguments::Dict)
    delete_object([::AWSConfig]; Path=)

    using AWSCore.Services.mediastore_data
    mediastore_data([::AWSConfig], "DELETE", "/{Path+}", arguments::Dict)
    mediastore_data([::AWSConfig], "DELETE", "/{Path+}", Path=)

# DeleteObject Operation

Deletes an object at the specified path.

# Arguments

## `Path = ::String` -- *Required*
The path (including the file name) where the object is stored in the container. Format: <folder name>/<folder name>/<file name>

# Returns

`DeleteObjectResponse`

# Exceptions

`ContainerNotFoundException`, `ObjectNotFoundException` or `InternalServerError`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/mediastore-data-2017-09-01/DeleteObject)
"""
@inline delete_object(aws::AWSConfig=default_aws_config(); args...) = delete_object(aws, args)

@inline delete_object(aws::AWSConfig, args) = AWSCore.Services.mediastore_data(aws, "DELETE", "/{Path+}", args)

@inline delete_object(args) = delete_object(default_aws_config(), args)

"""
    using AWSSDK.MediaStoreData.describe_object
    describe_object([::AWSConfig], arguments::Dict)
    describe_object([::AWSConfig]; Path=)

    using AWSCore.Services.mediastore_data
    mediastore_data([::AWSConfig], "HEAD", "/{Path+}", arguments::Dict)
    mediastore_data([::AWSConfig], "HEAD", "/{Path+}", Path=)

# DescribeObject Operation

Gets the headers for an object at the specified path.

# Arguments

## `Path = ::String` -- *Required*
The path (including the file name) where the object is stored in the container. Format: <folder name>/<folder name>/<file name>

# Returns

`DescribeObjectResponse`

# Exceptions

`ContainerNotFoundException`, `ObjectNotFoundException` or `InternalServerError`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/mediastore-data-2017-09-01/DescribeObject)
"""
@inline describe_object(aws::AWSConfig=default_aws_config(); args...) = describe_object(aws, args)

@inline describe_object(aws::AWSConfig, args) = AWSCore.Services.mediastore_data(aws, "HEAD", "/{Path+}", args)

@inline describe_object(args) = describe_object(default_aws_config(), args)

"""
    using AWSSDK.MediaStoreData.get_object
    get_object([::AWSConfig], arguments::Dict)
    get_object([::AWSConfig]; Path=, <keyword arguments>)

    using AWSCore.Services.mediastore_data
    mediastore_data([::AWSConfig], "GET", "/{Path+}", arguments::Dict)
    mediastore_data([::AWSConfig], "GET", "/{Path+}", Path=, <keyword arguments>)

# GetObject Operation

Downloads the object at the specified path.

# Arguments

## `Path = ::String` -- *Required*
The path (including the file name) where the object is stored in the container. Format: <folder name>/<folder name>/<file name>

For example, to upload the file `mlaw.avi` to the folder path `premium\\canada` in the container `movies`, enter the path `premium/canada/mlaw.avi`.

Do not include the container name in this path.

If the path includes any folders that don't exist yet, the service creates them. For example, suppose you have an existing `premium/usa` subfolder. If you specify `premium/canada`, the service creates a `canada` subfolder in the `premium` folder. You then have two subfolders, `usa` and `canada`, in the `premium` folder.

There is no correlation between the path to the source and the path (folders) in the container in AWS Elemental MediaStore.

For more information about folders and how they exist in a container, see the [AWS Elemental MediaStore User Guide](http://docs.aws.amazon.com/mediastore/latest/ug/).

The file name is the name that is assigned to the file that you upload. The file can have the same name inside and outside of AWS Elemental MediaStore, or it can have the same name. The file name can include or omit an extension.

## `*header:* Range = ::String`
The range bytes of an object to retrieve. For more information about the `Range` header, go to [http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35).

# Returns

`GetObjectResponse`

# Exceptions

`ContainerNotFoundException`, `ObjectNotFoundException`, `RequestedRangeNotSatisfiableException` or `InternalServerError`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/mediastore-data-2017-09-01/GetObject)
"""
@inline get_object(aws::AWSConfig=default_aws_config(); args...) = get_object(aws, args)

@inline get_object(aws::AWSConfig, args) = AWSCore.Services.mediastore_data(aws, "GET", "/{Path+}", args)

@inline get_object(args) = get_object(default_aws_config(), args)

"""
    using AWSSDK.MediaStoreData.list_items
    list_items([::AWSConfig], arguments::Dict)
    list_items([::AWSConfig]; <keyword arguments>)

    using AWSCore.Services.mediastore_data
    mediastore_data([::AWSConfig], "GET", "/", arguments::Dict)
    mediastore_data([::AWSConfig], "GET", "/", <keyword arguments>)

# ListItems Operation

Provides a list of metadata entries about folders and objects in the specified folder.

# Arguments

## `Path = ::String`
The path in the container from which to retrieve items. Format: <folder name>/<folder name>/<file name>

## `MaxResults = ::Int`
The maximum results to return. The service might return fewer results.

## `NextToken = ::String`
The `NextToken` received in the `ListItemsResponse` for the same container and path. Tokens expire after 15 minutes.

# Returns

`ListItemsResponse`

# Exceptions

`ContainerNotFoundException` or `InternalServerError`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/mediastore-data-2017-09-01/ListItems)
"""
@inline list_items(aws::AWSConfig=default_aws_config(); args...) = list_items(aws, args)

@inline list_items(aws::AWSConfig, args) = AWSCore.Services.mediastore_data(aws, "GET", "/", args)

@inline list_items(args) = list_items(default_aws_config(), args)

"""
    using AWSSDK.MediaStoreData.put_object
    put_object([::AWSConfig], arguments::Dict)
    put_object([::AWSConfig]; Body=, Path=, <keyword arguments>)

    using AWSCore.Services.mediastore_data
    mediastore_data([::AWSConfig], "PUT", "/{Path+}", arguments::Dict)
    mediastore_data([::AWSConfig], "PUT", "/{Path+}", Body=, Path=, <keyword arguments>)

# PutObject Operation

Uploads an object to the specified path. Object sizes are limited to 10 MB.

# Arguments

## `Body = blob` -- *Required*
The bytes to be stored.

## `Path = ::String` -- *Required*
The path (including the file name) where the object is stored in the container. Format: <folder name>/<folder name>/<file name>

For example, to upload the file `mlaw.avi` to the folder path `premium\\canada` in the container `movies`, enter the path `premium/canada/mlaw.avi`.

Do not include the container name in this path.

If the path includes any folders that don't exist yet, the service creates them. For example, suppose you have an existing `premium/usa` subfolder. If you specify `premium/canada`, the service creates a `canada` subfolder in the `premium` folder. You then have two subfolders, `usa` and `canada`, in the `premium` folder.

There is no correlation between the path to the source and the path (folders) in the container in AWS Elemental MediaStore.

For more information about folders and how they exist in a container, see the [AWS Elemental MediaStore User Guide](http://docs.aws.amazon.com/mediastore/latest/ug/).

The file name is the name that is assigned to the file that you upload. The file can have the same name inside and outside of AWS Elemental MediaStore, or it can have the same name. The file name can include or omit an extension.

## `*header:* Content-Type = ::String`
The content type of the object.

## `*header:* Cache-Control = ::String`
An optional `CacheControl` header that allows the caller to control the object's cache behavior. Headers can be passed in as specified in the HTTP at [https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9](https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9).

Headers with a custom user-defined value are also accepted.

## `*header:* x-amz-storage-class = "TEMPORAL"`
Indicates the storage class of a `Put` request. Defaults to high-performance temporal storage class, and objects are persisted into durable storage shortly after being received.

# Returns

`PutObjectResponse`

# Exceptions

`ContainerNotFoundException` or `InternalServerError`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/mediastore-data-2017-09-01/PutObject)
"""
@inline put_object(aws::AWSConfig=default_aws_config(); args...) = put_object(aws, args)

@inline put_object(aws::AWSConfig, args) = AWSCore.Services.mediastore_data(aws, "PUT", "/{Path+}", args)

@inline put_object(args) = put_object(default_aws_config(), args)

end # module MediaStoreData

#==============================================================================#
# End of file
#==============================================================================#


text:
module AdaptiveResonance

# Usings/imports for the whole package declared once
using Parameters    # ARTopts are parameters (@with_kw)
using Logging       # Logging utils used as main method of terminal reporting
using ProgressBars  # Provides progress bars for training and inference
using Printf        # Used for printing formatted progress bars
using LinearAlgebra: norm   # Trace and norms
using Statistics: median, mean  # Medians and mean for linkage methods

# Abstract types
abstract type ARTOpts end               # ART module options
abstract type ARTModule end             # ART modules
abstract type ART <: ARTModule end      # ART (unsupervised)
abstract type ARTMAP <: ARTModule end   # ARTMAP (supervised)

# Include all files
include("common.jl")        # Objects shared by all modules
include("constants.jl")     # Global constants and references for convenience
include("ARTMAP/ARTMAP.jl") # Supervised ART modules
include("ART/ART.jl")       # Unsupervised ART modules

# Export all public names
export

    # Abstract types
    ARTOpts,        # All module options are ARTOpts
    ARTModule,      # All modules are ART modules
    ART,            # ART modules (unsupervised)
    ARTMAP,         # ARTMAP modules (supervised)

    # Algorithmic functions
    train!,         # Train models: train!(art, data, y=[])
    classify,       # Inference: classify(art, data)
    performance,    # Classification accuracy: performance(y, y_hat)

    # Common structures
    DataConfig,     # ART data configs (feature ranges, dimension, etc.)
    data_setup!,    # Correctly set up an ART data configuration

    # Common utility functions
    complement_code,            # Map x -> [x, 1 - x] and normalize to [0, 1]
    get_data_characteristics,   # Get characteristics of x, used by data configs
    linear_normalization,       # Normalize x to [0, 1]
    get_data_shape,             # Get the dim, n_samples of x (accepts 1-D and 2-D)
    get_n_samples,              # Get the number of samples (1-D interpreted as one sample)

    # ART (unsupervised)
    FuzzyART, opts_FuzzyART,
    DDVFA, opts_DDVFA, get_W,
    DVFA, opts_DVFA,

    # ARTMAP (supervised)
    FAM, opts_FAM,
    DAM, opts_DAM,
    SFAM, opts_SFAM,

    # ARTSCENE filter functions
    color_to_gray,
    contrast_normalization,
    contrast_sensitive_oriented_filtering,
    contrast_insensitive_oriented_filtering,
    orientation_competition,
    patch_orientation_color,
    artscene_filter     # Runs all of the above in one step, returning features

end # module


text:
@inline function rootn_dbsi_db(x::DoubleFloat{T}, n::Signed) where {T<:AbstractFloat}
    return DoubleFloat{T}(rootn_ddsi_dd(HILO(x), n))
end


text:
@doc raw"""
    genVarConstr(M, coeffB, RHS)

This will be generated as markdown documentation by Documenter
"""

function genVarConstr(M::Model, coeffB::Array{Float64,1}, RHS::Array{Float64,1})
        @variable(M, -10 <= x <= 100)
        @variable(M, -10 <= y <= 100)
        @variable(M, -10 <= z <= 100)
        @constraint(M, coeffB[1] * x + coeffB[2] * y + coeffB[3] * z == RHS[1])
        return M
end

@doc raw"""
    testLP(setting, sep, coeffA, coeffB, coefC, RHS)

This will be generated as markdown documentation by Documenter
"""

function testLP(settings::Dict, coeffA::Array{Float64,1}, coeffB::Array{Float64,1}, coeffC::Array{Float64,1}, RHS::Array{Float64,1})
        if settings["Solver"] == "Gurobi"
                #Gurobi.GurobiSolver #Clp.ClpSolver
	        #model=Model(solver=GurobiSolver()) #For JuMP 18
                # I am just adding a line to see I can push a commit
                model=Model(Gurobi.Optimizer) #Model(Clp.Optimizer)
                model = genVarConstr(model, coeffB, RHS)
                @constraint(model, coeffC[1] * model[:x]^2 + coeffC[2] * model[:y]^2 + coeffC[3] * model[:z]^2 <= RHS[2])
                @objective(model, Min, coeffA[1]*model[:x]^2+coeffA[2]*model[:y]+coeffA[3]*model[:z]^2)
                #tstatus = solve(model) #For JuMP 18
        elseif settings["Solver"] == "Ipopt"
	        #model=Model(solver=GurobiSolver()) #For JuMP 18
                model = Model(Ipopt.Optimizer)
                model = genVarConstr(model, coeffB, RHS)
                @NLconstraint(model, coeffC[1] * model[:x]^2 + coeffC[2] * model[:y]^2 + coeffC[3] * model[:z]^2 <= RHS[2])
                @NLobjective(model, Min, coeffA[1]*model[:x]^2+coeffA[2]*model[:y]+coeffA[3]*model[:z]^2)
        end
        optimize!(model)
        tstatus = termination_status(model)
        optimal_obj = objective_value(model)
        opt_decVar1 = value(model[:x]) #getvalue(x) #JuMP 18
        opt_decVar2 = value(model[:y])
        opt_decVar3 = value(model[:z])

        results = Dict(
        "status" => tstatus,
        "optimal_obj" => optimal_obj,
        "opt_decVar1" => opt_decVar1,
        "opt_decVar2" => opt_decVar2,
        "opt_decVar3" => opt_decVar3,
        )

        return results
end