text:
function dependencies_json(app::DashApp)
    id_prop_named(p::IdProp) = (id = p[1], property = p[2])
    result = map(values(app.callbacks)) do dep
        (inputs = id_prop_named.(dep.id.input),
        state = id_prop_named.(dep.id.state),
        output = output_string(dep.id)
        )
    end
    return JSON2.write(result)
end

function process_dependencies(request::HTTP.Request, state::HandlerState)
    return HTTP.Response(
        200,
        ["Content-Type" => "application/json"],
        body = state.cache.dependencies_json
        )
end

function process_index(request::HTTP.Request, state::HandlerState)
    get_cache(state).need_recache && rebuild_cache!(state)
    return HTTP.Response(
        200,
        ["Content-Type" => "text/html"],
        body = state.cache.index_string
        )
end

layout_data(layout::Component) = layout
layout_data(layout::Function) = layout()
function process_layout(request::HTTP.Request, state::HandlerState)
    return HTTP.Response(
        200,
        ["Content-Type" => "application/json"],
        body = JSON2.write(layout_data(state.app.layout))
    )
end

function _process_callback(app::DashApp, body::String)
    params = JSON2.read(body)
    output = Symbol(params[:output])
    if !haskey(app.callbacks, output)
        return []
    end
    convert_values(inputs) = map(inputs) do x
        return get(x, :value, nothing)
    end
    args = []
    if haskey(params, :state)
        append!(args, convert_values(params.state))
    end
    if haskey(params, :inputs)
        append!(args, convert_values(params.inputs))
    end

    res = app.callbacks[output].func(args...)
    if length(app.callbacks[output].id.output) == 1
        if !(res isa NoUpdate)
            return Dict(
                :response => Dict(
                    :props => Dict(
                        Symbol(app.callbacks[output].id.output[1][2]) => Front.to_dash(res)
                    )
                )
            )
        else
            throw(PreventUpdate())
        end
    end
    response = Dict{Symbol, Any}()
    for (ind, out) in enumerate(app.callbacks[output].id.output)
        if !(res[ind] isa NoUpdate)
            push!(response,
            Symbol(out[1]) => Dict(
                Symbol(out[2]) => Front.to_dash(res[ind])
            )
            )
        end
    end
    if length(response) == 0
        throw(PreventUpdate())
    end
    return Dict(:response=>response, :multi=>true)
end

function process_callback(request::HTTP.Request, state::HandlerState)
        try
            return HTTP.Response(200, ["Content-Type" => "application/json"],
                body = JSON2.write(
                    _process_callback(state.app, String(request.body))
                )
            )
        catch e
            if isa(e,PreventUpdate)
                return HTTP.Response(204)
            else
                rethrow(e)
            end
        end
end

function mime_by_path(path)
    endswith(path, ".js") && return "application/javascript"
    endswith(path, ".css") && return "text/css"
    endswith(path, ".map") && return "application/json"
    return nothing
end
function process_resource(request::HTTP.Request, state::HandlerState; namespace::AbstractString, path::AbstractString)
    (relative_path, is_fp) = parse_fingerprint_path(path)
    registered_files = state.cache.resources.files
    if !haskey(registered_files, namespace)
        #TODO Exception like in python
        return HTTP.Response(404)
    end
    namespace_files = registered_files[namespace]
    if !in(relative_path, namespace_files.files)
        #TODO Exception like in python
        return HTTP.Response(404)
    end

    filepath = joinpath(namespace_files.base_path, relative_path)

    try
        headers = Pair{String,String}[]
        file_contents = read(joinpath(namespace_files.base_path, relative_path))
        mimetype = mime_by_path(relative_path)
        !isnothing(mimetype) && push!(headers, "Content-Type" => mimetype)
        if is_fp
            push!(headers,
                "Cache-Control" => "public, max-age=31536000" # 1 year
            )
        else
            etag = bytes2hex(MD5.md5(file_contents))
            push!(headers, "ETag" => etag)
            request_etag = HTTP.header(request, "If-None-Match", "")
            request_etag == etag && return HTTP.Response(304)
        end
        return HTTP.Response(200, headers; body = file_contents)

    catch e
        !(e isa SystemError) && rethrow(e)
        #TODO print to log
        return HTTP.Response(404)
    end
end

function process_assets(request::HTTP.Request, state::HandlerState; file_path::AbstractString)
    app = state.app
    filename = joinpath(get_assets_path(app), file_path)

    try
        headers = Pair{String,String}[]
        mimetype = mime_by_path(filename)
        !isnothing(mimetype) && push!(headers, "Content-Type" => mimetype)
        file_contents = read(filename)
        return HTTP.Response(200, headers;body = file_contents)
    catch
        return HTTP.Response(404)
    end

end

function process_reload_hash(request::HTTP.Request, state::HandlerState)
    reload_tuple = (
        reloadHash = state.reload.hash,
        hard = state.reload.hard,
        packages = keys(state.cache.resources.files),
        files = state.reload.changed_assets
    )
    state.reload.hard = false
    state.reload.changed_assets = []
    return HTTP.Response(200, ["Content-Type" => "application/json"], body = JSON2.write(reload_tuple))

end

function start_reload_poll(state::HandlerState)
    folders = Set{String}()
    push!(folders, get_assets_path(state.app))
    push!(folders, state.registry.dash_renderer.path)
    for pkg in values(state.registry.components)
        push!(folders, pkg.path)
    end
    state.reload.task = @async poll_folders(folders; interval = get_devsetting(state.app, :hot_reload_watch_interval)) do file, ts, deleted
        state.reload.hard = true
        state.reload.hash = generate_hash()
        assets_path = get_assets_path(state.app)
        if startswith(file, assets_path)
            state.cache.need_recache = true
            rel_path = lstrip(
                    replace(relpath(file, assets_path), '\\'=>'/'),
                    '/'
                )
            push!(state.reload.changed_assets,
                ChangedAsset(
                    asset_path(state.app, rel_path),
                    trunc(Int, ts),
                    endswith(file, "css")
                    )
            )
        end

    end
end

validate_layout(layout::Component) = validate(layout)

validate_layout(layout::Function) = validate_layout(layout())

validate_layout(layout) = error("The layout must be a component, tree of components, or a function which returns a component.")
#For test purposes, with the ability to pass a custom registry
function make_handler(app::DashApp, registry::ResourcesRegistry; check_layout = false)

    state = HandlerState(app, registry)
    prefix = get_setting(app, :routes_pathname_prefix)
    assets_url_path = get_setting(app, :assets_url_path)
    check_layout && validate_layout(get_layout(app))

    router = Router()
    add_route!(process_layout, router, "$(prefix)_dash-layout")
    add_route!(process_dependencies, router, "$(prefix)_dash-dependencies")
    add_route!(process_reload_hash, router, "$(prefix)_reload-hash")
    add_route!(process_resource, router, "$(prefix)_dash-component-suites/<namespace>/<path>")
    add_route!(process_assets, router, "$(prefix)$(assets_url_path)/<file_path>")
    add_route!(process_callback, router, "POST", "$(prefix)_dash-update-component")
    add_route!(process_index, router, "$prefix/*")
    add_route!(process_index, router, "$prefix")

    handler = state_handler(router, state)
    get_setting(app, :compress) && (handler = compress_handler(handler))

    compile_request = HTTP.Request("GET", prefix)
    HTTP.setheader(compile_request, "Accept-Encoding" => "gzip")
    HTTP.handle(handler, compile_request) #For handler precompilation

    get_devsetting(app, :hot_reload) && start_reload_poll(state)

    return handler
end

function make_handler(app::DashApp)
    return make_handler(app, main_registry(), check_layout = true)
end


text:
function currency_exchange_rate(from_currency::String, to_currency::String; client = GLOBAL[], parser = "default")
    params = Dict(
        "function"=>"CURRENCY_EXCHANGE_RATE",
        "from_currency"=>from_currency,
        "to_currency"=>to_currency,
        "apikey"=>key(client)
    )
    uri = _build_uri(client.scheme, client.host, "query", params)
    data = retry(_get_request, delays=Base.ExponentialBackOff(n=3, first_delay=5, max_delay=1000))(uri)
    p = _parser(parser, "json")
    return p(data)
end

function fx_intraday(from_currency::String, to_currency::String, interval::String="1min"; client = GLOBAL[], outputsize::String="compact", datatype::Union{String, Nothing}=nothing, parser = "default")
    @argcheck in(interval, ["1min", "5min", "15min", "30min", "60min"])
    @argcheck in(outputsize, ["compact", "full"])
    @argcheck in(datatype, ["json", "csv", nothing])

    params = Dict(
        "function"=>"FX_INTRADAY",
        "from_symbol"=>from_currency,
        "to_symbol"=>to_currency,
        "interval"=>interval,
        "outputsize"=>outputsize,
        "datatype"=>isnothing(datatype) ? "csv" : datatype,
        "apikey"=>key(client)
    )
    uri = _build_uri(client.scheme, client.host, "query", params)
    data = retry(_get_request, delays=Base.ExponentialBackOff(n=3, first_delay=5, max_delay=1000))(uri)
    p = _parser(parser, datatype)
    return p(data)
end

function fx_daily(from_currency::String, to_currency::String; client = GLOBAL[], outputsize::String="compact", datatype::Union{String, Nothing}=nothing, parser = "default")
    @argcheck in(outputsize, ["compact", "full"])
    @argcheck in(datatype, ["json", "csv", nothing])

    params = Dict(
        "function"=>"FX_DAILY",
        "from_symbol"=>from_currency,
        "to_symbol"=>to_currency,
        "outputsize"=>outputsize,
        "datatype"=>isnothing(datatype) ? "csv" : datatype,
        "apikey"=>key(client)
    )
    uri = _build_uri(client.scheme, client.host, "query", params)
    data = retry(_get_request, delays=Base.ExponentialBackOff(n=3, first_delay=5, max_delay=1000))(uri)
    p = _parser(parser, datatype)
    return p(data)
end

for func in (:weekly, :monthly)
    x = "fx_$(func)"
    fname = Symbol(x)
    @eval begin
        function ($fname)(from_currency::String, to_currency::String; client = GLOBAL[], datatype::Union{String, Nothing}=nothing, parser = "default")
            @argcheck in(datatype, ["json", "csv", nothing])
            params = Dict(
                "function"=>uppercase($x),
                "from_symbol"=>from_currency,
                "to_symbol"=>to_currency,
                "datatype"=>isnothing(datatype) ? "csv" : datatype,
                "apikey"=>key(client)
            )
            uri = _build_uri(client.scheme, client.host, "query", params)
            data = retry(_get_request, delays=Base.ExponentialBackOff(n=3, first_delay=5, max_delay=1000))(uri)
            p = _parser(parser, datatype)
            return p(data)
        end
        export $fname
    end
end

ext: jl


text:
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

# Assertions

struct AlwaysAssertionError <: Exception
    msg::String
end

# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

# Steps

abstract type AbstractStep end

struct DockerOnlyLine <: AbstractStep
    full_contents::String
end

struct PlaceholderDockerCopyFiles <: AbstractStep
end

struct RunStep <: AbstractStep
    command::String
end

struct EnvStep <: AbstractStep
    name::String
    value::String
end

struct AptStep <: AbstractStep
    command::String
end

struct PlaceholderYumStep <: AbstractStep
end

# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

# Step list

struct StepList
    list::Vector{AbstractStep}
end

# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

# Files

struct File
    contents::String
    dest_dir::String
    dest_filename::String
    dest_full_path::String
end

function File(contents::String,
              dest_dir::String,
              dest_filename::String)
    dest_full_path = string(dest_dir,
                            "/",
                            dest_filename)
    result = File(contents,
                  dest_dir,
                  dest_filename,
                  dest_full_path)
    return result
end

# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

# File plan

struct FileList
    list::Vector{File}
end

# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

# Template

struct Template
    files::FileList
    steps::StepList
end

# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


text:
# Burma Shave, but evaluating multiple channels per core.

using ArgParse

s = ArgParseSettings()
@add_arg_table s begin
    # "--opt1"
    # help = "an option with an argument"
    "--run_index", "-r"
    help = "Output run index"
    arg_type = Int
    # default = 0
    "--chain"
    help = "Write the chain to ~/web/ directory?"
    action = :store_true
    "--opt"
    help = "Use NLOpt instead of LittleMC"
    action = :store_true
    "config"
    help = "a YAML configuration file"
    required = true
end

parsed_args = parse_args(ARGS, s)

import YAML
config = YAML.load(open(parsed_args["config"]))

outfmt(run_index::Int) = config["out_base"] * @sprintf("run%02d/", run_index)

# This code is necessary for multiple simultaneous runs on odyssey
# so that different runs do not write into the same output directory
if parsed_args["run_index"] == nothing
    run_index = 0
    outdir = outfmt(run_index)
    while ispath(outdir)
        println(outdir, " exists")
        run_index += 1
        outdir = outfmt(run_index)
    end
else
    run_index = parsed_args["run_index"]
    outdir = outfmt(run_index)
    println("Deleting old $outdir")
    run(`rm -rf $outdir`)
end

# make the output directory
println("Creating ", outdir)
mkdir(outdir)

using visibilities
# load data and figure out how many channels
dvarr = DataVis(config["data_file"])
nchan = length(dvarr)

if haskey(config, "exclude")
    exclude = config["exclude"]
    const global keylist = filter(x->(!in(x, exclude)), Int[i for i=1:nchan]) # which channels of the dset to fit
else
    const global keylist = Int[i for i=1:nchan]
end

# go through any previously created directories and remove them
function cleardirs!(keylist::Vector{Int})
    println("Removing old directories")
    for keys in keylist
        key = keys[1]
        keydir = basedir * "jud$key"
        run(`rm -rf $keydir`)
    end
    println("Removed directories")
end

# This program is meant to be started with the -p option.
nchild = nworkers()
println("Workers allocated ", nchild)

# Chunk up the keylist into an acceptable number of keys per process.
max_keys_per_process = iceil(length(keylist)/nchild)
partial_proc = max_keys_per_process * nchild - length(keylist) # num of unfull processors
full_proc = nchild - partial_proc # number of full processors

chunk_keylist = Array(Any, nchild)
start_key = 1
end_key = start_key + (max_keys_per_process - 1)
for i=1:full_proc
    chunk_keylist[i] = keylist[start_key:end_key]
    start_key += max_keys_per_process
    end_key += max_keys_per_process
end

# Inch back to prep for filling the partially filled processes
end_key -= 1
# Now fill the partial_proc
for i=(full_proc+1):nchild
    chunk_keylist[i] = keylist[start_key:end_key]
    start_key += (max_keys_per_process - 1)
    end_key += (max_keys_per_process - 1)
end

# make the values of run_index and config available on all processes
for process in procs()
    @spawnat process global run_id=run_index
    @spawnat process global cfg=config
end

@everywhere basefmt(id::Int) = cfg["base_dir"] * @sprintf("run%02d/", id)

@everywhere const global basedir = basefmt(run_id)

# make the internal Judith directory, if it doesn't exist
if !ispath(basedir)
    println("Creating ", basedir)
    mkdir(basedir)
end

# Clear all directories
cleardirs!(keylist)

@everywhere using constants
@everywhere using parallel
@everywhere using visibilities
@everywhere using image
@everywhere using gridding
@everywhere using emodel

# Delete the old log file (if it exists)
const logfile = outdir * "log.log"
if isfile(logfile)
    rm(logfile)
end

using Logging
# change the default logger
Logging.configure(filename=logfile, level=DEBUG)

debug("Created logfile.")

@everywhere function initfunc(keys)

    # In contrast to `burma_shave.jl`, now each dataset receives several
    # channels, specified by keys

    # Load the relevant chunk of the dataset, return array
    dvarr = DataVis(cfg["data_file"], keys)
    for dset in dvarr
        # Conjugation is necessary for the SMA, methinks
        visibilities.conj!(dset) # Swap UV convention
    end

    # Create a directory where all RADMC files will reside and be driven from
    # using the first key as the directory index
    key = keys[1]
    keydir = basedir * "jud$key"
    println("Creating $keydir")
    mkdir(keydir)

    # Copy all relevant configuration scripts to this subdirectory
    # these are mainly setup files which will not change throughout the run
    run(`cp radmc3d.inp $keydir`)
    ag = basedir * "amr_grid.inp"
    run(`cp $ag $keydir`)
    run(`cp lines.inp $keydir`)
    run(`cp molecule_co.inp $keydir`)
    run(`cp wavelength_micron.inp $keydir`)

    # change the subprocess to reside in this directory for the remainder of the run
    # where it will drive its own independent RADMC3D process
    cd(keydir)

    # For each channel, also calculate the interpolation closures
    # npix = cfg["npix"]
    # pixsize = cfg["pixsize"] # [cm]
    # pix_AU = pixsize/AU # [AU]
    #
    # dl = sin(pix_AU/cfg["parameters"]["dpc"][1] * arcsec)
    #
    # uu = fftshift(fftfreq(npix, dl)) * 1e-3 # [kλ]
    # vv = fftshift(fftfreq(npix, dl)) * 1e-3 # [kλ]
    #
    # int_arr = Array(Function, length(keys))
    # for (i, dset) in enumerate(dvarr)
    #     int_arr[i] = plan_interpolate(dset, uu, vv)
    # end

    # return the array of datasets
    return dvarr

end

# This is the likelihood function called by each individual process
@everywhere function f(dvarr, keys::Vector{Int}, p::Parameters)
    # dvarr, int_arr = data

    nkeys = length(keys)

    # We are using the following convention: inclination ranges from
    # 0 to 180 degrees. 0 means face on, angular momentum vector pointing
    # at observer; 90 means edge on; and 180 means face on, angular momentum
    # vector pointing away from observer.
    # These are also the RADMC conventions.
    incl = p.incl # [deg]

    # We also adopt the RADMC convention for position angle, which defines position angle
    # by the angular momentum vector.
    # A positive PA angle means the disk angular momentum vector will be
    # rotated counter clockwise (from North towards East).
    PA = p.PA # [deg]

    vel = p.vel # [km/s]
    npix = cfg["npix"] # number of pixels, can alternatively specify x and y separately

    # Doppler shift the dataset wavelengths to rest-frame wavelength
    beta = vel/c_kms # relativistic Doppler formula
    lams = Array(Float64, length(keys))
    for i=1:nkeys
        lams[i] =  dvarr[i].lam * sqrt((1. - beta) / (1. + beta)) # [microns]
    end

    # key = keys[1]
    # keydir = basedir * "jud$key/"
    # println("Writing cameralambda into $keydir")
    write_lambda(lams, "") # write into current directory
    write_model(p, "", grid)

    # Run RADMC3D, redirect output to /dev/null
    run(`radmc3d image incl $incl posang $PA npix $npix loadlambda` |> DevNull)

    # Read the RADMC3D images from disk (we should already be in sub-directory)
    im = imread()

    # Convert raw images to the appropriate distance
    skim = imToSky(im, p.dpc)

    # Apply the gridding correction function before doing the FFT
    # shifts necessary as if the image were already offset
    corrfun!(skim, p.mu_RA, p.mu_DEC) # alpha = 1.0

    lnprobs = Array(Float64, nkeys)
    # Do the Fourier domain stuff per channel
    for i=1:nkeys
        dv = dvarr[i]
        # FFT the appropriate image channel
        vis_fft = transform(skim, i)

        # Apply the phase correction here, before we do the interpolation
        phase_shift!(vis_fft, p.mu_RA, p.mu_DEC)

        # Interpolate the `vis_fft` to the same locations as the DataSet
        # mvis = int_arr[i](dv, vis_fft)
        mvis = ModelVis(dv, vis_fft)

        # Calculate chi^2 between these two
        lnprobs[i] = lnprob(dv, mvis)

    end
    # Sum them all together and feed back to the master process
    return sum(lnprobs)

end

# Create the model grid
@everywhere global const grd = cfg["grid"]
@everywhere global const grid = Grid(grd["nr"], grd["ntheta"], grd["nphi"], grd["r_in"], grd["r_out"], grd["na"], true)
# Regenerate all of the static files (e.g., amr_grid.inp)
# so that they may be later copied
debug("Writing grid")
write_grid(basedir, grid)
debug("Wrote grid")

debug("Initializing processes")
pipes = initialize(nchild, chunk_keylist, initfunc, f)
gather!(pipes)
debug("Initialized processes")

# Calculate the lnprior based upon the current parameter values
function lnprior(pars::Parameters)
    mu_d = 142. # [pc]
    sig_d = 6. # [pc]
    return -0.5 * (pars.dpc - mu_d)^2 / sig_d^2
end

# this function is called only on the main process, which proposes MCMC jumps
# to this function, and farms out the likelihood evaluation to all of the child
# processes
function fprob(p::Vector{Float64})
    # Here is where we make the distinction between a proposed vector of floats
    # (i.e., the parameters), and the object which defines all of the disk parameters
    # which every single subprocess will use

    # Parameters is a composite type defined in model.jl or emodel.jl.

    # Fix the following arguments: gamma, dpc
    gamma = 1.0 # surface temperature gradient exponent
    dpc = cfg["parameters"]["dpc"][1] # [pc] distance

    M_star, a_c, T_10, q, logM_CO, ksi, incl, PA, e, w, vel, mu_RA, mu_DEC = p

    # Enforce hard priors on physical parameters
    # Short circuit evaluation if we know the RADMC won't be valid.
    if ksi <= 0. || T_10 <= 0. || a_c <= 0.0 || M_star <= 0.0
        return -Inf
    end

    if incl < 0. || incl > 180.
        return -Inf
    end

    if e < 0.0 || e > 0.7
        return -Inf
    end

    if w < 0. || w > 360.
        return -Inf
    end

    M_CO = 10^logM_CO

    # If we are going to fit with some parameters dropped out, here's the place to do it
    pars = Parameters(M_star, a_c, T_10, q, gamma, M_CO, ksi, dpc, incl, PA, e, w, vel, mu_RA, mu_DEC)

    distribute!(pipes, pars)
    return gather!(pipes) + lnprior(pars)# the summed lnprob
end

# wrapper for NLopt requires gradient as an argument (even if it's not used)
function fgrad(p::Vector, grad::Vector)
    val = fprob(p)
    debug(p, " : ", val)
    return val
end

function fp(p::Vector)
    val = fprob(p)
    debug(p, " : ", val)
    return val
end

debug("Initializing MCMC")
using Distributions
using PDMats

pp = config["parameters"]
# The parameters we'll be using
params = ["M_star", "a_c", "T_10", "q", "logM_CO", "ksi", "incl", "PA", "e", "w", "vel", "mu_RA", "mu_DEC"]
nparam = length(params)
starting_param = Array(Float64, nparam)
jumps = Array(Float64, nparam)

for i=1:nparam
    starting_param[i], jumps[i] = pp[params[i]]
end

if parsed_args["opt"]

    # Now try optimizing the function using NLopt
    using NLopt

    nparam = length(starting_param)
    opt = Opt(:LN_COBYLA, nparam)

    max_objective!(opt, fgrad)
    ftol_abs!(opt, 0.05) # the precision we want lnprob to

    lower = Float64[1.9, 3.0, 1.0, 0.01, -5.0, 0.01, 100.0, 140.0, -26.5, 0.0, 0.0]
    upper = Float64[3.0, 40., 100., 1.0, 1.0, 0.5, 115., 145., -25.5, 0.1, 0.1]

    lower_bounds!(opt, lower)
    upper_bounds!(opt, upper)

    (optf,optx,ret) = optimize(opt, starting_param)
    println(optf, " ", optx, " ", ret)

else

    # Use LittleMC to do the optimization

    jump_param = PDiagMat(jumps.^2)
    jump_param = full(jump_param)

    # Perturb the starting parameters
    proposal = MvNormal(jump_param)
    starting_param = starting_param .+ 3. * rand(proposal)

    # If we've provided an empirically measured covariance matrix for the MCMC
    # jump proposals, use that instead of our jumps without covariance
    if haskey(config, "opt_jump")
        using NPZ
        jump_param = config["jump_scale"]^2 * npzread(config["opt_jump"])
    end

    using LittleMC

    # Code to hook into the chain.js plot generator
    if parsed_args["chain"]
        csv = open("/n/home07/iczekala/web/chain.js/mc.csv", "w")
    else
        csv = open(outdir * "mc.csv", "w")
    end

    #Write the parameter header
    writecsv(csv, params')

    mc = MC(fp, config["samples"], starting_param, jump_param, csv)
    debug("Initialized MCMC")

    LittleMC.start(mc)

    println(mean(mc.samples, 2))
    println(std(mc.samples, 2))

    runstats(mc)

    debug("Acceptance: ", LittleMC.acceptance(mc))

    LittleMC.write(mc, outdir * "mc.hdf5")
    close(csv)

end

quit!(pipes)

max_stars_repo_name: elnjensen/DiskJockey

max_issues_repo_name: elnjensen/DiskJockey

max_forks_repo_name: elnjensen/DiskJockey


text:
module QuarkDroplets

export njlradius, saveradius

# Package which contains Bessel functions as besselj(ν,x)
using SpecialFunctions
# Package for obstaning the roots of a given function
using Roots
# Package for performing numerical integration
using QuadGK
# Package for solving nonlinear system of equations
using NLsolve
# Package for saving and loading results to Julia .jld files
using JLD

# Spherical bessel function of argument x and order l
function sphericalbessel(x, l)
    return √(π/2x)*besselj(l+1/2, x)
end

# Energy cutoff [MeV]
const Λ = 600
# Planck's constant [MeV⋅fm]
const ħ = 197.5
# Number of colors
const Nc = 3
# Number of flavours
const Nf = 2
# Coupling constant [MeV^(-2)] as chosen in [arXiv:hep-ph/0411128]
const G = 4.7 / 2 / Λ^2

# Solves the NJL mass gap equations for a fixed radius
include("njlradius.jl")

end

max_stars_repo_name: avramescudana/QuarkDroplets

max_issues_repo_name: avramescudana/QuarkDroplets

max_forks_repo_name: avramescudana/QuarkDroplets


text:
__precompile__(false)
module Globals

using GlobalFileHelper, FluidTensors, FluidFields, StaticArrays

export LX,LY,LZ,NX,NY,NZ,NRRX,NRX,ν,DEALIAS_TYPE,KX,KY,KZ,THR,NT,TRANGE,REAL_RANGES,DEALIAS,K,RXRANGE,XRANGE,YRANGE,ZRANGE,RANGEC, COMPLEX_RANGES, ZYRANGE
export RYRANGE, RZRANGE, XRANGE2X, KH, MAXDKH, KRZ, DKZ, SPEC_FIL_D2, SPEC_FIL_CUTOFF, STAT_FIL

include("CatVec.jl")

function nshells(kx,ky,kz)
    maxdk = max(kx[2],ky[2],kz[2])
    n = round(Int,sqrt(kx[end]^2 + maximum(x->x*x,ky) + maximum(x->x*x,kz))/maxdk) + 1
    return n, maxdk
end

function nshells2D(kx,ky)
    maxdk = max(kx[2],ky[2])
    n = round(Int,sqrt(kx[end]^2 + maximum(x->x*x,ky))/maxdk) + 1
    return n, maxdk
end

function compute_shells(kx::AbstractVector{T},ky::AbstractVector,kz::AbstractVector) where {T}
    Nx = length(kx)
    Ny = length(ky)
    Nz = length(kz)
    nShells, maxdk = nshells(kx,ky,kz)
    kh = zeros(T,nShells)
    numPtsInShell = zeros(Int,nShells)

    @inbounds for k in 1:Nz
        kz2 = kz[k]^2
        for j=1:Ny
            kzy2 = kz2 + ky[j]^2
            for i=1:Nx
                K = sqrt(muladd(kx[i],kx[i],kzy2))
                ii = round(Int,K/maxdk)+1
                kh[ii] += K
                numPtsInShell[ii] += 1
            end
        end
    end

    @inbounds @simd for i in 1:length(kh)
        kh[i] = kh[i]/numPtsInShell[i]
    end

    return kh
end

function compute_shells2D(kx::AbstractVector{T},ky) where {T}
    Nx = length(kx)
    Ny = length(ky)
    nShells2D, maxdk2D = nshells2D(kx,ky)
    kh = zeros(T,nShells2D)
    numPtsInShell2D = zeros(Int,nShells2D)

    @inbounds for j=1:Ny
        ky2 = ky[j]^2
        for i=1:Nx
            K = sqrt(muladd(kx[i],kx[i], ky2))
            ii = round(Int,K/maxdk2D)+1
            kh[ii] += K
            numPtsInShell2D[ii] += 1
        end
    end

    @inbounds @simd for i in 1:length(kh)
        kh[i] = kh[i]/numPtsInShell2D[i]
    end

    return kh
end

function splitrange(lr,nt)
    a = UnitRange{Int}[]
    sizehint!(a,nt)
    n = lr÷nt
    r = lr%nt
    stop = 0
    init = 1
    for i=1:r
        stop=init+n
        push!(a,init:stop)
        init = stop+1
    end
    for i=1:(nt-r)
        stop=init+n-1
        push!(a,init:stop)
        init = stop+1
    end
    return (a...,)
end

function rfftfreq(n::Integer,s::Real)::Vector{Float64}
    Float64[(n/2 - i)/s for i = n/2:-1:0]
end

function fftfreq(n::Integer,s::Real)::Vector{Float64}
    if iseven(n)
        return vcat(Float64[(n/2 - i)/s for i = n/2:-1:1],Float64[-i/s for i = n/2:-1:1])
    else return vcat(Float64[(n/2 - i)/s for i = n/2:-1:0],Float64[-i/s for i = (n-1)/2:-1:1])
    end
end

    d = readglobal()
    const global NRX = parse(Int,d[:nx])
    const global NY = parse(Int,d[:ny])
    const global NZ = parse(Int,d[:nz])

    const global NX = div(NRX,2)+1
    const global NRRX = 2NX

    const global LX = Float64(eval(Meta.parse(d[:xDomainSize])))
    const global LY = Float64(eval(Meta.parse(d[:yDomainSize])))
    const global LZ = Float64(eval(Meta.parse(d[:zDomainSize])))
    const global ν = Float64(eval(Meta.parse(d[:kinematicViscosity])))

    kxp = reshape(rfftfreq(NRX,LX),(NX,1,1))
    kyp = reshape(fftfreq(NY,LY),(1,NY,1))
    kzp = reshape(fftfreq(NZ,LZ),(1,1,NZ))

    haskey(d,:threaded) ? (tr = parse(Bool,d[:threaded])) : (tr = true)
    const global THR = tr

    const global NT = tr ? Threads.nthreads() : 1
    const global TRANGE = SOneTo(NT)

    const global REAL_RANGES = splitrange(NRRX*NY*NZ, NT)
    const global COMPLEX_RANGES = splitrange(NX*NY*NZ, NT)

    haskey(d,:cutoff) ? (cutoffr = Float64(eval(Meta.parse(d[:cutoff])))) : (cutoffr = 2/3)
    const global DEALIAS_TYPE = cutoffr

    cutoff = (cutoffr*kxp[end])^2
    cutoffx = (cutoffr*kxp[end])^2
    cutoffy = (cutoffr*maximum(abs,kyp))^2
    cutoffz = (cutoffr*maximum(abs,kzp))^2

    const global DEALIAS = BitArray(undef,(NX,NY,NZ))

    @. DEALIAS = (kxp^2 > cutoffx) | (kyp^2 > cutoffy) | (kzp^2 > cutoffz)

    const global KX = FluidFields.SRKvec(NRX,LX)#(kxp...,)
    const global KY = FluidFields.SKvec(NY,LY)#(kyp...,)
    const global KZ = FluidFields.SKvec(NZ,LZ)#(kzp...,)

    const global KH = (KX[2] >= KY[2]) ? KX : FluidFields.SRKvec(NY,LY)
    const global MAXDKH = KH[2]

    const global KRZ = FluidFields.SRKvec(NZ,LZ)
    const global DKZ = KRZ[2]

    s = (NX,NY,NZ)
    const global K = VecArray(HomogeneousArray{1}(KX,s),HomogeneousArray{2}(KY,s),HomogeneousArray{3}(KZ,s))

    const global RXRANGE = StaticArrays.SOneTo(NRX)
    const global RYRANGE = StaticArrays.SOneTo(NY)
    const global RZRANGE = StaticArrays.SOneTo(NZ)
    const global RANGEC = StaticArrays.SOneTo(NX*NY*NZ)

    const global XRANGE = StaticArrays.SOneTo(findfirst(view(DEALIAS,:,1,1))-1)
    const global XRANGE2X = StaticArrays.SOneTo(2length(XRANGE))
    const global YRANGE = CatVec(StaticArrays.SOneTo(findfirst(view(DEALIAS,1,:,1))-1),
                                 StaticArrays.SUnitRange(NY-findfirst(view(DEALIAS,1,:,1)) ,NY))

    const global ZRANGE = CatVec(StaticArrays.SOneTo(findfirst(view(DEALIAS,1,1,:))-1),
                                 StaticArrays.SUnitRange(NZ-findfirst(view(DEALIAS,1,1,:)) ,NZ))

    const global ZYRANGE = CartesianIndices((StaticArrays.SOneTo(length(YRANGE)),StaticArrays.SOneTo(length(ZRANGE))))

    const global SPEC_FIL_D2 = if haskey(d,:specFil)
        nf = parse(Float64,d[:specFil])
        (2π*LX*nf/NRX)^2
    else
        0.0
    end

    const global STAT_FIL = SPEC_FIL_D2 != 0.0

    const global SPEC_FIL_CUTOFF = π*π/SPEC_FIL_D2

end


text:
function update_eta!(state::State, data::Data, prior::Prior)
  update_etaC!(state, data, prior)
  update_etaT!(state, data, prior)
end

function update_etaC!(state::State, data::Data, prior::Prior)
  anew = prior.eta.alpha .+ 0

  for n in eachindex(state.lambdaC)
    anew[state.lambdaC[n]] += 1
  end

  if !state.beta
    for n in eachindex(state.lambdaT)
      anew[state.lambdaT[n]] += 1
    end
  end

  state.etaC = rand(Dirichlet(anew))
end

function update_etaT!(state::State, data::Data, prior::Prior)
  anew = prior.eta.alpha .+ 0

  if state.beta
    for n in eachindex(state.lambdaT)
      anew[state.lambdaT[n]] += 1
    end
  end

  state.etaT = rand(Dirichlet(anew))
end

max_stars_repo_name: luiarthur/CytofDensityEstimation

max_issues_repo_name: luiarthur/CytofDensityEstimation

max_forks_repo_name: luiarthur/CytofDensityEstimation


text:
module Dex

using Dex_jll

export DexCtx
export setup, start, stop, restart, isrunning

mutable struct DexCtx
    workdir::String
    proc::Union{Base.Process,Nothing}
    pid::Union{Int,Nothing}

    function DexCtx(workdir)
        ctx = new(workdir, nothing, nothing)
        pfile = pidfile(ctx)
        if isfile(pfile)
            ctx.pid = parse(Int, read(pidfile(ctx), String))
            isrunning(ctx)
        end
        ctx
    end
end

webdir(ctx::DexCtx) = joinpath(ctx.workdir, "web")
confdir(ctx::DexCtx) = joinpath(ctx.workdir, "conf")
conffile(ctx::DexCtx) = joinpath(confdir(ctx), "dexconfig.yaml")
logsdir(ctx::DexCtx) = joinpath(ctx.workdir, "logs")
pidfile(ctx::DexCtx) = joinpath(logsdir(ctx), "dex.pid")
logfile(ctx::DexCtx) = joinpath(logsdir(ctx), "dex.log")

function setup(ctx::DexCtx, configfile::String, templates::Union{String,Nothing}=nothing; force::Bool=false, reset_templates::Bool=(templates !== nothing))
    existing_setup = isdir(confdir(ctx)) && isdir(webdir(ctx)) && isdir(logsdir(ctx))

    existing_setup && !force && error("setup already exists, specify force=true to overwrite")

    # make the workdir
    for path in (webdir(ctx), confdir(ctx), logsdir(ctx))
        isdir(path) || mkpath(path)
    end

    # place configuration file
    (force || !isfile(conffile(ctx))) && cp(configfile, conffile(ctx); force=true)

    if reset_templates || !existing_setup
        # extract bundled templates
        run(`tar -xzf $webtemplates -C $(webdir(ctx))`)

        # copy over user provided templates
        (templates !== nothing) && run(`cp -R -f $(joinpath(templates, ".")) $(webdir(ctx))`)
    end
    nothing
end

function start(ctx::DexCtx; log=logfile(ctx), append::Bool=isa(log,AbstractString))
    config = conffile(ctx)
    dex() do dex_path
        command = Cmd(`$dex_path serve $config`; detach=true, dir=ctx.workdir)
        redirected_command = pipeline(command, stdout=log, stderr=log, append=append)
        ctx.proc = run(redirected_command; wait=false)
    end
    ctx.pid = getpid(ctx.proc)
    open(joinpath(logsdir(ctx), "dex.pid"), "a") do file
        println(file, ctx.pid)
    end
    nothing
end

isrunning(ctx::DexCtx) = (ctx.pid !== nothing) ? isrunning(ctx, ctx.pid) : false
function isrunning(ctx::DexCtx, pid::Int)
    dex_path = dex() do path
        path
    end

    cmdlinefile = "/proc/$pid/cmdline"
    if isfile(cmdlinefile)
        cmdline = read(cmdlinefile, String)
        if occursin(dex_path, cmdline) && occursin(confdir(ctx), cmdline)
            # process still running
            return true
        end
    end

    ctx.pid = nothing
    ctx.proc = nothing
    rm(pidfile(ctx); force=true)
    false
end

function stop(ctx::DexCtx)
    if isrunning(ctx)
        if ctx.proc !== nothing
            kill(ctx.proc)
        else
            run(Cmd(`/usr/bin/pkill -P $(ctx.pid)`; ignorestatus=true))
            run(`/bin/kill $(ctx.pid)`)
        end
        ctx.pid = nothing
        ctx.proc = nothing
        rm(pidfile(ctx); force=true)
    end
    nothing
end

function restart(ctx::DexCtx; delay_seconds::Int=0, log=logfile(ctx), append::Bool=isa(log,AbstractString))
    stop(ctx)
    (delay_seconds > 0) && sleep(delay_seconds)
    start(ctx; log=log, append=append)
end

end


text:
# Julia wrapper for header: /usr/include/slurm/slurm.h
# Automatically generated using Clang.jl wrap_c, version 0.0.0

function slurm_strerror(errnum::Cint)
    ccall((:slurm_strerror,libslurm),Cstring,(Cint,),errnum)
end

function slurm_seterrno(errnum::Cint)
    ccall((:slurm_seterrno,libslurm),Void,(Cint,),errnum)
end

function slurm_get_errno()
    ccall((:slurm_get_errno,libslurm),Cint,())
end

function slurm_perror(msg)
    ccall((:slurm_perror,libslurm),Void,(Cstring,),msg)
end

function slurm_hostlist_create(hostlist)
    ccall((:slurm_hostlist_create,libslurm),hostlist_t,(Cstring,),hostlist)
end

function slurm_hostlist_count(hl::hostlist_t)
    ccall((:slurm_hostlist_count,libslurm),Cint,(hostlist_t,),hl)
end

function slurm_hostlist_destroy(hl::hostlist_t)
    ccall((:slurm_hostlist_destroy,libslurm),Void,(hostlist_t,),hl)
end

function slurm_hostlist_find(hl::hostlist_t,hostname)
    ccall((:slurm_hostlist_find,libslurm),Cint,(hostlist_t,Cstring),hl,hostname)
end

function slurm_hostlist_push(hl::hostlist_t,hosts)
    ccall((:slurm_hostlist_push,libslurm),Cint,(hostlist_t,Cstring),hl,hosts)
end

function slurm_hostlist_push_host(hl::hostlist_t,host)
    ccall((:slurm_hostlist_push_host,libslurm),Cint,(hostlist_t,Cstring),hl,host)
end

function slurm_hostlist_ranged_string(hl::hostlist_t,n::Cint,buf)
    ccall((:slurm_hostlist_ranged_string,libslurm),ssize_t,(hostlist_t,Cint,Cstring),hl,n,buf)
end

function slurm_hostlist_ranged_string_malloc(hl::hostlist_t)
    ccall((:slurm_hostlist_ranged_string_malloc,libslurm),Cstring,(hostlist_t,),hl)
end

function slurm_hostlist_ranged_string_xmalloc(hl::hostlist_t)
    ccall((:slurm_hostlist_ranged_string_xmalloc,libslurm),Cstring,(hostlist_t,),hl)
end

function slurm_hostlist_shift(hl::hostlist_t)
    ccall((:slurm_hostlist_shift,libslurm),Cstring,(hostlist_t,),hl)
end

function slurm_hostlist_uniq(hl::hostlist_t)
    ccall((:slurm_hostlist_uniq,libslurm),Void,(hostlist_t,),hl)
end

function slurm_list_append(l::List,x)
    ccall((:slurm_list_append,libslurm),Ptr{Void},(List,Ptr{Void}),l,x)
end

function slurm_list_count(l::List)
    ccall((:slurm_list_count,libslurm),Cint,(List,),l)
end

function slurm_list_create(f::ListDelF)
    ccall((:slurm_list_create,libslurm),List,(ListDelF,),f)
end

function slurm_list_destroy(l::List)
    ccall((:slurm_list_destroy,libslurm),Void,(List,),l)
end

function slurm_list_find(i::ListIterator,f::ListFindF,key)
    ccall((:slurm_list_find,libslurm),Ptr{Void},(ListIterator,ListFindF,Ptr{Void}),i,f,key)
end

function slurm_list_is_empty(l::List)
    ccall((:slurm_list_is_empty,libslurm),Cint,(List,),l)
end

function slurm_list_iterator_create(l::List)
    ccall((:slurm_list_iterator_create,libslurm),ListIterator,(List,),l)
end

function slurm_list_iterator_reset(i::ListIterator)
    ccall((:slurm_list_iterator_reset,libslurm),Void,(ListIterator,),i)
end

function slurm_list_iterator_destroy(i::ListIterator)
    ccall((:slurm_list_iterator_destroy,libslurm),Void,(ListIterator,),i)
end

function slurm_list_next(i::ListIterator)
    ccall((:slurm_list_next,libslurm),Ptr{Void},(ListIterator,),i)
end

function slurm_list_sort(l::List,f::ListCmpF)
    ccall((:slurm_list_sort,libslurm),Void,(List,ListCmpF),l,f)
end

function slurm_list_pop(l::List)
    ccall((:slurm_list_pop,libslurm),Ptr{Void},(List,),l)
end

function slurm_print_block_info_msg(out,info_ptr,one_liner::Cint)
    ccall((:slurm_print_block_info_msg,libslurm),Void,(Ptr{FILE},Ptr{block_info_msg_t},Cint),out,info_ptr,one_liner)
end

function slurm_print_block_info(out,bg_info_ptr,one_liner::Cint)
    ccall((:slurm_print_block_info,libslurm),Void,(Ptr{FILE},Ptr{block_info_t},Cint),out,bg_info_ptr,one_liner)
end

function slurm_sprint_block_info(bg_info_ptr,one_liner::Cint)
    ccall((:slurm_sprint_block_info,libslurm),Cstring,(Ptr{block_info_t},Cint),bg_info_ptr,one_liner)
end

function slurm_load_block_info(update_time::time_t,block_info_msg_pptr,show_flags::UInt16)
    ccall((:slurm_load_block_info,libslurm),Cint,(time_t,Ptr{Ptr{block_info_msg_t}},UInt16),update_time,block_info_msg_pptr,show_flags)
end

function slurm_free_block_info_msg(block_info_msg)
    ccall((:slurm_free_block_info_msg,libslurm),Void,(Ptr{block_info_msg_t},),block_info_msg)
end

function slurm_update_block(block_msg)
    ccall((:slurm_update_block,libslurm),Cint,(Ptr{update_block_msg_t},),block_msg)
end

function slurm_init_update_block_msg(update_block_msg)
    ccall((:slurm_init_update_block_msg,libslurm),Void,(Ptr{update_block_msg_t},),update_block_msg)
end

function slurm_init_job_desc_msg(job_desc_msg)
    ccall((:slurm_init_job_desc_msg,libslurm),Void,(Ptr{job_desc_msg_t},),job_desc_msg)
end

function slurm_allocate_resources(job_desc_msg,job_alloc_resp_msg)
    ccall((:slurm_allocate_resources,libslurm),Cint,(Ptr{job_desc_msg_t},Ptr{Ptr{resource_allocation_response_msg_t}}),job_desc_msg,job_alloc_resp_msg)
end

function slurm_allocate_resources_blocking(user_req,timeout::time_t,pending_callback)
    ccall((:slurm_allocate_resources_blocking,libslurm),Ptr{resource_allocation_response_msg_t},(Ptr{job_desc_msg_t},time_t,Ptr{Void}),user_req,timeout,pending_callback)
end

function slurm_free_resource_allocation_response_msg(msg)
    ccall((:slurm_free_resource_allocation_response_msg,libslurm),Void,(Ptr{resource_allocation_response_msg_t},),msg)
end

function slurm_free_job_alloc_info_response_msg(msg)
    ccall((:slurm_free_job_alloc_info_response_msg,libslurm),Void,(Ptr{job_alloc_info_response_msg_t},),msg)
end

function slurm_allocation_lookup(job_id::UInt32,info)
    ccall((:slurm_allocation_lookup,libslurm),Cint,(UInt32,Ptr{Ptr{job_alloc_info_response_msg_t}}),job_id,info)
end

function slurm_allocation_lookup_lite(job_id::UInt32,info)
    ccall((:slurm_allocation_lookup_lite,libslurm),Cint,(UInt32,Ptr{Ptr{resource_allocation_response_msg_t}}),job_id,info)
end

function slurm_read_hostfile(filename,n::Cint)
    ccall((:slurm_read_hostfile,libslurm),Cstring,(Cstring,Cint),filename,n)
end

function slurm_allocation_msg_thr_create(port,callbacks)
    ccall((:slurm_allocation_msg_thr_create,libslurm),Ptr{allocation_msg_thread_t},(Ptr{UInt16},Ptr{slurm_allocation_callbacks_t}),port,callbacks)
end

function slurm_allocation_msg_thr_destroy(msg_thr)
    ccall((:slurm_allocation_msg_thr_destroy,libslurm),Void,(Ptr{allocation_msg_thread_t},),msg_thr)
end

function slurm_submit_batch_job(job_desc_msg,slurm_alloc_msg)
    ccall((:slurm_submit_batch_job,libslurm),Cint,(Ptr{job_desc_msg_t},Ptr{Ptr{submit_response_msg_t}}),job_desc_msg,slurm_alloc_msg)
end

function slurm_free_submit_response_response_msg(msg)
    ccall((:slurm_free_submit_response_response_msg,libslurm),Void,(Ptr{submit_response_msg_t},),msg)
end

function slurm_job_will_run(job_desc_msg)
    ccall((:slurm_job_will_run,libslurm),Cint,(Ptr{job_desc_msg_t},),job_desc_msg)
end

function slurm_job_will_run2(req,will_run_resp)
    ccall((:slurm_job_will_run2,libslurm),Cint,(Ptr{job_desc_msg_t},Ptr{Ptr{will_run_response_msg_t}}),req,will_run_resp)
end

function slurm_sbcast_lookup(job_id::UInt32,step_id::UInt32,info)
    ccall((:slurm_sbcast_lookup,libslurm),Cint,(UInt32,UInt32,Ptr{Ptr{job_sbcast_cred_msg_t}}),job_id,step_id,info)
end

function slurm_free_sbcast_cred_msg(msg)
    ccall((:slurm_free_sbcast_cred_msg,libslurm),Void,(Ptr{job_sbcast_cred_msg_t},),msg)
end

function slurm_load_licenses(arg1::time_t,arg2,arg3::UInt16)
    ccall((:slurm_load_licenses,libslurm),Cint,(time_t,Ptr{Ptr{license_info_msg_t}},UInt16),arg1,arg2,arg3)
end

function slurm_free_license_info_msg(arg1)
    ccall((:slurm_free_license_info_msg,libslurm),Void,(Ptr{license_info_msg_t},),arg1)
end

function slurm_load_assoc_mgr_info(arg1,arg2)
    ccall((:slurm_load_assoc_mgr_info,libslurm),Cint,(Ptr{assoc_mgr_info_request_msg_t},Ptr{Ptr{assoc_mgr_info_msg_t}}),arg1,arg2)
end

function slurm_free_assoc_mgr_info_msg(arg1)
    ccall((:slurm_free_assoc_mgr_info_msg,libslurm),Void,(Ptr{assoc_mgr_info_msg_t},),arg1)
end

function slurm_free_assoc_mgr_info_request_members(arg1)
    ccall((:slurm_free_assoc_mgr_info_request_members,libslurm),Void,(Ptr{assoc_mgr_info_request_msg_t},),arg1)
end

function slurm_free_assoc_mgr_info_request_msg(arg1)
    ccall((:slurm_free_assoc_mgr_info_request_msg,libslurm),Void,(Ptr{assoc_mgr_info_request_msg_t},),arg1)
end

function slurm_kill_job(job_id::UInt32,signal::UInt16,flags::UInt16)
    ccall((:slurm_kill_job,libslurm),Cint,(UInt32,UInt16,UInt16),job_id,signal,flags)
end

function slurm_kill_job_step(job_id::UInt32,step_id::UInt32,signal::UInt16)
    ccall((:slurm_kill_job_step,libslurm),Cint,(UInt32,UInt32,UInt16),job_id,step_id,signal)
end

function slurm_kill_job2(job_id,signal::UInt16,flags::UInt16)
    ccall((:slurm_kill_job2,libslurm),Cint,(Cstring,UInt16,UInt16),job_id,signal,flags)
end

function slurm_signal_job(job_id::UInt32,signal::UInt16)
    ccall((:slurm_signal_job,libslurm),Cint,(UInt32,UInt16),job_id,signal)
end

function slurm_signal_job_step(job_id::UInt32,step_id::UInt32,signal::UInt32)
    ccall((:slurm_signal_job_step,libslurm),Cint,(UInt32,UInt32,UInt32),job_id,step_id,signal)
end

function slurm_complete_job(job_id::UInt32,job_return_code::UInt32)
    ccall((:slurm_complete_job,libslurm),Cint,(UInt32,UInt32),job_id,job_return_code)
end

function slurm_terminate_job_step(job_id::UInt32,step_id::UInt32)
    ccall((:slurm_terminate_job_step,libslurm),Cint,(UInt32,UInt32),job_id,step_id)
end

function slurm_step_ctx_params_t_init(ptr)
    ccall((:slurm_step_ctx_params_t_init,libslurm),Void,(Ptr{slurm_step_ctx_params_t},),ptr)
end

function slurm_step_ctx_create(step_params)
    ccall((:slurm_step_ctx_create,libslurm),Ptr{slurm_step_ctx_t},(Ptr{slurm_step_ctx_params_t},),step_params)
end

function slurm_step_ctx_create_timeout(step_params,timeout::Cint)
    ccall((:slurm_step_ctx_create_timeout,libslurm),Ptr{slurm_step_ctx_t},(Ptr{slurm_step_ctx_params_t},Cint),step_params,timeout)
end

function slurm_step_ctx_create_no_alloc(step_params,step_id::UInt32)
    ccall((:slurm_step_ctx_create_no_alloc,libslurm),Ptr{slurm_step_ctx_t},(Ptr{slurm_step_ctx_params_t},UInt32),step_params,step_id)
end

function slurm_jobinfo_ctx_get(jobinfo,data_type::Cint,data)
    ccall((:slurm_jobinfo_ctx_get,libslurm),Cint,(Ptr{switch_jobinfo_t},Cint,Ptr{Void}),jobinfo,data_type,data)
end

function slurm_step_ctx_daemon_per_node_hack(ctx,node_list,node_cnt::UInt32,curr_task_num)
    ccall((:slurm_step_ctx_daemon_per_node_hack,libslurm),Cint,(Ptr{slurm_step_ctx_t},Cstring,UInt32,Ptr{UInt32}),ctx,node_list,node_cnt,curr_task_num)
end

function slurm_step_ctx_destroy(ctx)
    ccall((:slurm_step_ctx_destroy,libslurm),Cint,(Ptr{slurm_step_ctx_t},),ctx)
end

function slurm_step_launch_params_t_init(ptr)
    ccall((:slurm_step_launch_params_t_init,libslurm),Void,(Ptr{slurm_step_launch_params_t},),ptr)
end

function slurm_step_launch(ctx,params,callbacks)
    ccall((:slurm_step_launch,libslurm),Cint,(Ptr{slurm_step_ctx_t},Ptr{slurm_step_launch_params_t},Ptr{slurm_step_launch_callbacks_t}),ctx,params,callbacks)
end

function slurm_step_launch_add(ctx,params,node_list,start_nodeid::Cint)
    ccall((:slurm_step_launch_add,libslurm),Cint,(Ptr{slurm_step_ctx_t},Ptr{slurm_step_launch_params_t},Cstring,Cint),ctx,params,node_list,start_nodeid)
end

function slurm_step_launch_wait_start(ctx)
    ccall((:slurm_step_launch_wait_start,libslurm),Cint,(Ptr{slurm_step_ctx_t},),ctx)
end

function slurm_step_launch_wait_finish(ctx)
    ccall((:slurm_step_launch_wait_finish,libslurm),Void,(Ptr{slurm_step_ctx_t},),ctx)
end

function slurm_step_launch_abort(ctx)
    ccall((:slurm_step_launch_abort,libslurm),Void,(Ptr{slurm_step_ctx_t},),ctx)
end

function slurm_step_launch_fwd_signal(ctx,signo::Cint)
    ccall((:slurm_step_launch_fwd_signal,libslurm),Void,(Ptr{slurm_step_ctx_t},Cint),ctx,signo)
end

function slurm_step_launch_fwd_wake(ctx)
    ccall((:slurm_step_launch_fwd_wake,libslurm),Void,(Ptr{slurm_step_ctx_t},),ctx)
end

function slurm_mpi_plugin_init(plugin_name)
    ccall((:slurm_mpi_plugin_init,libslurm),Cint,(Cstring,),plugin_name)
end

function slurm_api_version()
    ccall((:slurm_api_version,libslurm),Clong,())
end

function slurm_load_ctl_conf(update_time::time_t,slurm_ctl_conf_ptr)
    ccall((:slurm_load_ctl_conf,libslurm),Cint,(time_t,Ptr{Ptr{slurm_ctl_conf_t}}),update_time,slurm_ctl_conf_ptr)
end

function slurm_free_ctl_conf(slurm_ctl_conf_ptr)
    ccall((:slurm_free_ctl_conf,libslurm),Void,(Ptr{slurm_ctl_conf_t},),slurm_ctl_conf_ptr)
end

function slurm_print_ctl_conf(out,slurm_ctl_conf_ptr)
    ccall((:slurm_print_ctl_conf,libslurm),Void,(Ptr{FILE},Ptr{slurm_ctl_conf_t}),out,slurm_ctl_conf_ptr)
end

function slurm_write_ctl_conf(slurm_ctl_conf_ptr,node_info_ptr,part_info_ptr)
    ccall((:slurm_write_ctl_conf,libslurm),Void,(Ptr{slurm_ctl_conf_t},Ptr{node_info_msg_t},Ptr{partition_info_msg_t}),slurm_ctl_conf_ptr,node_info_ptr,part_info_ptr)
end

function slurm_ctl_conf_2_key_pairs(slurm_ctl_conf_ptr)
    ccall((:slurm_ctl_conf_2_key_pairs,libslurm),Ptr{Void},(Ptr{slurm_ctl_conf_t},),slurm_ctl_conf_ptr)
end

function slurm_print_key_pairs(out,key_pairs,title)
    ccall((:slurm_print_key_pairs,libslurm),Void,(Ptr{FILE},Ptr{Void},Cstring),out,key_pairs,title)
end

function slurm_load_slurmd_status(slurmd_status_ptr)
    ccall((:slurm_load_slurmd_status,libslurm),Cint,(Ptr{Ptr{slurmd_status_t}},),slurmd_status_ptr)
end

function slurm_free_slurmd_status(slurmd_status_ptr)
    ccall((:slurm_free_slurmd_status,libslurm),Void,(Ptr{slurmd_status_t},),slurmd_status_ptr)
end

function slurm_print_slurmd_status(out,slurmd_status_ptr)
    ccall((:slurm_print_slurmd_status,libslurm),Void,(Ptr{FILE},Ptr{slurmd_status_t}),out,slurmd_status_ptr)
end

function slurm_init_update_step_msg(step_msg)
    ccall((:slurm_init_update_step_msg,libslurm),Void,(Ptr{step_update_request_msg_t},),step_msg)
end

function slurm_get_statistics(buf,req)
    ccall((:slurm_get_statistics,libslurm),Cint,(Ptr{Ptr{stats_info_response_msg_t}},Ptr{stats_info_request_msg_t}),buf,req)
end

function slurm_reset_statistics(req)
    ccall((:slurm_reset_statistics,libslurm),Cint,(Ptr{stats_info_request_msg_t},),req)
end

function slurm_job_cpus_allocated_on_node_id(job_resrcs_ptr,node_id::Cint)
    ccall((:slurm_job_cpus_allocated_on_node_id,libslurm),Cint,(Ptr{job_resources_t},Cint),job_resrcs_ptr,node_id)
end

function slurm_job_cpus_allocated_on_node(job_resrcs_ptr,node_name)
    ccall((:slurm_job_cpus_allocated_on_node,libslurm),Cint,(Ptr{job_resources_t},Cstring),job_resrcs_ptr,node_name)
end

function slurm_job_cpus_allocated_str_on_node_id(cpus,cpus_len::Cint,job_resrcs_ptr,node_id::Cint)
    ccall((:slurm_job_cpus_allocated_str_on_node_id,libslurm),Cint,(Cstring,Cint,Ptr{job_resources_t},Cint),cpus,cpus_len,job_resrcs_ptr,node_id)
end

function slurm_job_cpus_allocated_str_on_node(cpus,cpus_len::Cint,job_resrcs_ptr,node_name)
    ccall((:slurm_job_cpus_allocated_str_on_node,libslurm),Cint,(Cstring,Cint,Ptr{job_resources_t},Cstring),cpus,cpus_len,job_resrcs_ptr,node_name)
end

function slurm_free_job_info_msg(job_buffer_ptr)
    ccall((:slurm_free_job_info_msg,libslurm),Void,(Ptr{job_info_msg_t},),job_buffer_ptr)
end

function slurm_get_end_time(jobid::UInt32,end_time_ptr)
    ccall((:slurm_get_end_time,libslurm),Cint,(UInt32,Ptr{time_t}),jobid,end_time_ptr)
end

function slurm_get_job_stderr(buf,buf_size::Cint,job_ptr)
    ccall((:slurm_get_job_stderr,libslurm),Void,(Cstring,Cint,Ptr{job_info_t}),buf,buf_size,job_ptr)
end

function slurm_get_job_stdin(buf,buf_size::Cint,job_ptr)
    ccall((:slurm_get_job_stdin,libslurm),Void,(Cstring,Cint,Ptr{job_info_t}),buf,buf_size,job_ptr)
end

function slurm_get_job_stdout(buf,buf_size::Cint,job_ptr)
    ccall((:slurm_get_job_stdout,libslurm),Void,(Cstring,Cint,Ptr{job_info_t}),buf,buf_size,job_ptr)
end

function slurm_get_rem_time(jobid::UInt32)
    ccall((:slurm_get_rem_time,libslurm),Clong,(UInt32,),jobid)
end

function slurm_job_node_ready(job_id::UInt32)
    ccall((:slurm_job_node_ready,libslurm),Cint,(UInt32,),job_id)
end

function slurm_load_job(resp,job_id::UInt32,show_flags::UInt16)
    ccall((:slurm_load_job,libslurm),Cint,(Ptr{Ptr{job_info_msg_t}},UInt32,UInt16),resp,job_id,show_flags)
end

function slurm_load_job_user(job_info_msg_pptr,user_id::UInt32,show_flags::UInt16)
    ccall((:slurm_load_job_user,libslurm),Cint,(Ptr{Ptr{job_info_msg_t}},UInt32,UInt16),job_info_msg_pptr,user_id,show_flags)
end

function slurm_load_jobs(update_time::time_t,job_info_msg_pptr,show_flags::UInt16)
    ccall((:slurm_load_jobs,libslurm),Cint,(time_t,Ptr{Ptr{job_info_msg_t}},UInt16),update_time,job_info_msg_pptr,show_flags)
end

function slurm_notify_job(job_id::UInt32,message)
    ccall((:slurm_notify_job,libslurm),Cint,(UInt32,Cstring),job_id,message)
end

function slurm_pid2jobid(job_pid::pid_t,job_id_ptr)
    ccall((:slurm_pid2jobid,libslurm),Cint,(pid_t,Ptr{UInt32}),job_pid,job_id_ptr)
end

function slurm_print_job_info(out,job_ptr,one_liner::Cint)
    ccall((:slurm_print_job_info,libslurm),Void,(Ptr{FILE},Ptr{slurm_job_info_t},Cint),out,job_ptr,one_liner)
end

function slurm_print_job_info_msg(out,job_info_msg_ptr,one_liner::Cint)
    ccall((:slurm_print_job_info_msg,libslurm),Void,(Ptr{FILE},Ptr{job_info_msg_t},Cint),out,job_info_msg_ptr,one_liner)
end

function slurm_sprint_job_info(job_ptr,one_liner::Cint)
    ccall((:slurm_sprint_job_info,libslurm),Cstring,(Ptr{slurm_job_info_t},Cint),job_ptr,one_liner)
end

function slurm_update_job(job_msg)
    ccall((:slurm_update_job,libslurm),Cint,(Ptr{job_desc_msg_t},),job_msg)
end

function slurm_update_job2(job_msg,resp)
    ccall((:slurm_update_job2,libslurm),Cint,(Ptr{job_desc_msg_t},Ptr{Ptr{job_array_resp_msg_t}}),job_msg,resp)
end

function slurm_xlate_job_id(job_id_str)
    ccall((:slurm_xlate_job_id,libslurm),UInt32,(Cstring,),job_id_str)
end

function slurm_get_job_steps(update_time::time_t,job_id::UInt32,step_id::UInt32,step_response_pptr,show_flags::UInt16)
    ccall((:slurm_get_job_steps,libslurm),Cint,(time_t,UInt32,UInt32,Ptr{Ptr{job_step_info_response_msg_t}},UInt16),update_time,job_id,step_id,step_response_pptr,show_flags)
end

function slurm_free_job_step_info_response_msg(msg)
    ccall((:slurm_free_job_step_info_response_msg,libslurm),Void,(Ptr{job_step_info_response_msg_t},),msg)
end

function slurm_print_job_step_info_msg(out,job_step_info_msg_ptr,one_liner::Cint)
    ccall((:slurm_print_job_step_info_msg,libslurm),Void,(Ptr{FILE},Ptr{job_step_info_response_msg_t},Cint),out,job_step_info_msg_ptr,one_liner)
end

function slurm_print_job_step_info(out,step_ptr,one_liner::Cint)
    ccall((:slurm_print_job_step_info,libslurm),Void,(Ptr{FILE},Ptr{job_step_info_t},Cint),out,step_ptr,one_liner)
end

function slurm_job_step_layout_get(job_id::UInt32,step_id::UInt32)
    ccall((:slurm_job_step_layout_get,libslurm),Ptr{slurm_step_layout_t},(UInt32,UInt32),job_id,step_id)
end

function slurm_sprint_job_step_info(step_ptr,one_liner::Cint)
    ccall((:slurm_sprint_job_step_info,libslurm),Cstring,(Ptr{job_step_info_t},Cint),step_ptr,one_liner)
end

function slurm_job_step_stat(job_id::UInt32,step_id::UInt32,node_list,use_protocol_ver::UInt16,resp)
    ccall((:slurm_job_step_stat,libslurm),Cint,(UInt32,UInt32,Cstring,UInt16,Ptr{Ptr{job_step_stat_response_msg_t}}),job_id,step_id,node_list,use_protocol_ver,resp)
end

function slurm_job_step_get_pids(job_id::UInt32,step_id::UInt32,node_list,resp)
    ccall((:slurm_job_step_get_pids,libslurm),Cint,(UInt32,UInt32,Cstring,Ptr{Ptr{job_step_pids_response_msg_t}}),job_id,step_id,node_list,resp)
end

function slurm_job_step_layout_free(layout)
    ccall((:slurm_job_step_layout_free,libslurm),Void,(Ptr{slurm_step_layout_t},),layout)
end

function slurm_job_step_pids_free(object)
    ccall((:slurm_job_step_pids_free,libslurm),Void,(Ptr{job_step_pids_t},),object)
end

function slurm_job_step_pids_response_msg_free(object)
    ccall((:slurm_job_step_pids_response_msg_free,libslurm),Void,(Ptr{Void},),object)
end

function slurm_job_step_stat_free(object)
    ccall((:slurm_job_step_stat_free,libslurm),Void,(Ptr{job_step_stat_t},),object)
end

function slurm_job_step_stat_response_msg_free(object)
    ccall((:slurm_job_step_stat_response_msg_free,libslurm),Void,(Ptr{Void},),object)
end

function slurm_update_step(step_msg)
    ccall((:slurm_update_step,libslurm),Cint,(Ptr{step_update_request_msg_t},),step_msg)
end

function slurm_load_node(update_time::time_t,resp,show_flags::UInt16)
    ccall((:slurm_load_node,libslurm),Cint,(time_t,Ptr{Ptr{node_info_msg_t}},UInt16),update_time,resp,show_flags)
end

function slurm_load_node_single(resp,node_name,show_flags::UInt16)
    ccall((:slurm_load_node_single,libslurm),Cint,(Ptr{Ptr{node_info_msg_t}},Cstring,UInt16),resp,node_name,show_flags)
end

function slurm_get_node_energy(host,delta::UInt16,sensors_cnt,energy)
    ccall((:slurm_get_node_energy,libslurm),Cint,(Cstring,UInt16,Ptr{UInt16},Ptr{Ptr{acct_gather_energy_t}}),host,delta,sensors_cnt,energy)
end

function slurm_free_node_info_msg(node_buffer_ptr)
    ccall((:slurm_free_node_info_msg,libslurm),Void,(Ptr{node_info_msg_t},),node_buffer_ptr)
end

function slurm_print_node_info_msg(out,node_info_msg_ptr,one_liner::Cint)
    ccall((:slurm_print_node_info_msg,libslurm),Void,(Ptr{FILE},Ptr{node_info_msg_t},Cint),out,node_info_msg_ptr,one_liner)
end

function slurm_print_node_table(out,node_ptr,node_scaling::Cint,one_liner::Cint)
    ccall((:slurm_print_node_table,libslurm),Void,(Ptr{FILE},Ptr{node_info_t},Cint,Cint),out,node_ptr,node_scaling,one_liner)
end

function slurm_sprint_node_table(node_ptr,node_scaling::Cint,one_liner::Cint)
    ccall((:slurm_sprint_node_table,libslurm),Cstring,(Ptr{node_info_t},Cint,Cint),node_ptr,node_scaling,one_liner)
end

function slurm_init_update_node_msg(update_node_msg)
    ccall((:slurm_init_update_node_msg,libslurm),Void,(Ptr{update_node_msg_t},),update_node_msg)
end

function slurm_update_node(node_msg)
    ccall((:slurm_update_node,libslurm),Cint,(Ptr{update_node_msg_t},),node_msg)
end

function slurm_load_front_end(update_time::time_t,resp)
    ccall((:slurm_load_front_end,libslurm),Cint,(time_t,Ptr{Ptr{front_end_info_msg_t}}),update_time,resp)
end

function slurm_free_front_end_info_msg(front_end_buffer_ptr)
    ccall((:slurm_free_front_end_info_msg,libslurm),Void,(Ptr{front_end_info_msg_t},),front_end_buffer_ptr)
end

function slurm_print_front_end_info_msg(out,front_end_info_msg_ptr,one_liner::Cint)
    ccall((:slurm_print_front_end_info_msg,libslurm),Void,(Ptr{FILE},Ptr{front_end_info_msg_t},Cint),out,front_end_info_msg_ptr,one_liner)
end

function slurm_print_front_end_table(out,front_end_ptr,one_liner::Cint)
    ccall((:slurm_print_front_end_table,libslurm),Void,(Ptr{FILE},Ptr{front_end_info_t},Cint),out,front_end_ptr,one_liner)
end

function slurm_sprint_front_end_table(front_end_ptr,one_liner::Cint)
    ccall((:slurm_sprint_front_end_table,libslurm),Cstring,(Ptr{front_end_info_t},Cint),front_end_ptr,one_liner)
end

function slurm_init_update_front_end_msg(update_front_end_msg)
    ccall((:slurm_init_update_front_end_msg,libslurm),Void,(Ptr{update_front_end_msg_t},),update_front_end_msg)
end

function slurm_update_front_end(front_end_msg)
    ccall((:slurm_update_front_end,libslurm),Cint,(Ptr{update_front_end_msg_t},),front_end_msg)
end

function slurm_load_topo(topo_info_msg_pptr)
    ccall((:slurm_load_topo,libslurm),Cint,(Ptr{Ptr{topo_info_response_msg_t}},),topo_info_msg_pptr)
end

function slurm_free_topo_info_msg(msg)
    ccall((:slurm_free_topo_info_msg,libslurm),Void,(Ptr{topo_info_response_msg_t},),msg)
end

function slurm_print_topo_info_msg(out,topo_info_msg_ptr,one_liner::Cint)
    ccall((:slurm_print_topo_info_msg,libslurm),Void,(Ptr{FILE},Ptr{topo_info_response_msg_t},Cint),out,topo_info_msg_ptr,one_liner)
end

function slurm_print_topo_record(out,topo_ptr,one_liner::Cint)
    ccall((:slurm_print_topo_record,libslurm),Void,(Ptr{FILE},Ptr{topo_info_t},Cint),out,topo_ptr,one_liner)
end

function slurm_load_powercap(powercap_info_msg_pptr)
    ccall((:slurm_load_powercap,libslurm),Cint,(Ptr{Ptr{powercap_info_msg_t}},),powercap_info_msg_pptr)
end

function slurm_free_powercap_info_msg(msg)
    ccall((:slurm_free_powercap_info_msg,libslurm),Void,(Ptr{powercap_info_msg_t},),msg)
end

function slurm_print_powercap_info_msg(out,powercap_info_msg_ptr,one_liner::Cint)
    ccall((:slurm_print_powercap_info_msg,libslurm),Void,(Ptr{FILE},Ptr{powercap_info_msg_t},Cint),out,powercap_info_msg_ptr,one_liner)
end

function slurm_update_powercap(powercap_msg)
    ccall((:slurm_update_powercap,libslurm),Cint,(Ptr{update_powercap_msg_t},),powercap_msg)
end

function slurm_get_select_jobinfo(jobinfo,data_type::select_jobdata_type,data)
    ccall((:slurm_get_select_jobinfo,libslurm),Cint,(Ptr{dynamic_plugin_data_t},select_jobdata_type,Ptr{Void}),jobinfo,data_type,data)
end

function slurm_get_select_nodeinfo(nodeinfo,data_type::select_nodedata_type,state::node_states,data)
    ccall((:slurm_get_select_nodeinfo,libslurm),Cint,(Ptr{dynamic_plugin_data_t},select_nodedata_type,node_states,Ptr{Void}),nodeinfo,data_type,state,data)
end

function slurm_init_part_desc_msg(update_part_msg)
    ccall((:slurm_init_part_desc_msg,libslurm),Void,(Ptr{update_part_msg_t},),update_part_msg)
end

function slurm_load_partitions(update_time::time_t,part_buffer_ptr,show_flags::UInt16)
    ccall((:slurm_load_partitions,libslurm),Cint,(time_t,Ptr{Ptr{partition_info_msg_t}},UInt16),update_time,part_buffer_ptr,show_flags)
end

function slurm_free_partition_info_msg(part_info_ptr)
    ccall((:slurm_free_partition_info_msg,libslurm),Void,(Ptr{partition_info_msg_t},),part_info_ptr)
end

function slurm_print_partition_info_msg(out,part_info_ptr,one_liner::Cint)
    ccall((:slurm_print_partition_info_msg,libslurm),Void,(Ptr{FILE},Ptr{partition_info_msg_t},Cint),out,part_info_ptr,one_liner)
end

function slurm_print_partition_info(out,part_ptr,one_liner::Cint)
    ccall((:slurm_print_partition_info,libslurm),Void,(Ptr{FILE},Ptr{partition_info_t},Cint),out,part_ptr,one_liner)
end

function slurm_sprint_partition_info(part_ptr,one_liner::Cint)
    ccall((:slurm_sprint_partition_info,libslurm),Cstring,(Ptr{partition_info_t},Cint),part_ptr,one_liner)
end

function slurm_create_partition(part_msg)
    ccall((:slurm_create_partition,libslurm),Cint,(Ptr{update_part_msg_t},),part_msg)
end

function slurm_update_partition(part_msg)
    ccall((:slurm_update_partition,libslurm),Cint,(Ptr{update_part_msg_t},),part_msg)
end

function slurm_delete_partition(part_msg)
    ccall((:slurm_delete_partition,libslurm),Cint,(Ptr{delete_part_msg_t},),part_msg)
end

function slurm_print_layout_info(out,layout_info_ptr,one_liner::Cint)
    ccall((:slurm_print_layout_info,libslurm),Void,(Ptr{FILE},Ptr{layout_info_msg_t},Cint),out,layout_info_ptr,one_liner)
end

function slurm_load_layout(layout_type,entities,_type,no_relation::UInt32,resp)
    ccall((:slurm_load_layout,libslurm),Cint,(Cstring,Cstring,Cstring,UInt32,Ptr{Ptr{layout_info_msg_t}}),layout_type,entities,_type,no_relation,resp)
end

function slurm_update_layout(layout_info_msg)
    ccall((:slurm_update_layout,libslurm),Cint,(Ptr{update_layout_msg_t},),layout_info_msg)
end

function slurm_free_layout_info_msg(layout_info_msg)
    ccall((:slurm_free_layout_info_msg,libslurm),Void,(Ptr{layout_info_msg_t},),layout_info_msg)
end

function slurm_init_resv_desc_msg(update_resv_msg)
    ccall((:slurm_init_resv_desc_msg,libslurm),Void,(Ptr{resv_desc_msg_t},),update_resv_msg)
end

function slurm_create_reservation(resv_msg)
    ccall((:slurm_create_reservation,libslurm),Cstring,(Ptr{resv_desc_msg_t},),resv_msg)
end

function slurm_update_reservation(resv_msg)
    ccall((:slurm_update_reservation,libslurm),Cint,(Ptr{resv_desc_msg_t},),resv_msg)
end

function slurm_delete_reservation(resv_msg)
    ccall((:slurm_delete_reservation,libslurm),Cint,(Ptr{reservation_name_msg_t},),resv_msg)
end

function slurm_load_reservations(update_time::time_t,resp)
    ccall((:slurm_load_reservations,libslurm),Cint,(time_t,Ptr{Ptr{reserve_info_msg_t}}),update_time,resp)
end

function slurm_print_reservation_info_msg(out,resv_info_ptr,one_liner::Cint)
    ccall((:slurm_print_reservation_info_msg,libslurm),Void,(Ptr{FILE},Ptr{reserve_info_msg_t},Cint),out,resv_info_ptr,one_liner)
end

function slurm_print_reservation_info(out,resv_ptr,one_liner::Cint)
    ccall((:slurm_print_reservation_info,libslurm),Void,(Ptr{FILE},Ptr{reserve_info_t},Cint),out,resv_ptr,one_liner)
end

function slurm_sprint_reservation_info(resv_ptr,one_liner::Cint)
    ccall((:slurm_sprint_reservation_info,libslurm),Cstring,(Ptr{reserve_info_t},Cint),resv_ptr,one_liner)
end

function slurm_free_reservation_info_msg(resv_info_ptr)
    ccall((:slurm_free_reservation_info_msg,libslurm),Void,(Ptr{reserve_info_msg_t},),resv_info_ptr)
end

function slurm_ping(primary::Cint)
    ccall((:slurm_ping,libslurm),Cint,(Cint,),primary)
end

function slurm_reconfigure()
    ccall((:slurm_reconfigure,libslurm),Cint,())
end

function slurm_shutdown(options::UInt16)
    ccall((:slurm_shutdown,libslurm),Cint,(UInt16,),options)
end

function slurm_takeover()
    ccall((:slurm_takeover,libslurm),Cint,())
end

function slurm_set_debugflags(debug_flags_plus::UInt64,debug_flags_minus::UInt64)
    ccall((:slurm_set_debugflags,libslurm),Cint,(UInt64,UInt64),debug_flags_plus,debug_flags_minus)
end

function slurm_set_debug_level(debug_level::UInt32)
    ccall((:slurm_set_debug_level,libslurm),Cint,(UInt32,),debug_level)
end

function slurm_set_schedlog_level(schedlog_level::UInt32)
    ccall((:slurm_set_schedlog_level,libslurm),Cint,(UInt32,),schedlog_level)
end

function slurm_suspend(job_id::UInt32)
    ccall((:slurm_suspend,libslurm),Cint,(UInt32,),job_id)
end

function slurm_suspend2(job_id,resp)
    ccall((:slurm_suspend2,libslurm),Cint,(Cstring,Ptr{Ptr{job_array_resp_msg_t}}),job_id,resp)
end

function slurm_resume(job_id::UInt32)
    ccall((:slurm_resume,libslurm),Cint,(UInt32,),job_id)
end

function slurm_resume2(job_id,resp)
    ccall((:slurm_resume2,libslurm),Cint,(Cstring,Ptr{Ptr{job_array_resp_msg_t}}),job_id,resp)
end

function slurm_free_job_array_resp(resp)
    ccall((:slurm_free_job_array_resp,libslurm),Void,(Ptr{job_array_resp_msg_t},),resp)
end

function slurm_requeue(job_id::UInt32,state::UInt32)
    ccall((:slurm_requeue,libslurm),Cint,(UInt32,UInt32),job_id,state)
end

function slurm_requeue2(job_id,state::UInt32,resp)
    ccall((:slurm_requeue2,libslurm),Cint,(Cstring,UInt32,Ptr{Ptr{job_array_resp_msg_t}}),job_id,state,resp)
end

function slurm_checkpoint_able(job_id::UInt32,step_id::UInt32,start_time)
    ccall((:slurm_checkpoint_able,libslurm),Cint,(UInt32,UInt32,Ptr{time_t}),job_id,step_id,start_time)
end

function slurm_checkpoint_disable(job_id::UInt32,step_id::UInt32)
    ccall((:slurm_checkpoint_disable,libslurm),Cint,(UInt32,UInt32),job_id,step_id)
end

function slurm_checkpoint_enable(job_id::UInt32,step_id::UInt32)
    ccall((:slurm_checkpoint_enable,libslurm),Cint,(UInt32,UInt32),job_id,step_id)
end

function slurm_checkpoint_create(job_id::UInt32,step_id::UInt32,max_wait::UInt16,image_dir)
    ccall((:slurm_checkpoint_create,libslurm),Cint,(UInt32,UInt32,UInt16,Cstring),job_id,step_id,max_wait,image_dir)
end

function slurm_checkpoint_requeue(job_id::UInt32,max_wait::UInt16,image_dir)
    ccall((:slurm_checkpoint_requeue,libslurm),Cint,(UInt32,UInt16,Cstring),job_id,max_wait,image_dir)
end

function slurm_checkpoint_vacate(job_id::UInt32,step_id::UInt32,max_wait::UInt16,image_dir)
    ccall((:slurm_checkpoint_vacate,libslurm),Cint,(UInt32,UInt32,UInt16,Cstring),job_id,step_id,max_wait,image_dir)
end

function slurm_checkpoint_restart(job_id::UInt32,step_id::UInt32,stick::UInt16,image_dir)
    ccall((:slurm_checkpoint_restart,libslurm),Cint,(UInt32,UInt32,UInt16,Cstring),job_id,step_id,stick,image_dir)
end

function slurm_checkpoint_complete(job_id::UInt32,step_id::UInt32,begin_time::time_t,error_code::UInt32,error_msg)
    ccall((:slurm_checkpoint_complete,libslurm),Cint,(UInt32,UInt32,time_t,UInt32,Cstring),job_id,step_id,begin_time,error_code,error_msg)
end

function slurm_checkpoint_task_complete(job_id::UInt32,step_id::UInt32,task_id::UInt32,begin_time::time_t,error_code::UInt32,error_msg)
    ccall((:slurm_checkpoint_task_complete,libslurm),Cint,(UInt32,UInt32,UInt32,time_t,UInt32,Cstring),job_id,step_id,task_id,begin_time,error_code,error_msg)
end

function slurm_checkpoint_error(job_id::UInt32,step_id::UInt32,error_code,error_msg)
    ccall((:slurm_checkpoint_error,libslurm),Cint,(UInt32,UInt32,Ptr{UInt32},Ptr{Cstring}),job_id,step_id,error_code,error_msg)
end

function slurm_checkpoint_tasks(job_id::UInt32,step_id::UInt16,begin_time::time_t,image_dir,max_wait::UInt16,nodelist)
    ccall((:slurm_checkpoint_tasks,libslurm),Cint,(UInt32,UInt16,time_t,Cstring,UInt16,Cstring),job_id,step_id,begin_time,image_dir,max_wait,nodelist)
end

function slurm_set_trigger(trigger_set)
    ccall((:slurm_set_trigger,libslurm),Cint,(Ptr{trigger_info_t},),trigger_set)
end

function slurm_clear_trigger(trigger_clear)
    ccall((:slurm_clear_trigger,libslurm),Cint,(Ptr{trigger_info_t},),trigger_clear)
end

function slurm_get_triggers(trigger_get)
    ccall((:slurm_get_triggers,libslurm),Cint,(Ptr{Ptr{trigger_info_msg_t}},),trigger_get)
end

function slurm_pull_trigger(trigger_pull)
    ccall((:slurm_pull_trigger,libslurm),Cint,(Ptr{trigger_info_t},),trigger_pull)
end

function slurm_free_trigger_msg(trigger_free)
    ccall((:slurm_free_trigger_msg,libslurm),Void,(Ptr{trigger_info_msg_t},),trigger_free)
end

function slurm_init_trigger_msg(trigger_info_msg)
    ccall((:slurm_init_trigger_msg,libslurm),Void,(Ptr{trigger_info_t},),trigger_info_msg)
end

function slurm_burst_buffer_state_string(state::UInt16)
    ccall((:slurm_burst_buffer_state_string,libslurm),Cstring,(UInt16,),state)
end

function slurm_load_burst_buffer_info(burst_buffer_info_msg_pptr)
    ccall((:slurm_load_burst_buffer_info,libslurm),Cint,(Ptr{Ptr{burst_buffer_info_msg_t}},),burst_buffer_info_msg_pptr)
end

function slurm_free_burst_buffer_info_msg(burst_buffer_info_msg)
    ccall((:slurm_free_burst_buffer_info_msg,libslurm),Void,(Ptr{burst_buffer_info_msg_t},),burst_buffer_info_msg)
end

function slurm_print_burst_buffer_info_msg(out,info_ptr,one_liner::Cint,verbosity::Cint)
    ccall((:slurm_print_burst_buffer_info_msg,libslurm),Void,(Ptr{FILE},Ptr{burst_buffer_info_msg_t},Cint,Cint),out,info_ptr,one_liner,verbosity)
end

function slurm_print_burst_buffer_record(out,burst_buffer_ptr,one_liner::Cint,verbose::Cint)
    ccall((:slurm_print_burst_buffer_record,libslurm),Void,(Ptr{FILE},Ptr{burst_buffer_info_t},Cint,Cint),out,burst_buffer_ptr,one_liner,verbose)
end

function slurm_network_callerid(req::network_callerid_msg_t,job_id,node_name,node_name_size::Cint)
    ccall((:slurm_network_callerid,libslurm),Cint,(network_callerid_msg_t,Ptr{UInt32},Cstring,Cint),req,job_id,node_name,node_name_size)
end

function slurm_top_job(job_id_str)
    ccall((:slurm_top_job,libslurm),Cint,(Cstring,),job_id_str)
end


text:
using Xpress, Compat.Test
using Compat.SparseArrays
using Compat.LinearAlgebra

tests = ["xprs_attrs_test",
         "lp_01a",
         "lp_01b",
         "lp_02",
         "lp_03",
         "lp_04",
         "mip_01",
         "qp_01",
         "qp_02",
         "qcqp_01",
         "iis",
         "mathprog",
         "MOIWrapper",
        #  "wordhunt"
         ]

if VERSION < v"0.7.0"
    push!(tests, "jump")
end

for t in tests
    fp = "$(t).jl"
    println("running $(fp) ...")
    evalfile(fp)
end


text:
require("../../src/BlackBoxOptim.jl")
require("../covar_matrix_self_adaptation_es.jl")
require("../experiment_framework.jl")
require("../../src/experiments/parameter_experiment.jl")

using BlackBoxOptim

for(dim in [2,4,8,16,32,64])

  n = dim
  p = BlackBoxOptim.as_fixed_dim_problem(BlackBoxOptim.example_problems["Sphere"], n)
  p = BlackBoxOptim.shifted(p)
  diameter = minimum(diameters(search_space(p)))

  pe = ParameterExperiment(
  ["lambda", "mu", "sigma", "decompose_covar_prob",
   "max_successes_before_increasing", "max_failures_before_decreasing",
   "max_rounds_without_improvement", "tau_c"
  ],
  [((ds, ps) -> int(10^ds[1])),
   ((ds, ps) -> int(max(1.0, ds[2]*ps[1]))),
   ((ds, ps) -> diameter * 10^ds[3]),
   ((ds, ps) -> ds[4]),
   ((ds, ps) -> int(ds[5])),
   ((ds, ps) -> int(ds[6])),
   ((ds, ps) -> int(10^ds[7])),
   ((ds, ps) -> 1 + n * (n+1) / (ds[8]*ps[2]))
  ],
  [( log10(4.0 + log(n)), log10(4*n*n)),
   ( 1/50, 1/2),
   (-3.0, 0.0),
   (0.01, 0.99),
   (-1000.0, 1000.0), # Inactive if less than 1
   (-1000.0, 1000.0), # Inactive if less than 1
   (1.0, 4.0),
   (0.01, 100.0)
  ]
 )

 # Do when with fewer repeats just to test things...
 explore_parameters(pe, cmsa_es, p; experiment_prefix = "cmsa_es", num_repeats = 10)

end


text:
"""
    VectorTuple{T, I <: Tuple}

A collection DataType for storing a `Tuple` of singular elements of type `T`
and/or `AbstractArray{<:T}`s in a convenient vector form that utilizes
linear indexing. Here `I` is denotes the type of a `Tuple` that stores the
indices of each tuple element as given by `indices`. `VectorTuple`s should be
defined from an original tuple via `VectorTuple(tuple)` or by listing the tuple
elements `VectorTuple(items...)`. Note this is still an experimental type and is
primarily intended to store infinite parameter reference tuples and point
variable support value tuples. Some of the notable capabilities are exemplified
below.

**Example**
```julia-repl
julia> tuple = (3, [-2, 4], ones(2, 2))
(3, [-2, 4], [1.0 1.0; 1.0 1.0])

julia> vt = VectorTuple(tuple) # make by listing items (notice everything is a vector)
([3.0], [3.0, 4.0], [1.0, 1.0, 1.0, 1.0])

julia> vt[2] # linear indexing
-2.0

julia> vt[2, 2] # tuple indexing (note the second index is treated linearly)
4.0

julia> vt[6:end] # linear slicing
2-element Array{Float64,1}:
 1.0
 1.0

julia> vt[2:3, :] # tuple slicing
2-element Array{Array{Float64,1},1}:
 [-2.0, 4.0]
 [1.0, 1.0, 1.0, 1.0]

julia> tuple2 = Tuple(vt) # rebuild original Tuple with original indices
([3.0], [-2.0, 4.0], [1.0 1.0; 1.0 1.0])

julia> inds = [true, true, true, false, true, true, true];

julia> restricted_copy(vt, delete_locs) # make a copy with deleted elements
([3.0], [-2.0, 4.0], [1.0, 1.0, 1.0])

julia> Tuple(vt) # The 3rd element becomes a SparseAxisArray because of deletion
([3.0], [-2.0, 4.0],   [1, 2]  =  1.0
  [2, 2]  =  1.0
  [2, 1]  =  1.0)
```
"""
struct VectorTuple{T, I <: Tuple}
    values::Vector{T}
    ranges::Vector{UnitRange{Int}}
    indices::I
end

## Order arrays by index if necessary (to take care of SparseAxisArrays)
# SparseAxisArray
function _make_ordered(arr::JuMPC.SparseAxisArray{T}, inds)::Vector{T} where {T}
    return vectorize(arr, inds)
end

# other
_make_ordered(arr, indices) = arr

# internal function for constructor
function _make_vt_components(tuple::Tuple)
    # form the range vector
    ranges = Vector{UnitRange{Int}}(undef, length(tuple))
    for i in eachindex(ranges)
        element_length = length(tuple[i])
        if i === 1
            ranges[i] = UnitRange(1, element_length)
        else
            ranges[i] = UnitRange(ranges[i-1].stop + 1, ranges[i-1].stop + element_length)
        end
    end
    # get the indices
    inds = Tuple(indices(t) for t in tuple)
    # prepare the values vector
    vals = [j for i in eachindex(tuple) for j in _make_ordered(tuple[i], inds[i])]
    # return everything
    return vals, ranges, inds
end

# Constructor from a Tuple without type
function VectorTuple(tuple::Tuple)
    vals, ranges, indices = _make_vt_components(tuple)
    return VectorTuple(vals, ranges, indices)
end

# Constructor from various arguments (like splatting the tuple) without type
function VectorTuple(items...)
    return VectorTuple(items)
end

# Extend Base.:(==)
function Base.:(==)(vt1::VectorTuple, vt2::VectorTuple)::Bool
    return all(getproperty(vt1, f) == getproperty(vt2, f) for f in fieldnames(VectorTuple))
end

# Extend Base.size
function Base.size(vt::VectorTuple, d::Int)::Int
    d > 1 && throw(ArgumentError("invalid VectorTuple dimension $d"))
    return length(vt.ranges)
end

# Determine if 2 VectorTuples have the same structure
function same_structure(vt1::VectorTuple, vt2::VectorTuple;
                        use_indices = true)::Bool
    same_size = vt1.ranges == vt2.ranges
    return same_size && (!use_indices || (vt1.indices == vt2.indices))
end

# Extend Base.copy
function Base.copy(vt::VectorTuple)
    return VectorTuple(copy(vt.values), copy(vt.ranges), vt.indices)
end

## Extend first and last indices
# Base.firstindex (linear)
Base.firstindex(vt::VectorTuple)::Int = firstindex(vt.values)

# Base.firstindex (tuple)
Base.firstindex(vt::VectorTuple, d::Int)::Int = 1

# Base.lastindex (linear)
Base.lastindex(vt::VectorTuple)::Int = lastindex(vt.values)

# Base.lastindex (tuple)
function Base.lastindex(vt::VectorTuple, d::Int)::Int
    return d == 1 ? size(vt, 1) : throw(ArgumentError("lastindex(::VectorTuple, " *
                                                      "d::Int > 1) not defined."))
end

## Extend Base.getindex
# linear index along vector
Base.getindex(vt::VectorTuple, i) = getindex(vt.values, i)

# Tuple indexing (single position)
function Base.getindex(vt::VectorTuple, i::Int, j)
    return getindex(vt.values[vt.ranges[i]], j)
end

# Tuple indexing (with a colon)
function Base.getindex(vt::VectorTuple, i::Colon, j)
    return [getindex(vt, i, j) for i = 1:size(vt, 1)]
end

# Tuple indexing (with an iterable) --> assumed backup
function Base.getindex(vt::VectorTuple, is, j)
    return [getindex(vt, i, j) for i in is]
end

## Extend Base.setindex!
# linear index along vector
function Base.setindex!(vt::VectorTuple, v, i)
    return setindex!(vt.values, v, i)
end

# Tuple indexing (with integer i and colon j)
function Base.setindex!(vt::VectorTuple, v, i::Int, j::Colon)
    return setindex!(vt.values, v, vt.ranges[i])
end

# Tuple indexing (with integer i and any non colon j)
function Base.setindex!(vt::VectorTuple, v, i::Int, j)
    linear_index = (vt.ranges[i].start - 1) .+ j
    if any(linear_index .> vt.ranges[i].stop)
        throw(BoundsError(vt, [i, j]))
    end
    return setindex!(vt.values, v, linear_index)
end

# Tuple indexing (with colon i and integer j)
function Base.setindex!(vt::VectorTuple, v, i::Colon, j::Int)
    linear_indexes = [vt.ranges[k].start - 1 + j for k in eachindex(vt.ranges)]
    return setindex!(vt.values, v, linear_indexes)
end

# Tuple indexing (with colon i and noninteger j)
function Base.setindex!(vt::VectorTuple, v, i::Colon, j)
    return setindex!(vt, v, 1:size(vt, 1), j)
end

# Tuple indexing (with array i and any j)
function Base.setindex!(vt::VectorTuple, v, i, j)
    @assert length(v) == length(i)
    return [setindex!(vt, v[k], i[k], j) for k in 1:length(i)]
end

# Extend simple Base redirect methods with VectorTuple arguments
for op = (:length, :isempty, :eachindex, :keys)
    @eval Base.$op(vt::VectorTuple) = $op(vt.values)
end

# Extend simple Base 2 argument methods
for op = (:findfirst, :findall)
    @eval Base.$op(f::Function, vt::VectorTuple) = $op(f, vt.values)
end

# Extend Base.in
Base.in(i, vt::VectorTuple)::Bool = in(i, vt.values)

# Extend Base.iterate
Base.iterate(vt::VectorTuple) = iterate(vt.values)
Base.iterate(vt::VectorTuple, i) = iterate(vt.values, i)

## Update the indices if an element is deleted
# SparseAxisArray
function _update_indices(inds::ContainerIndices{1, <:Vector}, i)
    new_axes = deleteat!(copy(inds.axes), i)
    cart_inds = CartesianIndices(new_axes)
    return length(new_axes) >= 2 ? ContainerIndices(cart_inds, new_axes) : nothing
end

# DenseAxisArray
function _update_indices(inds::ContainerIndices, i)
    new_axes = reduce(vcat, Base.Iterators.product(inds.axes...))
    new_inds = ContainerIndices(CartesianIndices(new_axes), new_axes)
    return _update_indices(new_inds, i) # call the SparseAxisArray version
end

# Array
function _update_indices(inds::ContainerIndices{N, Nothing}, i) where {N}
    new_axes = [Tuple(inds.indices[k]) for k in 1:length(inds.indices)]
    new_inds = ContainerIndices(CartesianIndices(new_axes), new_axes)
    return _update_indices(new_inds, i) # call the SparseAxisArray version
end

# Make a restricted copy (a copy with deleted elements)
function restricted_copy(vt::VectorTuple, inds::AbstractVector{<:Bool})
    # get the new values
    new_values = vt.values[inds]
    # process the new ranges and indices
    inv_inds = .!inds
    prev_sum = 0
    delete_inds = Int[]
    new_ranges = copy(vt.ranges)
    new_indices = collect(vt.indices)
    for i in eachindex(new_ranges)
        delete_sum = sum(inv_inds[new_ranges[i]])
        if length(new_ranges[i]) == delete_sum
            push!(delete_inds, i)
        else
            group_inds = new_ranges[i][inv_inds[new_ranges[i]]] .+ (1 - new_ranges[i].start)
            if length(group_inds) != 0
                new_indices[i] = _update_indices(new_indices[i], group_inds)
            end
            new_ranges[i] = UnitRange(new_ranges[i].start - prev_sum,
                                      new_ranges[i].stop - prev_sum - delete_sum)
        end
        prev_sum += delete_sum
    end
    deleteat!(new_ranges, delete_inds)
    deleteat!(new_indices, delete_inds)
    # make the new VectorTuple and return
    return VectorTuple(new_values, new_ranges, Tuple(i for i in new_indices))
end

## Make the original array for a particular tuple element
# AbstractArray
function _make_array(vals::Vector, inds::ContainerIndices)
    return unvectorize(vals, inds)
end

# Other
function _make_array(vals::Vector, inds::Nothing)
    return length(vals) == 1 ? first(vals) : vals
end

# Define Tuple construction from a VectorTuple
function Base.Tuple(vt::VectorTuple; use_indices = true)
    if use_indices
        return Tuple(_make_array(vt.values[vt.ranges[i]], vt.indices[i])
                     for i in eachindex(vt.ranges))
    else
        return Tuple(length(vt.ranges[i]) == 1 ? vt.values[vt.ranges[i].start] : vt.values[vt.ranges[i]]
                     for i in eachindex(vt.ranges))
    end
end

# Define Tuple using construction from a values vector in combination with a VT
function Base.Tuple(vals::Vector, vt::VectorTuple; use_indices = true)
    @assert length(vals) == length(vt)
    if use_indices
        return Tuple(_make_array(vals[vt.ranges[i]], vt.indices[i])
                     for i in eachindex(vt.ranges))
    else
        return Tuple(length(vt.ranges[i]) == 1 ? vals[vt.ranges[i].start] : vals[vt.ranges[i]]
                     for i in eachindex(vt.ranges))
    end
end

## Enable pretty printing
# Extend Base.string
function Base.string(vt::VectorTuple)::String
    return string(Tuple(vt, use_indices = false))
end

# Show VectorTuples in REPLMode
function Base.show(io::IO, vt::VectorTuple)
    print(io, string(vt))
    return
end

# Show VectorTuples in IJuliaMode
function Base.show(io::IO, ::MIME"text/latex", vt::VectorTuple)
    print(io, string(vt))
end


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

using Markdown
using InteractiveUtils

# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).
macro bind(def, element)
    quote
        local el = $(esc(element))
        global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : missing
        el
    end
end

# ╔═╡ 87fefce0-02c5-11eb-3bc6-ad05fe23cf93
begin
	import Pkg
	Pkg.activate(mktempdir())
	Pkg.add("Plots")
	Pkg.add("PlutoUI")
	using Plots
	using PlutoUI
end

# ╔═╡ 3a7f37b0-02c9-11eb-28d5-1d8d43c6f44a
md"### Curva de Juros Interativa (Nelson-Siegel-Svensson)"

# ╔═╡ 5e857a22-02c9-11eb-2c2b-97f06fbcf1a8
md"Este pluto notebook permite interagir com os 6 parâmetros **β₀, β₁, β₂, β₃, λ₁, λ₂** do modelo de curva de juros de Nelson-Siegel-Svensson, gerando a visualização interativa da curva de juros.

Deste modo, é possível observar o impacto que cada parâmetro tem sobre o comportamento da curva de juros."

# ╔═╡ abc28efe-02db-11eb-12a1-e3aa3ea94d5f
md"O modelo segue a seguinte formulação:

$y_{t}(\tau)=\beta_{0, t}+\beta_{1, t} \left(\frac{1-e^{-\lambda_{1, x} \tau}}{\lambda_{1, t} \cdot \tau}\right)+\beta_{2, t} \left(\frac{1-e^{-\lambda_{1, x} \tau}}{\lambda_{1, t} \cdot \tau}-e^{-\lambda_{1, x} \cdot \tau}\right)+\beta_{3, t} \left(\frac{1-e^{-\lambda_{2, x} \cdot \tau}}{\lambda_{2, t} \cdot \tau}-e^{-\lambda_{2, x} \cdot \tau}\right)$"

# ╔═╡ c633a440-02c8-11eb-185a-8b3e594df121
begin
	n = @bind n Slider(5:100, default=25, show_value=true)
	β₀ = @bind β₀ Slider(0.01:0.001:1.0, default=0.05, show_value=true)
	β₁ = @bind β₁ Slider(-1:0.01:1.0, default=-0.05, show_value=true)
	β₂ = @bind β₂ Slider(-1:0.01:1.0, default=-0.1, show_value=true)
	β₃ = @bind β₃ Slider(-1:0.01:1.0, default=-0.05, show_value=true)
	λ₁ = @bind λ₁ Slider(0.01:0.01:2.0, default=0.1, show_value=true)
	λ₂ = @bind λ₂ Slider(0.01:0.01:1.0, default=0.08, show_value=true)

	md"""**Parâmetros da Curva de Juros**

	**N°**: $(n) 	Número de Obs. (21 du)

	**β₀**: $(β₀)	Fator de Nível (Longo Prazo)

	**β₁**: $(β₁)	Fator de Inclinação (Curto Prazo)

	**β₂**: $(β₂)	Fator de Curvatura (Médio Prazo)

	**β₃**: $(β₃)	Fator de Curvatura (Médio Prazo)

	**λ₁**: $(λ₁)   Velocidade de Decaimento (Médio Prazo)

	**λ₂**: $(λ₂)	Velocidade de Decaimento (Médio Prazo)"""
end

# ╔═╡ bdab38e0-02c5-11eb-09cf-43a08fb6bf8b
begin
	x = collect(21:21:(n*21))
	x[1] = 21
	@show x
end

# ╔═╡ b74b0b10-02ca-11eb-17cb-f5c8fdc4ee50
begin
	nss(β₀, β₁, β₂, β₃, λ₁, λ₂, t) =   β₀ +
									β₁*((1-exp(-λ₁*t))/(λ₁*t)) +
									β₂*((1-exp(-λ₁*t))/(λ₁*t) - exp(-λ₁*t)) +
									β₃*((1-exp(-λ₂*t))/(λ₂*t) - exp(-λ₂*t))
	y = [nss(β₀, β₁, β₂, β₃, λ₁, λ₂, i)*100 for i in x]
end

# ╔═╡ 3a9d9420-02d4-11eb-2df5-a12b2a9eecb8
begin
	gr()
	plot(x, y,
		leg=false,
		title="Curva de Juros (NSS)",
		xlabel="Vencimento em dias úteis", ylabel="% a.a",
		ylim=(-3,10),
		c=:blue, lw=3,
		shape=:hexagon,
		msize=4, # msize equivale a markersize
		markercolor=:white,
		markeralpha=1)
	plot!([-1, n*21], [0,0], c=:black, lab="", l=:dash)
end

# ╔═╡ Cell order:
# ╟─3a7f37b0-02c9-11eb-28d5-1d8d43c6f44a
# ╟─5e857a22-02c9-11eb-2c2b-97f06fbcf1a8
# ╟─abc28efe-02db-11eb-12a1-e3aa3ea94d5f
# ╟─87fefce0-02c5-11eb-3bc6-ad05fe23cf93
# ╟─c633a440-02c8-11eb-185a-8b3e594df121
# ╟─3a9d9420-02d4-11eb-2df5-a12b2a9eecb8
# ╟─bdab38e0-02c5-11eb-09cf-43a08fb6bf8b
# ╟─b74b0b10-02ca-11eb-17cb-f5c8fdc4ee50

max_stars_repo_name: AugustoCL/ETTJ-Interativa

max_issues_repo_name: AugustoCL/ETTJ-Interativa

max_forks_repo_name: AugustoCL/ETTJ-Interativa


text:
module BaseModule
export Position, Ionization, LQuantumNumber, MQuantumNumber, MQuantumNumbers, distance, origin, floatregex, @T_str, doublefactorial, evaluateFunction, trlog
import Base.*, Base.+, Base./, Base.-, Base.isless, Base.convert

struct Position
	x::Float64
	y::Float64
	z::Float64
end

const origin = Position(0.,0.,0.)

"""
    floatregex
is the regex-string that matches any floating point number with or without scientific notation

use it by combining it like
```
Regex(raw"5\\+" * floatregex)
```
to match e.g. '5+3.7'
"""
const floatregex = raw"[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?"

*(c::Real,p::Position) = Position(c*p.x,c*p.y,c*p.z)
*(p::Position,c::Real) = Position(c*p.x,c*p.y,c*p.z)
/(p::Position,c::Real) = Position(p.x/c,p.y/c,p.z/c)
+(p::Position,q::Position) = Position(p.x+q.x,p.y+q.y,p.z+q.z)
-(p::Position,q::Position) = Position(p.x-q.x,p.y-q.y,p.z-q.z)

convert(::Type{Vector{Float64}},p::Position) = [p.x,p.y,p.z]

function distance(p::Position,q::Position)
  pq = p - q
  return sqrt((pq.x)^2+(pq.y)^2+(pq.z)^2)
end

struct Ionization
  charge::Int64
end

"""
MQuantumNumber describes a single orientation of an atomic orbital in cartesian space by denoting the exponent of x, y and z of the radial part
E.g.:   a d_xy orbital can be described by MQuantumNumber(1,1,0)
"""
struct MQuantumNumber
  x::Int
  y::Int
  z::Int
end

lqnExponent = Dict{String,Int}(
  "S" => 	0,
  "P" => 	1,
  "D" => 	2,
  "F" =>	3,
  "G" =>	4,
  "H" =>	5,
  "I" =>	6,
  "K" =>	7,
)

exponentLqn = Dict{Int,String}(
  0 => 	"S",
  1 => 	"P",
  2 => 	"D",
  3 =>	"F",
  4 =>	"G",
  5 =>	"H",
  6 =>	"I",
  7 =>	"K",
)

"""
The LQuantumNumber desribes whether a function is spherical (s, lqn=0), polarized (p, lqn=1), etc.
As is generally known the total MQuantumNumber in pure coordinates lies between -lqn and +lqn.
This means that the sum of the three cartesian components can at most b. LQuantumNumber.
"""
struct LQuantumNumber
	symbol::String
	exponent::Int

	LQuantumNumber(sym::AbstractString) = new(sym,lqnExponent[sym])
	LQuantumNumber(exp::Int) = new(exponentLqn[exp],exp)
end

"""
    numberMQNsCartesian(l::LQuantumNumber)
returns the number of (cartesian, i.e. 'xxy' etc.) `MQuantumNumber`s with the given `LQuantumNumber`. This is equivalent to
`length(MQuantumNumbers(lqn))`.
"""
function numberMQNsCartesian(lqn::LQuantumNumber)
  l = lqn.exponent
  div((l+1)^2+(l+1),2)
end

"""
    numberMQNsPure(l::LQuantumNumber)
returns the number of pure m-Quantum numbers with the given `LQuantumNumber`: -l <= m <= l.
"""
function numberMQNsPure(lqn::LQuantumNumber)
  2*lqn.exponent + 1
end

"""
MQuantumNumber**s** returns the array of all MQuantumNumber objects corresponding to the LQuantumNumber.
Order is for example xx,xy,xz,yy,yz,zz for LQuantumNumber = 2
"""
function MQuantumNumbers(lqn::LQuantumNumber)
  maxmqn = lqn.exponent
  mqnarray=Vector{MQuantumNumber}(undef,((maxmqn+1)^2+(maxmqn+1))÷2)
  i = 0
  for x in maxmqn:-1:0
    for y in (maxmqn-x):-1:0
      i += 1
      z = maxmqn-x-y
      mqnarray[i] = MQuantumNumber(x,y,z)
    end
  end
  return mqnarray
end

isless(lqn1::LQuantumNumber, lqn2::LQuantumNumber) = lqn1.exponent<lqn2.exponent

function evaluateFunction(x::Position, f::Function)
  return f(x)
end

doublefactorial(n::Int) = prod(n:-2:1)

"""
    trLog(m::Matrix)
trace(logm(m::Matrix)) efficiently via Cholesky-decomposition.
"""
function trlog(m::Matrix)
  L = chol(m)
  result = 0.
  for idx in 1:size(L)[1]
    result += 2*log(L[idx,idx])
  end
  return result
end

end # module


text:
__precompile__(true)

module PlotsGR

include("init.jl")
include("backend.jl")
include("output.jl")

end # module


text:
module Atoms

using Compat

using AtomicLevels
import AtomicLevels: AbstractOrbital
using HalfIntegers
using AngularMomentumAlgebra
import AngularMomentumAlgebra: jmⱼ
using EnergyExpressions
import EnergyExpressions: NBodyMatrixElement, OrbitalMatrixElement,
    orbital_equation, MCEquationSystem, QuantumOperator

using ContinuumArrays
import ContinuumArrays: Basis
using QuasiArrays
import QuasiArrays: MulQuasiArray
using LazyArrays
import LazyArrays: materialize, materialize!, MulAdd
using FillArrays
using BandedMatrices
using BlockBandedMatrices

using FiniteDifferencesQuasi
using FEDVRQuasi

using LinearAlgebra
using SparseArrays

using ArnoldiMethod
using SCF
import SCF: norm_rot!, update!, KrylovWrapper, print_block
using CoulombIntegrals
import CoulombIntegrals: locs
using IterativeFactorizations

using AtomicPotentials
using PseudoPotentials

using Formatting
using UnicodeFun

function unique_orbitals(configurations::Vector{C}) where {O,C<:Configuration{O}}
    map(configurations) do config
        config.orbitals
    end |> o -> Vector{O}(vcat(o...)) |> unique |> sort
end

getspatialorb(orb::Orbital) = orb
getspatialorb(orb::SpinOrbital) = orb.orb

getn(orb::AbstractOrbital) = getspatialorb(orb).n
getℓ(orb::AbstractOrbital) = getspatialorb(orb).ℓ

include("restricted_bases.jl")
include("radial_orbitals.jl")
include("atom_types.jl")
include("one_body.jl")
include("utils.jl")
include("hydrogenic.jl")
include("projectors.jl")
include("lazy_matmuls.jl")
include("orbital_integrals.jl")
include("orbital_hamiltonian.jl")
include("orbital_equation.jl")
include("common_integrals.jl")
include("observables.jl")
include("spin_orbit.jl")
include("equations.jl")

end # module