text:
@testset "JuMP direct model - Linear Constraints - Affine parameters" begin
    optimizer = POI.Optimizer(GLPK.Optimizer())

    model = direct_model(optimizer)

    @variable(model, x[i = 1:2] >= 0)

    @variable(model, y in POI.Parameter(0))
    @variable(model, w in POI.Parameter(0))
    @variable(model, z in POI.Parameter(0))

    @constraint(model, 2 * x[1] + x[2] + y <= 4)
    @constraint(model, 1 * x[1] + 2 * x[2] + z <= 4)

    @objective(model, Max, 4 * x[1] + 3 * x[2] + w)

    optimize!(model)

    @test isapprox.(value(x[1]), 4.0 / 3.0, atol = ATOL)
    @test isapprox.(value(x[2]), 4.0 / 3.0, atol = ATOL)
    @test isapprox.(value(y), 0, atol = ATOL)

    # ===== Set parameter value =====
    MOI.set(model, POI.ParameterValue(), y, 2.0)
    optimize!(model)

    @test isapprox.(value(x[1]), 0.0, atol = ATOL)
    @test isapprox.(value(x[2]), 2.0, atol = ATOL)
    @test isapprox.(value(y), 2.0, atol = ATOL)
end

@testset "JuMP direct model - Linear Constraints - Parameter x variable" begin
    optimizer = POI.Optimizer(GLPK.Optimizer())

    model = direct_model(optimizer)

    @variable(model, x[i = 1:2] >= 0)

    @variable(model, y in POI.Parameter(0))
    @variable(model, w in POI.Parameter(0))
    @variable(model, z in POI.Parameter(0))

    @constraint(model, 2 * x[1] + x[2] + y <= 4)
    @constraint(model, (1 + y) * x[1] + 2 * x[2] + z <= 4)

    @objective(model, Max, 4 * x[1] + 3 * x[2] + w)

    optimize!(model)

    @test isapprox.(value(x[1]), 4.0 / 3.0, atol = ATOL)
    @test isapprox.(value(x[2]), 4.0 / 3.0, atol = ATOL)
    @test isapprox.(value(y), 0, atol = ATOL)

    # ===== Set parameter value =====
    MOI.set(model, POI.ParameterValue(), y, 2.0)
    optimize!(model)

    @test isapprox.(value(x[1]), 0.0, atol = ATOL)
    @test isapprox.(value(x[2]), 2.0, atol = ATOL)
    @test isapprox.(value(y), 2.0, atol = ATOL)
end

@testset "JuMP - Linear Constraints - Affine parameters" begin
    model = Model(() -> POI.Optimizer(GLPK.Optimizer()))

    @variable(model, x[i = 1:2] >= 0)

    @variable(model, y in POI.Parameter(0))
    @variable(model, w in POI.Parameter(0))
    @variable(model, z in POI.Parameter(0))

    @constraint(model, 2 * x[1] + x[2] + y <= 4)
    @constraint(model, 1 * x[1] + 2 * x[2] + z <= 4)

    @objective(model, Max, 4 * x[1] + 3 * x[2] + w)

    optimize!(model)

    @test isapprox.(value(x[1]), 4.0 / 3.0, atol = ATOL)
    @test isapprox.(value(x[2]), 4.0 / 3.0, atol = ATOL)
    @test isapprox.(value(y), 0, atol = ATOL)

    # ===== Set parameter value =====
    MOI.set(model, POI.ParameterValue(), y, 2.0)
    optimize!(model)

    @test isapprox.(value(x[1]), 0.0, atol = ATOL)
    @test isapprox.(value(x[2]), 2.0, atol = ATOL)
    @test isapprox.(value(y), 2.0, atol = ATOL)
end

@testset "JuMP - Linear Constraints - Parameter x variable" begin
    model = Model(() -> POI.Optimizer(GLPK.Optimizer()))

    @variable(model, x[i = 1:2] >= 0)

    @variable(model, y in POI.Parameter(0))
    @variable(model, w in POI.Parameter(0))
    @variable(model, z in POI.Parameter(0))

    @test MOI.get(model, POI.ParameterValue(), y) == 0

    @constraint(model, 2 * x[1] + x[2] + y <= 4)
    @constraint(model, (1 + y) * x[1] + 2 * x[2] + z <= 4)

    @objective(model, Max, 4 * x[1] + 3 * x[2] + w)

    optimize!(model)

    @test isapprox.(value(x[1]), 4.0 / 3.0, atol = ATOL)
    @test isapprox.(value(x[2]), 4.0 / 3.0, atol = ATOL)
    @test isapprox.(value(y), 0, atol = ATOL)

    # ===== Set parameter value =====
    MOI.set(model, POI.ParameterValue(), y, 2.0)
    optimize!(model)

    @test isapprox.(value(x[1]), 0.0, atol = ATOL)
    @test isapprox.(value(x[2]), 2.0, atol = ATOL)
    @test isapprox.(value(y), 2.0, atol = ATOL)
end

@testset "JuMP ConstraintFunction and ObjectiveFunction getters" begin
    model = direct_model(
        POI.Optimizer(
            MOI.Utilities.CachingOptimizer(
                MOI.Utilities.UniversalFallback(MOI.Utilities.Model{Float64}()),
                MOI.Utilities.AUTOMATIC,
            ),
        ),
    )

    vx = @variable(model, x[i = 1:2])
    vp = @variable(model, p[i = 1:2] in POI.Parameter.(-1))
    c1 = @constraint(model, con, sum(x) + sum(p) >= 1)
    c2 = @constraint(model, conq, sum(x .* p) >= 1)
    c3 = @constraint(model, conqa, sum(x .* p) + x[1]^2 + x[1] + p[1] >= 1)

    @test MOI.get(model, MOI.ConstraintFunction(), c1) ≈
          MOI.ScalarAffineFunction{Float64}(
        [
            MOI.ScalarAffineTerm{Float64}(1.0, MOI.VariableIndex(1)),
            MOI.ScalarAffineTerm{Float64}(1.0, MOI.VariableIndex(2)),
            MOI.ScalarAffineTerm{Float64}(
                1.0,
                MOI.VariableIndex(POI.PARAMETER_INDEX_THRESHOLD + 1),
            ),
            MOI.ScalarAffineTerm{Float64}(
                1.0,
                MOI.VariableIndex(POI.PARAMETER_INDEX_THRESHOLD + 2),
            ),
        ],
        0.0,
    )

    @test MOI.get(model, MOI.ConstraintFunction(), c2) ≈
          MOI.ScalarQuadraticFunction{Float64}(
        [
            MOI.ScalarQuadraticTerm{Float64}(
                1.0,
                MOI.VariableIndex(1),
                MOI.VariableIndex(POI.PARAMETER_INDEX_THRESHOLD + 1),
            ),
            MOI.ScalarQuadraticTerm{Float64}(
                1.0,
                MOI.VariableIndex(2),
                MOI.VariableIndex(POI.PARAMETER_INDEX_THRESHOLD + 2),
            ),
        ],
        [],
        0.0,
    )

    @test MOI.get(model, MOI.ConstraintFunction(), c3) ≈
          MOI.ScalarQuadraticFunction{Float64}(
        [
            MOI.ScalarQuadraticTerm{Float64}(
                1.0,
                MOI.VariableIndex(1),
                MOI.VariableIndex(POI.PARAMETER_INDEX_THRESHOLD + 1),
            ),
            MOI.ScalarQuadraticTerm{Float64}(
                1.0,
                MOI.VariableIndex(2),
                MOI.VariableIndex(POI.PARAMETER_INDEX_THRESHOLD + 2),
            ),
            MOI.ScalarQuadraticTerm{Float64}(
                2.0,
                MOI.VariableIndex(1),
                MOI.VariableIndex(1),
            ),
        ],
        [
            MOI.ScalarAffineTerm{Float64}(1.0, MOI.VariableIndex(1)),
            MOI.ScalarAffineTerm{Float64}(
                1.0,
                MOI.VariableIndex(POI.PARAMETER_INDEX_THRESHOLD + 1),
            ),
        ],
        0.0,
    )

    o1 = @objective(model, Min, sum(x) + sum(p))

    F = MOI.get(model, MOI.ObjectiveFunctionType())
    @test MOI.get(model, MOI.ObjectiveFunction{F}()) ≈
          MOI.ScalarAffineFunction{Float64}(
        [
            MOI.ScalarAffineTerm{Float64}(1.0, MOI.VariableIndex(1)),
            MOI.ScalarAffineTerm{Float64}(1.0, MOI.VariableIndex(2)),
            MOI.ScalarAffineTerm{Float64}(
                1.0,
                MOI.VariableIndex(POI.PARAMETER_INDEX_THRESHOLD + 1),
            ),
            MOI.ScalarAffineTerm{Float64}(
                1.0,
                MOI.VariableIndex(POI.PARAMETER_INDEX_THRESHOLD + 2),
            ),
        ],
        0.0,
    )

    o2 = @objective(model, Min, sum(x .* p) + 2)

    F = MOI.get(model, MOI.ObjectiveFunctionType())
    @test MOI.get(model, MOI.ObjectiveFunction{F}()) ≈
          MOI.ScalarQuadraticFunction{Float64}(
        [
            MOI.ScalarQuadraticTerm{Float64}(
                1.0,
                MOI.VariableIndex(1),
                MOI.VariableIndex(POI.PARAMETER_INDEX_THRESHOLD + 1),
            ),
            MOI.ScalarQuadraticTerm{Float64}(
                1.0,
                MOI.VariableIndex(2),
                MOI.VariableIndex(POI.PARAMETER_INDEX_THRESHOLD + 2),
            ),
        ],
        [],
        2.0,
    )

    o3 = @objective(model, Min, sum(x .* p) + x[1]^2 + x[1] + p[1])

    F = MOI.get(model, MOI.ObjectiveFunctionType())
    @test MOI.get(model, MOI.ObjectiveFunction{F}()) ≈
          MOI.ScalarQuadraticFunction{Float64}(
        [
            MOI.ScalarQuadraticTerm{Float64}(
                1.0,
                MOI.VariableIndex(1),
                MOI.VariableIndex(POI.PARAMETER_INDEX_THRESHOLD + 1),
            ),
            MOI.ScalarQuadraticTerm{Float64}(
                1.0,
                MOI.VariableIndex(2),
                MOI.VariableIndex(POI.PARAMETER_INDEX_THRESHOLD + 2),
            ),
            MOI.ScalarQuadraticTerm{Float64}(
                2.0,
                MOI.VariableIndex(1),
                MOI.VariableIndex(1),
            ),
        ],
        [
            MOI.ScalarAffineTerm{Float64}(1.0, MOI.VariableIndex(1)),
            MOI.ScalarAffineTerm{Float64}(
                1.0,
                MOI.VariableIndex(POI.PARAMETER_INDEX_THRESHOLD + 1),
            ),
        ],
        0.0,
    )
end

@testset "JuMP Interpret parametric bounds simple example" begin
    model = Model(() -> POI.Optimizer(GLPK.Optimizer()))
    MOI.set(model, POI.ConstraintsInterpretation(), POI.ONLY_BOUNDS)

    @variable(model, x[i = 1:2])
    @variable(model, p[i = 1:2] in POI.Parameter.(-1))
    @constraint(model, [i in 1:2], x[i] >= p[i])
    @objective(model, Min, sum(x))
    optimize!(model)

    @test MOI.get(model, MOI.ListOfConstraintTypesPresent()) ==
          Tuple{Type,Type}[
        (MOI.ScalarAffineFunction{Float64}, MOI.GreaterThan{Float64}),
        (MOI.VariableIndex, POI.Parameter),
    ]

    @test MOI.get(
        backend(model).optimizer.model.optimizer,
        MOI.ListOfConstraintTypesPresent(),
    ) == Tuple{Type,Type}[(MOI.VariableIndex, MOI.GreaterThan{Float64})]

    @test objective_value(model) == -2

    MOI.set(model, POI.ParameterValue(), p[1], 4.0)

    optimize!(model)
    @test objective_value(model) == 3
end

@testset "JuMP Interpret parametric bounds parametric expression" begin
    model = Model(() -> POI.Optimizer(GLPK.Optimizer()))
    MOI.set(model, POI.ConstraintsInterpretation(), POI.ONLY_BOUNDS)

    @variable(model, x[i = 1:2])
    @variable(model, p[i = 1:2] in POI.Parameter.(-1))
    @constraint(model, [i in 1:2], x[i] >= p[i] + p[1])
    @objective(model, Min, sum(x))
    optimize!(model)

    @test MOI.get(model, MOI.ListOfConstraintTypesPresent()) ==
          Tuple{Type,Type}[
        (MOI.ScalarAffineFunction{Float64}, MOI.GreaterThan{Float64}),
        (MOI.VariableIndex, POI.Parameter),
    ]

    @test MOI.get(
        backend(model).optimizer.model.optimizer,
        MOI.ListOfConstraintTypesPresent(),
    ) == Tuple{Type,Type}[(MOI.VariableIndex, MOI.GreaterThan{Float64})]

    @test objective_value(model) == -4

    MOI.set(model, POI.ParameterValue(), p[1], 4.0)

    optimize!(model)
    @test objective_value(model) == 11.0
end

@testset "JuMP Interpret parametric bounds direct model" begin
    model = direct_model(POI.Optimizer(GLPK.Optimizer()))
    MOI.set(model, POI.ConstraintsInterpretation(), POI.ONLY_BOUNDS)

    @variable(model, x[i = 1:2])
    @variable(model, p[i = 1:2] in POI.Parameter.(-1))
    @constraint(model, [i in 1:2], x[i] >= p[i])
    @objective(model, Min, sum(x))
    optimize!(model)

    @test MOI.get(model, MOI.ListOfConstraintTypesPresent()) ==
          Tuple{Type,Type}[(MOI.VariableIndex, MOI.GreaterThan{Float64})]

    @test MOI.get(
        backend(model).optimizer,
        MOI.ListOfConstraintTypesPresent(),
    ) == Tuple{Type,Type}[(MOI.VariableIndex, MOI.GreaterThan{Float64})]

    @test objective_value(model) == -2

    MOI.set(model, POI.ParameterValue(), p[1], 4.0)

    optimize!(model)
    @test objective_value(model) == 3
end

@testset "JuMP Interpret parametric bounds direct model no interpretation" begin
    model = direct_model(POI.Optimizer(GLPK.Optimizer()))
    MOI.set(model, POI.ConstraintsInterpretation(), POI.ONLY_CONSTRAINTS)

    @variable(model, x[i = 1:2])
    @variable(model, p[i = 1:2] in POI.Parameter.(-1))
    @constraint(model, [i in 1:2], x[i] >= p[i])
    @objective(model, Min, sum(x))
    optimize!(model)

    @test MOI.get(model, MOI.ListOfConstraintTypesPresent()) ==
          Tuple{Type,Type}[(
        MOI.ScalarAffineFunction{Float64},
        MOI.GreaterThan{Float64},
    )]

    @test MOI.get(
        backend(model).optimizer,
        MOI.ListOfConstraintTypesPresent(),
    ) == Tuple{Type,Type}[(
        MOI.ScalarAffineFunction{Float64},
        MOI.GreaterThan{Float64},
    )]

    @test objective_value(model) == -2

    MOI.set(model, POI.ParameterValue(), p[1], 4.0)

    optimize!(model)
    @test objective_value(model) == 3
end

@testset "JuMP Interpret parametric bounds direct model change interpretation" begin
    model = direct_model(POI.Optimizer(GLPK.Optimizer()))
    MOI.set(model, POI.ConstraintsInterpretation(), POI.ONLY_BOUNDS)
    @variable(model, x[i = 1:2])
    @variable(model, p[i = 1:2] in POI.Parameter.(-1))
    @constraint(model, [i in 1:2], x[i] >= p[i])
    @test_throws ErrorException @constraint(model, [i in 1:2], 2x[i] >= p[i])
    MOI.set(model, POI.ConstraintsInterpretation(), POI.ONLY_CONSTRAINTS)
    @constraint(model, [i in 1:2], 2x[i] >= p[i])
    @objective(model, Min, sum(x))
    optimize!(model)

    @test objective_value(model) == -1

    MOI.set(model, POI.ParameterValue(), p[1], 4.0)

    optimize!(model)
    @test objective_value(model) == 3.5
end

@testset "JuMP Interpret parametric bounds direct model both interpretations" begin
    model = direct_model(POI.Optimizer(GLPK.Optimizer()))
    MOI.set(model, POI.ConstraintsInterpretation(), POI.BOUNDS_AND_CONSTRAINTS)
    @variable(model, x[i = 1:2])
    @variable(model, p[i = 1:2] in POI.Parameter.(-1))
    @constraint(model, [i in 1:2], x[i] >= p[i])
    @constraint(model, [i in 1:2], 2x[i] >= p[i])
    @objective(model, Min, sum(x))
    optimize!(model)

    @test objective_value(model) == -1

    MOI.set(model, POI.ParameterValue(), p[1], 4.0)

    optimize!(model)
    @test objective_value(model) == 3.5
end

@testset "JuMP Interpret parametric bounds parametric not a valid bound" begin
    model = direct_model(POI.Optimizer(GLPK.Optimizer()))
    MOI.set(model, POI.ConstraintsInterpretation(), POI.ONLY_BOUNDS)

    @variable(model, x[i = 1:2])
    @variable(model, p[i = 1:2] in POI.Parameter.(-1))
    @test_throws ErrorException @constraint(
        model,
        [i in 1:2],
        2x[i] >= p[i] + p[1]
    )
end


text:
"""
A module that provides several renderers for `Document` objects. The supported
formats are currently:

  * `:markdown` -- the default format.
  * `:html` -- generates a complete HTML site with navigation and search included.
  * `:latex` -- generates a PDF using LuaLaTeX.

"""
module Writers

import ..Documenter:
    Anchors,
    Builder,
    Documents,
    Expanders,
    Documenter,
    Utilities

import .Utilities: Selectors

#
# Format selector definitions.
#

abstract type FormatSelector <: Selectors.AbstractSelector end

abstract type MarkdownFormat <: FormatSelector end
abstract type LaTeXFormat    <: FormatSelector end
abstract type HTMLFormat     <: FormatSelector end

Selectors.order(::Type{MarkdownFormat}) = 1.0
Selectors.order(::Type{LaTeXFormat})    = 2.0
Selectors.order(::Type{HTMLFormat})     = 3.0

Selectors.matcher(::Type{MarkdownFormat}, fmt, _) = isa(fmt, MarkdownWriter.Markdown)
Selectors.matcher(::Type{LaTeXFormat},    fmt, _) = isa(fmt, LaTeXWriter.LaTeX)
Selectors.matcher(::Type{HTMLFormat},     fmt, _) = isa(fmt, HTMLWriter.HTML)

Selectors.runner(::Type{MarkdownFormat}, fmt, doc) = MarkdownWriter.render(doc, fmt)
Selectors.runner(::Type{LaTeXFormat},    fmt, doc) = LaTeXWriter.render(doc, fmt)
Selectors.runner(::Type{HTMLFormat},     fmt, doc) = HTMLWriter.render(doc, fmt)

"""
Writes a [`Documents.Document`](@ref) object to `.user.build` directory in
the formats specified in the `.user.format` vector.

Adding additional formats requires adding new `Selector` definitions as follows:

```julia
abstract type CustomFormat <: FormatSelector end

Selectors.order(::Type{CustomFormat}) = 4.0 # or a higher number.
Selectors.matcher(::Type{CustomFormat}, fmt, _) = fmt === :custom
Selectors.runner(::Type{CustomFormat}, _, doc) = CustomWriter.render(doc)

# Definition of `CustomWriter` module below...
```
"""
function render(doc::Documents.Document)
    # Render each format. Additional formats must define an `order`, `matcher`, `runner`, as
    # well as their own rendering methods in a separate module.
    for each in doc.user.format
        if isa(each, MarkdownWriter.Markdown) && !backends_enabled[:markdown]
            @warn """Deprecated format

            The Markdown/MkDocs backend must now be imported from a separate package.
            Add DocumenterMarkdown to your documentation dependencies and add

                using DocumenterMarkdown

            to your make.jl script, and use

                makedocs(
                    format = Markdown(),
                    ...
                )

            in the call to `makedocs`.
            Built-in support for markdown outpu will be removed completely in a future
            Documenter version, causing builds to fail completely.

            See the Output Backends section in the manual for more information.
            """
        elseif isa(each, LaTeXWriter.LaTeX) && !backends_enabled[:latex]
            @warn """Deprecated format

            The LaTeX/PDF backend must now be imported from a separate package.
            Add DocumenterLaTeX to your documentation dependencies and add

                using DocumenterLaTeX

            to your make.jl script, and use

                makedocs(
                    format = LaTeX(),
                    ...
                )

            in the call to `makedocs`.
            Built-in support for LaTeX/PDF output will be removed completely in a future
            Documenter version, causing builds to fail completely.

            See the Output Backends section in the manual for more information.
            """
        end
        Selectors.dispatch(FormatSelector, each, doc)
    end
    # Revert all local links to their original URLs.
    for (link, url) in doc.internal.locallinks
        link.url = url
    end
end

include("MarkdownWriter.jl")
include("HTMLWriter.jl")
include("LaTeXWriter.jl")

# This is hack to enable shell packages that would behave as in the supplementary Writer
# modules have been moved out of Documenter.
#
# External packages DocumenterMarkdown and DocumenterLaTeX can use the enable_backend
# function to mark that a certain backend is loaded in backends_enabled. That is used to
# determine whether a deprecation warning should be printed in the render method above.
#
# enable_backend() is not part of the API and will be removed as soon as LaTeXWriter and
# MarkdownWriter are actually moved out into a separate module (TODO).
backends_enabled = Dict(
    :markdown => false,
    :latex => false
)

function enable_backend(backend::Symbol)
    global backends_enabled
    if backend in keys(backends_enabled)
        backends_enabled[backend] = true
    else
        @error "Unknown backend. Expected one of:" keys(backends_enabled)
        throw(ArgumentError("Unknown backend $backend."))
    end
end

end

ext: jl


text:
# Initialize an empty PairwiseListMatrix (PLM) for a pairwise measure in column or
# sequence pairs. These functions take care of the labels.
"""
Initialize an empty `PairwiseListMatrix` for a pairwise measure in column pairs. It uses the
column mapping (column number in the input MSA file) if it’s available, otherwise it uses
the actual column numbers. You can use the positional argument to indicate the number
`Type` (default: `Float64`), if the `PairwiseListMatrix` should store the diagonal values
on the list (default: `false`) and a default value for the diagonal (default: `NaN`).
"""
function sequencepairsmatrix(msa::AbstractMatrix{Residue}, ::Type{T},
                             ::Type{Val{diagonal}}, diagonalvalue::T) where {T,diagonal}
    plm = PairwiseListMatrix(T, nsequences(msa), diagonal, diagonalvalue)
    nplm = setlabels(plm, sequencenames(msa))
    setdimnames!(nplm, ["Seq1", "Seq2"])
    nplm::NamedArray{T,2,PairwiseListMatrix{T,diagonal,Vector{T}},NTuple{2,OrderedDict{String,Int}}}
end

function sequencepairsmatrix(msa::AbstractMatrix{Residue})
    sequencepairsmatrix(msa, Float64, Val{false}, NaN)
end

"""
Initialize an empty `PairwiseListMatrix` for a pairwise measure in sequence pairs. It uses
the sequence names if they are available, otherwise it uses the actual sequence numbers.
You can use the positional argument to indicate the number `Type` (default: `Float64`),
if the `PairwiseListMatrix` should store the diagonal values on the list (default: `false`)
and a default value for the diagonal (default: `NaN`).
"""
function columnpairsmatrix(msa::AbstractMatrix{Residue}, ::Type{T},
                           ::Type{Val{diagonal}}, diagonalvalue::T) where {T,diagonal}
    plm = PairwiseListMatrix(T, ncolumns(msa), diagonal, diagonalvalue)
    nplm = setlabels(plm, columnnames(msa))
    setdimnames!(nplm, ["Col1", "Col2"])
    nplm::NamedArray{T,2,PairwiseListMatrix{T,diagonal,Vector{T}},NTuple{2,OrderedDict{String,Int}}}
end

function columnpairsmatrix(msa::AbstractMatrix{Residue})
    columnpairsmatrix(msa, Float64, Val{false}, NaN)
end


text:
using StaticCompiler
using StaticTools

function print_args(argc::Int, argv::Ptr{Ptr{UInt8}})
    printf(c"Argument count is %d:\n", argc)
    for i=1:argc
        # iᵗʰ input argument string
        pᵢ = unsafe_load(argv, i) # Get pointer
        strᵢ = MallocString(pᵢ) # Can wrap to get high-level interface
        println(strᵢ)
        # No need to `free` since we didn't allocate this memory
    end
    newline()
    println(c"Testing string indexing and substitution")
    m = m"Hello world!"
    println(m[1:5])
    println(m)
    m[7:11] = c"there"
    println(m)
    free(m)

    s = m"Hello world!"
    println(s[1:5])
    println(s)
    s[7:11] = c"there"
    println(s)

    println(c"That was fun, see you next time!")
    return 0
end

# Attempt to compile
path = compile_executable(print_args, (Int64, Ptr{Ptr{UInt8}}), "./")


text:
using Documenter
using TiffImages

using Literate
using Images

EXAMPLE_DIR = joinpath(@__DIR__, "..", "examples")
EXAMPLES = filter(x->endswith(x, ".jl"), joinpath.(EXAMPLE_DIR, readdir(EXAMPLE_DIR)))
OUTPUT = joinpath(@__DIR__, "src", "examples")

for ex in EXAMPLES
    Literate.markdown(ex, OUTPUT, documenter = true)
end

DocMeta.setdocmeta!(TiffImages, :DocTestSetup, :(using TiffImages); recursive=true)
makedocs(
    format = Documenter.HTML(
        prettyurls = true,
    ),
    modules=[TiffImages],
    sitename="TiffImages.jl",
    authors="Tamas Nagy and contributors",
    pages = [
        "Home" => "index.md",
        "Examples" => [
            "Reading TIFFs" => joinpath("examples", "reading.md")
            "Writing TIFFs" => joinpath("examples", "writing.md")
        ],
        "Library" => [
            "Public" => joinpath("lib", "public.md"),
            "Extending" => [
                "Overview" => joinpath("lib", "extend", "index.md"),
                "Built-in Tags" => joinpath("lib", "extend", "tags.md"),
            ],
        ],
        "Contributing" => "contributing.md"
    ]
)

deploydocs(
    repo = "github.com/tlnagy/TiffImages.jl.git",
    push_preview = true
)


text:
module TestMLJInterface

using ParallelKMeans
using ParallelKMeans: KMeans
using Random
using Test
using Suppressor
using MLJBase

@testset "Test struct construction" begin
    model = KMeans()

    @test model.algo            == :Hamerly
    @test model.init            == nothing
    @test model.k               == 3
    @test model.k_init          == "k-means++"
    @test model.max_iters       == 300
    @test model.copy            == true
    @test model.threads         == Threads.nthreads()
    @test model.tol             == 1.0e-6
end

@testset "Test bad struct warings" begin
    @test_logs (:warn, "Unsupported KMeans variant. Defaulting to Hamerly algorithm.") ParallelKMeans.KMeans(algo=:Fake)
    @test_logs (:warn, "Only \"k-means++\" or \"random\" seeding algorithms are supported. Defaulting to k-means++ seeding.") ParallelKMeans.KMeans(k_init="abc")
    @test_logs (:warn, "Number of clusters must be greater than 0. Defaulting to 3 clusters.") ParallelKMeans.KMeans(k=0)
    @test_logs (:warn, "Tolerance level must be less than 1. Defaulting to tol of 1e-6.") ParallelKMeans.KMeans(tol=2)
    @test_logs (:warn, "Number of permitted iterations must be greater than 0. Defaulting to 300 iterations.") ParallelKMeans.KMeans(max_iters=0)
    @test_logs (:warn, "Number of threads must be at least 1. Defaulting to all threads available.") ParallelKMeans.KMeans(threads=0)
end

@testset "Test model fitting verbosity" begin
    Random.seed!(2020)
    X = table([1 2; 1 4; 1 0; 10 2; 10 4; 10 0])
    model = KMeans(k=2, max_iters=1)
    results = @capture_out fit(model, 1, X)

    @test results == "Iteration 1: Jclust = 28.0\n"
end

@testset "Test Lloyd model fitting" begin
    Random.seed!(2020)
    X = table([1 2; 1 4; 1 0; 10 2; 10 4; 10 0])
    X_test = table([10 1])

    model = KMeans(algo = :Lloyd, k=2)
    results, cache, report = fit(model, 0, X)

    @test cache              == nothing
    @test results.converged  == true
    @test report.totalcost   == 16

    params = fitted_params(model, results)
    @test params.cluster_centers == [1.0 10.0; 2.0 2.0]

    # Use trained model to cluster new data X_test
    preds = transform(model, results, X_test)
    @test preds[:x1][1] == 82.0
    @test preds[:x2][1] == 1.0

    # Make predictions on new data X_test with fitted params
    yhat = predict(model, results, X_test)
    @test yhat[1] == 2
end

@testset "Test Hamerly model fitting" begin
    Random.seed!(2020)
    X = table([1 2; 1 4; 1 0; 10 2; 10 4; 10 0])
    X_test = table([10 1])

    model = KMeans(algo = :Hamerly, k=2)
    results, cache, report = fit(model, 0, X)

    @test cache              == nothing
    @test results.converged  == true
    @test report.totalcost   == 16

    params = fitted_params(model, results)
    @test params.cluster_centers == [1.0 10.0; 2.0 2.0]

    # Use trained model to cluster new data X_test
    preds = transform(model, results, X_test)
    @test preds[:x1][1] == 82.0
    @test preds[:x2][1] == 1.0

    # Make predictions on new data X_test with fitted params
    yhat = predict(model, results, X_test)
    @test yhat[1] == 2
end

@testset "Test Elkan model fitting" begin
    Random.seed!(2020)
    X = table([1 2; 1 4; 1 0; 10 2; 10 4; 10 0])
    X_test = table([10 1])

    model = KMeans(algo = :Elkan, k=2)
    results, cache, report = fit(model, 0, X)

    @test cache              == nothing
    @test results.converged  == true
    @test report.totalcost   == 16

    params = fitted_params(model, results)
    @test params.cluster_centers == [1.0 10.0; 2.0 2.0]

    # Use trained model to cluster new data X_test
    preds = transform(model, results, X_test)
    @test preds[:x1][1] == 82.0
    @test preds[:x2][1] == 1.0

    # Make predictions on new data X_test with fitted params
    yhat = predict(model, results, X_test)
    @test yhat[1] == 2
end

@testset "Testing non convergence warning" begin
    Random.seed!(2020)
    X = table([1 2; 1 4; 1 0; 10 2; 10 4; 10 0])
    X_test = table([10 1])

    model = KMeans(k=2, max_iters=1)
    results, cache, report = fit(model, 0, X)

    @test_logs (:warn, "Failed to converge. Using last assignments to make transformations.") transform(model, results, X_test)
end

"""
@testset "Testing non convergence warning during model fitting" begin
    Random.seed!(2020)
    X = table([1 2; 1 4; 1 0; 10 2; 10 4; 10 0])
    X_test = table([10 1])

    model = KMeans(k=2, max_iters=1)
    @test_logs (:warn, "Specified model failed to converge.") fit(model, 1, X);
end
"""
end # module


text:
module AdjacencyArrays

import SparseArrays, Random, DelimitedFiles
import Base.show, Base.display

export AbstractNetwork
export EmptyNetwork
export GlobalNetwork
export RegularNetwork
export ErdosRenyiNetwork
export WattsStrogatzNetwork
export CustomNetwork

export numnodes, numconnections, isdirected, maxconnections, numshortcuts, isregular
export hasnode, hasconnection
export connectivity, connectivities, meanconnectivity
export clusteringcoefficient, clusteringcoefficients, transitivity
export shortestpath, averagepathlength
export sigma, omega, smallworldness, equivalentRandomNetwork, equivalentLatticeNetwork
export adjVet, adjMat
export adjVetToMat, adjMatToVet, saveAdjMat, saveAdjVet
export neighbors, allEdges

include("architectures/AbstractNetwork.jl")
include("utils.jl")
include("properties/NetworkProperties.jl")

include("architectures/Empty.jl")
include("architectures/Global.jl")
include("architectures/Regular.jl")
include("architectures/ErdosRenyi.jl")
include("architectures/WattsStrogatz.jl")
include("architectures/CustomNetwork.jl")

include("properties/Abstract.jl")
include("properties/Empty.jl")
include("properties/Global.jl")
include("properties/Regular.jl")
include("properties/ErdosRenyi.jl")
include("properties/WattsStrogatz.jl")

include("operators/Abstract.jl")

end


text:
module ExodusII

EntIDType = Int64

# Utility functions

function array_cstring_to_string(s::Array{UInt8})
  i = findfirst(s.==UInt8('\0'))
  if i==0
    i = length(s)+1
  end
  return String(s[1:(i-1)])
end

function handle_return_no_warn(code::Cint)
  if code <= -1
    error("Exodus error: \"$(ex_get_error())\"")
  end
end

function handle_return(code::Cint)
  if code >= 1
    warn("Exodus warning: \"$(ex_get_error())\"")
  end
  if code <= -1
    error("Exodus error: \"$(ex_get_error())\"")
  end
end

# Constants defined in exodusII.h

EX_API_VERS = 6.02
EX_API_VERS_NODOT = Cint(602)
EX_READ  = 0x0000
EX_WRITE = 0x0001

EX_NOCLOBBER    = 0x0004
EX_CLOBBER      = 0x0008
EX_NORMAL_MODEL = 0x0010
EX_LARGE_MODEL  = 0x0020
EX_NETCDF4      = 0x0040
EX_NOSHARE      = 0x0080
EX_SHARE        = 0x0100
EX_NOCLASSIC    = 0x0200

EX_MAPS_INT64_DB = 0x0400
EX_IDS_INT64_DB  = 0x0800
EX_BULK_INT64_DB = 0x1000
EX_ALL_INT64_DB  = EX_MAPS_INT64_DB|EX_IDS_INT64_DB|EX_BULK_INT64_DB
EX_MAPS_INT64_API = 0x2000
EX_IDS_INT64_API  = 0x4000
EX_BULK_INT64_API = 0x8000
EX_ALL_INT64_API  = EX_MAPS_INT64_API|EX_IDS_INT64_API|EX_BULK_INT64_API

EX_INQ_FILE_TYPE       =  1 # inquire EXODUS II file type
EX_INQ_API_VERS        =  2 # inquire API version number
EX_INQ_DB_VERS         =  3 # inquire database version number
EX_INQ_TITLE           =  4 # inquire database title
EX_INQ_DIM             =  5 # inquire number of dimensions
EX_INQ_NODES           =  6 # inquire number of nodes
EX_INQ_ELEM            =  7 # inquire number of elements
EX_INQ_ELEM_BLK        =  8 # inquire number of element blocks
EX_INQ_NODE_SETS       =  9 # inquire number of node sets
EX_INQ_NS_NODE_LEN     = 10 # inquire length of node set node list
EX_INQ_SIDE_SETS       = 11 # inquire number of side sets
EX_INQ_SS_NODE_LEN     = 12 # inquire length of side set node list
EX_INQ_SS_ELEM_LEN     = 13 # inquire length of side set element list
EX_INQ_QA              = 14 # inquire number of QA records
EX_INQ_INFO            = 15 # inquire number of info records
EX_INQ_TIME            = 16 # inquire number of time steps in the database
EX_INQ_EB_PROP         = 17 # inquire number of element block properties
EX_INQ_NS_PROP         = 18 # inquire number of node set properties
EX_INQ_SS_PROP         = 19 # inquire number of side set properties
EX_INQ_NS_DF_LEN       = 20 # inquire length of node set distribution factor list
EX_INQ_SS_DF_LEN       = 21 # inquire length of side set distribution factor list
EX_INQ_LIB_VERS        = 22 # inquire API Lib vers number
EX_INQ_EM_PROP         = 23 # inquire number of element map properties
EX_INQ_NM_PROP         = 24 # inquire number of node map properties
EX_INQ_ELEM_MAP        = 25 # inquire number of element maps
EX_INQ_NODE_MAP        = 26 # inquire number of node maps
EX_INQ_EDGE            = 27 # inquire number of edges
EX_INQ_EDGE_BLK        = 28 # inquire number of edge blocks
EX_INQ_EDGE_SETS       = 29 # inquire number of edge sets
EX_INQ_ES_LEN          = 30 # inquire length of concat edge set edge list
EX_INQ_ES_DF_LEN       = 31 # inquire length of concat edge set dist factor list
EX_INQ_EDGE_PROP       = 32 # inquire number of properties stored per edge block
EX_INQ_ES_PROP         = 33 # inquire number of properties stored per edge set
EX_INQ_FACE            = 34 # inquire number of faces
EX_INQ_FACE_BLK        = 35 # inquire number of face blocks
EX_INQ_FACE_SETS       = 36 # inquire number of face sets
EX_INQ_FS_LEN          = 37 # inquire length of concat face set face list
EX_INQ_FS_DF_LEN       = 38 # inquire length of concat face set dist factor list
EX_INQ_FACE_PROP       = 39 # inquire number of properties stored per face block
EX_INQ_FS_PROP         = 40 # inquire number of properties stored per face set
EX_INQ_ELEM_SETS       = 41 # inquire number of element sets
EX_INQ_ELS_LEN         = 42 # inquire length of concat element set element list
EX_INQ_ELS_DF_LEN      = 43 # inquire length of concat element set dist factor list
EX_INQ_ELS_PROP        = 44 # inquire number of properties stored per elem set
EX_INQ_EDGE_MAP        = 45 # inquire number of edge maps
EX_INQ_FACE_MAP        = 46 # inquire number of face maps
EX_INQ_COORD_FRAMES    = 47 # inquire number of coordinate frames
EX_INQ_DB_MAX_ALLOWED_NAME_LENGTH  = 48 # inquire size of MAX_NAME_LENGTH dimension on database
EX_INQ_DB_MAX_USED_NAME_LENGTH  = 49 # inquire size of MAX_NAME_LENGTH dimension on database
EX_INQ_MAX_READ_NAME_LENGTH = 50 # inquire client-specified max size of returned names
EX_INQ_DB_FLOAT_SIZE   = 51 # inquire size of floating-point values stored on database
EX_INQ_NUM_CHILD_GROUPS= 52 # inquire number of groups contained in this (exoid) group
EX_INQ_GROUP_PARENT    = 53 # inquire id of parent of this (exoid) group; returns exoid if at root
EX_INQ_GROUP_ROOT      = 54 # inquire id of root group "/" of this (exoid) group; returns exoid if at root
EX_INQ_GROUP_NAME_LEN  = 55 # inquire length of name of group exoid
EX_INQ_GROUP_NAME      = 56 # inquire name of group exoid. "/" returned for root group
EX_INQ_FULL_GROUP_NAME_LEN = 57 # inquire length of full path name of this (exoid) group
EX_INQ_FULL_GROUP_NAME = 58 # inquire full "/"-separated path name of this (exoid) group
EX_INQ_INVALID         = -1

# enum ex_entity_type {
EX_NODAL       = 14 # nodal "block" for variables
EX_NODE_BLOCK  = 14 # alias for EX_NODAL
EX_NODE_SET    =  2 # node set property code
EX_EDGE_BLOCK  =  6 # edge block property code
EX_EDGE_SET    =  7 # edge set property code
EX_FACE_BLOCK  =  8 # face block property code
EX_FACE_SET    =  9 # face set property code
EX_ELEM_BLOCK  =  1 # element block property code
EX_ELEM_SET    = 10 # face set property code

EX_SIDE_SET    =  3 # side set property code

EX_ELEM_MAP    =  4 # element map property code
EX_NODE_MAP    =  5 # node map property code
EX_EDGE_MAP    = 11 # edge map property code
EX_FACE_MAP    = 12 # face map property code

EX_GLOBAL      = 13 # global "block" for variables
EX_COORDINATE  = 15 # kluge so some internal wrapper functions work
EX_INVALID     = -1
# }

# These lengths do not include space for the terminating nul. Following the
# exodusII manual space should be allocated with a +1
EX_MAX_STRING_LENGTH = 32
EX_MAX_LINE_LENGTH = 80

# Constants
julia_float_size = 8

function ex_get_error()
  msg = Ref{Ptr{UInt8}}(0)
  func = Ref{Ptr{UInt8}}(0)
  code = Ref{Cint}(0)

  ccall((:ex_get_err,"libexoIIv2"),
        Void,
        (Ref{Ptr{UInt8}},Ref{Ptr{UInt8}},Ref{Cint}),
        msg, func, code)
  return unsafe_string(msg[])
end

type ex_file
  fid::Cint
  title::String
  num_dim::Int32
  num_nodes::Int32
  num_elem::Int32
  num_elem_blk::Int32
  num_node_sets::Int32
  num_side_sets::Int32
end

function ex_create(path::String,
                   title::String,
                   num_dim,
                   num_nodes,
                   num_elem,
                   num_elem_blk,
                   num_node_sets,
                   num_side_sets)

  app_float_size = Ref{Cint}(julia_float_size)
  fil_float_size = Ref{Cint}(julia_float_size)
  fid = ccall((:ex_create_int,"libexoIIv2"),
              Cint,
              (Cstring,Cint,Ref{Cint},Ref{Cint},Cint),
              path,EX_CLOBBER,app_float_size,fil_float_size,EX_API_VERS_NODOT)
  handle_return_no_warn(fid)

  ret = ccall((:ex_put_init,"libexoIIv2"),
              Cint,
              (Cint,Cstring,Int64,Int64,Int64,Int64,Int64,Int64),
              fid,title,num_dim,num_nodes,num_elem,num_elem_blk,num_node_sets,num_side_sets)
  if ret < 0
    ccall((:ex_close,"libexoIIv2"),Cint,(Cint,),fid)
    handle_return(ret)
  end

  return ex_file(fid,
                 title,
                 num_dim,
                 num_nodes,
                 num_elem,
                 num_elem_blk,
                 num_node_sets,
                 num_side_sets)
end

function ex_open(path::String)::ex_file
  my_float_size = Ref{Cint}(julia_float_size)
  file_float_size = Ref{Cint}(8) # sizeof(double)
  file_ver_num = Ref{Float32}(0)  # is written to

  fid = ccall((:ex_open_int,"libexoIIv2"),
              Cint,
              (Cstring,Cint,Ref{Cint},Ref{Cint},Ref{Float32},Cint),
              path,EX_READ,my_float_size,file_float_size,file_ver_num,EX_API_VERS_NODOT)
  handle_return_no_warn(fid)

  ret = ccall((:ex_int64_status,"libexoIIv2"),Cint,(Cint,),fid)
  if ret & (EX_ALL_INT64_DB|EX_ALL_INT64_API) > 0
    ret = ccall((:ex_close,"libexoIIv2"),Cint,(Cint,),fid)
    error("Julia exodus interface cannot handle int64 bulk data")
  end

  title = Array{UInt8}(EX_MAX_LINE_LENGTH+1)
  num_dim = Ref{Int32}(0)
  num_nodes = Ref{Int32}(0)
  num_elem = Ref{Int32}(0)
  num_elem_blk = Ref{Int32}(0)
  num_node_sets = Ref{Int32}(0)
  num_side_sets = Ref{Int32}(0)
  ret = ccall((:ex_get_init,"libexoIIv2"),
              Cint,
              (Cint,Ref{UInt8},Ref{Int32},Ref{Int32},Ref{Int32},Ref{Int32},Ref{Int32},Ref{Int32}),
              fid,title,num_dim,num_nodes,num_elem,num_elem_blk,num_node_sets,num_side_sets)
  handle_return(ret)

  return ex_file(fid,
                 array_cstring_to_string(title),
                 num_dim[],
                 num_nodes[],
                 num_elem[],
                 num_elem_blk[],
                 num_node_sets[],
                 num_side_sets[])
end

function ex_close(file::ex_file)
  ret = ccall((:ex_close,"libexoIIv2"),Cint,(Cint,),file.fid)
  handle_return(ret)
end

function ex_put_coord(file::ex_file,coord::Array{Float64,2})
  if all(size(coord) != (file.num_dim,file.num_nodes))
    error("size of coords provided incorrect ($(size(coord))!=$([file.num_dim,file.num_nodes]))")
  end

  X = coord[1,:]
  Y = Ptr{Float64}(0)
  Z = Ptr{Float64}(0)
  if file.num_dim >= 2
    Y = coord[2,:]
  end
  if file.num_dim >= 3
    Z = coord[3,:]
  end

  ret = ccall((:ex_put_coord,"libexoIIv2"),
              Cint,
              (Cint,Ptr{Float64},Ptr{Float64},Ptr{Float64}),
              file.fid,X,Y,Z)
  handle_return(ret)
end

function ex_get_coord(file::ex_file)
  X = Array{Float64}(file.num_nodes)
  Y = Array{Float64}(file.num_nodes)
  Z = Array{Float64}(file.num_nodes)
  ret = ccall((:ex_get_coord,"libexoIIv2"),
              Cint,
              (Cint,Ptr{Float64},Ptr{Float64},Ptr{Float64}),
              file.fid,X,Y,Z)
  handle_return(ret)
  if file.num_dim == 1
    return X'
  elseif file.num_dim == 2
    return vcat(X',Y')
  elseif file.num_dim == 3
    return vcat(X',Y',Z')
  else
    error("Unexpected number of dimensions in ExodusII file")
  end
end

function ex_put_coord_names(file::ex_file,names::Array{String})
  if length(names) != file.num_dim
    error("number of names does not match number of dimensions")
  end
  for name in names
    if length(name)>EX_MAX_STRING_LENGTH
      error("Coordinate name is too long")
    end
  end
  ret = ccall((:ex_put_coord_names,"libexoIIv2"),
              Cint,
              (Cint,Ptr{Cstring}),
              file.fid,names)
  handle_return(ret)
end

function ex_put_name(file::ex_file,entity_type,entity_id,name)
  if length(name) > EX_MAX_STRING_LENGTH
    error("name too long, must be at most $(EX_MAX_STRING_LENGTH) chars")
  end
  ret = ccall((:ex_put_name,"libexoIIv2"),
              Cint,
              (Cint,Cint,EntIDType,Cstring),
              file.fid,entity_type,entity_id,name)
  handle_return(ret)
end

function ex_get_name(file::ex_file,entity_type,entity_id)
  name = Array{UInt8}(EX_MAX_STRING_LENGTH+1)
  ret = ccall((:ex_get_name,"libexoIIv2"),
              Cint,
              (Cint,Cint,EntIDType,Ptr{UInt8}),
              file.fid,entity_type,entity_id,name)
  handle_return(ret)
  return array_cstring_to_string(name)
end

function ex_get_coord_names(file::ex_file)
  raw_names = Array{Array{UInt8}}([Array{UInt8}(EX_MAX_STRING_LENGTH+1) for i in 1:file.num_dim])
  ret = ccall((:ex_get_coord_names,"libexoIIv2"),
              Cint,
              (Cint,Ref{Ptr{UInt8}}),
              file.fid,raw_names)
  handle_return(ret)
  return map(array_cstring_to_string,raw_names)
end

function ex_put_node_num_map{T<:Integer}(file::ex_file,node_map::Array{T})
  nm = convert(Array{Int32},node_map)
  ret = ccall((:ex_put_node_num_map,"libexoIIv2"),
              Cint,
              (Cint,Ptr{Int32}),
              file.fid,nm)
  handle_return(ret)
end

function ex_get_node_num_map(file::ex_file)
  node_map = Array{Int32}(file.num_nodes)
  ret = ccall((:ex_get_node_num_map,"libexoIIv2"),
              Cint,
              (Cint,Ref{Int32}),
              file.fid,node_map)
  handle_return(ret)
  return node_map
end

function ex_put_elem_num_map{T<:Integer}(file::ex_file,elem_map::Array{T})
  em = convert(Array{Int32},elem_map)
  ret = ccall((:ex_put_elem_num_map,"libexoIIv2"),
              Cint,
              (Cint,Ptr{Int32}),
              file.fid,em)
  handle_return(ret)
end

function ex_get_elem_num_map(file::ex_file)
  elem_map = Array{Int32}(file.num_elem)
  ret = ccall((:ex_get_elem_num_map,"libexoIIv2"),
              Cint,
              (Cint,Ref{Int32}),
              file.fid,elem_map)
  handle_return(ret)
  return elem_map
end

function ex_put_elem_block(file::ex_file,
                           block_id,
                           elem_type::String,
                           num_elem,
                           nodes_per_elem,
                           num_attr)
  ret = ccall((:ex_put_elem_block,"libexoIIv2"),
              Cint,
              (Cint,EntIDType,Cstring,Int64,Int64,Int64),
              file.fid,block_id,elem_type,num_elem,nodes_per_elem,num_attr)
  handle_return(ret)
end

function ex_get_elem_block(file::ex_file,block_id::Integer)
  elem_type = Array{UInt8}(EX_MAX_STRING_LENGTH+1)
  num_el             = Ref{Int32}(0)
  num_nodes_per_elem = Ref{Int32}(0)
  num_attr           = Ref{Int32}(0)
  ret = ccall((:ex_get_elem_block,"libexoIIv2"),
              Cint,
              (Cint,EntIDType,Ref{UInt8},Ref{Int32},Ref{Int32},Ref{Int32}),
              file.fid,block_id,elem_type,num_el,num_nodes_per_elem,num_attr)
  handle_return(ret)
  return array_cstring_to_string(elem_type), num_el[], num_nodes_per_elem[], num_attr[]
end

function ex_get_elem_block_ids(file::ex_file)
  block_ids = Array{Int32}(file.num_elem_blk)
  ret = ccall((:ex_get_elem_blk_ids,"libexoIIv2"),
              Cint,
              (Cint,Ref{Int32}),
              file.fid,block_ids)
  handle_return(ret)
  return block_ids
end

function ex_put_elem_connections{T<:Integer}(file::ex_file,block_id,connections::Array{T,2})
  _,num_elem,nodes_per_el = ex_get_elem_block(file,block_id)
  if size(connections)!=(nodes_per_el,num_elem)
    error("connections is incorrect size")
  end

  conn = reshape(convert(Array{Int32,2},connections),(num_elem*nodes_per_el,))

  ret = ccall((:ex_put_elem_conn,"libexoIIv2"),
              Cint,
              (Cint,EntIDType,Ptr{Int32}),
              file.fid,block_id,conn)
  handle_return(ret)
end

function ex_get_elem_connections(file::ex_file,block_id::Integer)
  _,num_elem,nodes_per_el = ex_get_elem_block(file,block_id)

  raw_connect = Array{Int32}(nodes_per_el*num_elem)
  ret = ccall((:ex_get_elem_conn,"libexoIIv2"),
              Cint,
              (Cint,EntIDType,Ref{Int32}),
              file.fid,block_id,raw_connect)
  handle_return(ret)

  return reshape(raw_connect,(nodes_per_el,num_elem))
end

function ex_put_node_set_param(file::ex_file,node_set_id,num_nodes,num_dist=0)
  ret = ccall((:ex_put_node_set_param,"libexoIIv2"),
              Cint,
              (Cint,EntIDType,Int64,Int64),
              file.fid,node_set_id,num_nodes,num_dist)
  handle_return(ret)
end

function ex_get_node_set_param(file::ex_file,node_set_id)
  num_nodes_in_set = Ref{Int32}(0)
  num_dist_in_set = Ref{Int32}(0)
  ret = ccall((:ex_get_node_set_param,"libexoIIv2"),
              Cint,
              (Cint,EntIDType,Ref{Int32},Ref{Int32}),
              file.fid,node_set_id,num_nodes_in_set,num_dist_in_set)
  handle_return(ret)
  return num_nodes_in_set[],num_dist_in_set[]
end

function ex_put_node_set{T<:Integer}(file::ex_file,node_set_id,node_list::Array{T})
  nl = convert(Array{Int32},node_list)
  ret = ccall((:ex_put_node_set,"libexoIIv2"),
              Cint,
              (Cint,EntIDType,Ptr{Int32}),
              file.fid,node_set_id,nl)
  handle_return(ret)
end

function ex_get_node_set(file::ex_file,node_set_id)
  num_nodes,_ = ex_get_node_set_param(file,node_set_id)
  node_set = Array{Int32}(num_nodes)
  ret = ccall((:ex_get_node_set,"libexoIIv2"),
              Cint,
              (Cint,EntIDType,Ref{Int32}),
              file.fid,node_set_id,node_set)
  handle_return(ret)
  return node_set
end

function ex_get_node_set_ids(file::ex_file)
  node_set_ids = Array{Int32}(file.num_node_sets)
  ret = ccall((:ex_get_node_set_ids,"libexoIIv2"),
              Cint,
              (Cint,Ref{Int32}),
              file.fid,node_set_ids)
  handle_return(ret)
  return node_set_ids
end

function ex_get_elem_blk_prop_names(file::ex_file)
  ret_int = Ref{Int32}(0)
  ret_flt = Ref{Float64}(0)
  ret_chr = Ref{UInt8}(0)
  ret = ccall((:ex_inquire,"libexoIIv2"),
              Cint,
              (Cint,Cint,Ref{Int32},Ref{Float64},Ref{UInt8}),
              file.fid,EX_INQ_EB_PROP,ret_int,ret_flt,ret_chr)
  handle_return(ret)
  num_prop = ret_int[]
  raw_names = Array{Array{UInt8}}([Array{UInt8}(EX_MAX_STRING_LENGTH) for i in num_prop])
  ret = ccall((:ex_get_prop_names,"libexoIIv2"),
              Cint,
              (Cint,Cint,Ref{Ptr{UInt8}}),
              file.fid,EX_ELEM_BLOCK,raw_names)
  handle_return(ret)
  return map(array_cstring_to_string,raw_names)
end

function ex_get_node_set_prop_names(file::ex_file)
  ret_int = Ref{Int32}(0)
  ret_flt = Ref{Float64}(0)
  ret_chr = Ref{UInt8}(0)
  ret = ccall((:ex_inquire,"libexoIIv2"),
              Cint,
              (Cint,Cint,Ref{Int32},Ref{Float64},Ref{UInt8}),
              file.fid,EX_INQ_NS_PROP,ret_int,ret_flt,ret_chr)
  handle_return(ret)
  num_prop = ret_int[]
  raw_names = Array{Array{UInt8}}([Array{UInt8}(EX_MAX_STRING_LENGTH) for i in num_prop])
  ret = ccall((:ex_get_prop_names,"libexoIIv2"),
              Cint,
              (Cint,Cint,Ref{Ptr{UInt8}}),
              file.fid,EX_NODE_SET,raw_names)
  handle_return(ret)
  return map(array_cstring_to_string,raw_names)
end

function ex_get_side_set_prop_names(file::ex_file)
  ret_int = Ref{Int32}(0)
  ret_flt = Ref{Float64}(0)
  ret_chr = Ref{UInt8}(0)
  ret = ccall((:ex_inquire,"libexoIIv2"),
              Cint,
              (Cint,Cint,Ref{Int32},Ref{Float64},Ref{UInt8}),
              file.fid,EX_INQ_SS_PROP,ret_int,ret_flt,ret_chr)
  handle_return(ret)
  num_prop = ret_int[]
  raw_names = Array{Array{UInt8}}([Array{UInt8}(EX_MAX_STRING_LENGTH) for i in num_prop])
  ret = ccall((:ex_get_prop_names,"libexoIIv2"),
              Cint,
              (Cint,Cint,Ref{Ptr{UInt8}}),
              file.fid,EX_SIDE_SET,raw_names)
  handle_return(ret)
  return map(array_cstring_to_string,raw_names)
end

function ex_put_var_param(file::ex_file,var_type::String,num_vars)
  ret = ccall((:ex_put_var_param,"libexoIIv2"),
              Cint,
              (Cint,Cstring,Cint),
              file.fid,var_type,num_vars)
  handle_return(ret)
end

function ex_put_num_node_vars(file::ex_file,num_vars)
  ex_put_var_param(file,"n",num_vars)
end

function ex_put_num_elem_vars(file::ex_file,num_vars)
  ex_put_var_param(file,"e",num_vars)
end

function ex_get_var_param(file::ex_file,var_type::String)
  num = Ref{Cint}(0)
  ret = ccall((:ex_get_var_param,"libexoIIv2"),
              Cint,
              (Cint,Cstring,Ref{Cint}),
              file.fid,var_type,num)
  handle_return(ret)
  return num[]
end

function ex_put_var_names(file::ex_file,var_type::String,names)
  num_vars = length(names)
  for name in names
    if length(name)>EX_MAX_STRING_LENGTH
      error("Variable name is too long")
    end
  end
  ret = ccall((:ex_put_var_names,"libexoIIv2"),
              Cint,
              (Cint,Cstring,Cint,Ptr{Cstring}),
              file.fid,var_type,num_vars,names)
  handle_return(ret)
end

function ex_get_var_names(file::ex_file,var_type::String,num_vars)
  names = Array{Array{UInt8}}([Array{UInt8}(EX_MAX_STRING_LENGTH+1) for i in 1:num_vars])
  ret = ccall((:ex_get_var_names,"libexoIIv2"),
              Cint,
              (Cint,Cstring,Cint,Ref{Ptr{UInt8}}),
              file.fid,var_type,num_vars,names)
  handle_return(ret)
  return map(array_cstring_to_string,names)
end

function ex_put_nodal_var_names(file::ex_file,names)
  if length(names) != ex_get_var_param(file,"n")
    error("number of nodal var names incorrect")
  end
  return ex_put_var_names(file,"n",names)
end

function ex_get_nodal_var_names(file::ex_file)
  return ex_get_var_names(file,"n",ex_get_var_param(file,"n"))
end

function ex_put_elem_var_names(file::ex_file,names)
  if length(names) != ex_get_var_param(file,"e")
    error("number of elem var names incorrect")
  end
  return ex_put_var_names(file,"e",names)
end

function ex_get_elem_var_names(file::ex_file)
  return ex_get_var_names(file,"e",ex_get_var_param(file,"e"))
end

function ex_put_time(file::ex_file,time_step,time_val)
  val = Ref{Float64}(time_val)
  ret = ccall((:ex_put_time,"libexoIIv2"),
              Cint,
              (Cint,Cint,Ptr{Float64}),
              file.fid,time_step,val)
  handle_return(ret)
end

function ex_get_num_times(file::ex_file)::Int32
  ret_int = Ref{Int32}(0)
  ret_flt = Ref{Float64}(0)
  ret_chr = Ref{UInt8}(0)
  ret = ccall((:ex_inquire,"libexoIIv2"),
              Cint,
              (Cint,Int32,Ref{Int32},Ref{Float64},Ref{UInt8}),
              file.fid,EX_INQ_TIME,ret_int,ret_flt,ret_chr)
  handle_return(ret)
  return ret_int[]
end

function ex_get_time(file::ex_file,time_index::Integer)
  time = Ref{Float64}(0)
  ret = ccall((:ex_get_time,"libexoIIv2"),
              Cint,
              (Cint,Cint,Ref{Float64}),
              file.fid,time_index,time)
  handle_return(ret)
  return time[]
end

function ex_get_all_times(file::ex_file)
  times = Array{Float64}(ex_get_num_times(file))
  ret = ccall((:ex_get_all_times,"libexoIIv2"),
              Cint,
              (Cint,Ref{Float64}),
              file.fid,times)
  handle_return(ret)
  return times
end

function ex_put_elem_var_tab{T<:Integer}(file::ex_file,elem_var_tab::Array{T,2})
  num_var,num_blk = size(elem_var_tab)
  tab = reshape(convert(Array{Cint,2},elem_var_tab),num_var*num_blk)
  ret = ccall((:ex_put_elem_var_tab,"libexoIIv2"),
              Cint,
              (Cint,Cint,Cint,Ptr{Cint}),
              file.fid,num_blk,num_var,tab)
  handle_return(ret)
end

function ex_get_elem_var_tab(file::ex_file)
  num_elem_vars = ex_get_var_param(file,"e")
  elem_var_table = Array{Cint}(file.num_elem_blk*num_elem_vars)
  ret = ccall((:ex_get_elem_var_tab,"libexoIIv2"),
              Cint,
              (Cint,Cint,Cint,Ref{Cint}),
              file.fid,file.num_elem_blk,num_elem_vars,elem_var_table)
  handle_return(ret)
  return reshape(elem_var_table,(num_elem_vars,file.num_elem_blk))
end

function ex_put_elem_var(file::ex_file,time_step::Integer,elem_var::Integer,elem_blk_id,vals)
  num_elem = length(vals)
  ret = ccall((:ex_put_elem_var,"libexoIIv2"),
              Cint,
              (Cint,Cint,Cint,EntIDType,Int64,Ptr{Float64}),
              file.fid,time_step,elem_var,elem_blk_id,num_elem,vals)
  handle_return(ret)
end

function ex_get_elem_var_vals(file::ex_file,time_step::Integer,name::String,block_id)
  var_index = findfirst(ex_get_elem_var_names(file).==name)
  if var_index==0
    error("Could not find elemental variable \"$(name)\" in exodusII file")
  end
  num_elem_in_blk = ex_get_elem_block(file,block_id)[2]
  values = Array{Float64}(num_elem_in_blk)

  ret = ccall((:ex_get_elem_var,"libexoIIv2"),
              Cint,
              (Cint,Cint,Cint,EntIDType,Int64,Ref{Float64}),
              file.fid,time_step,var_index,block_id,num_elem_in_blk,values)
  handle_return(ret)
  return values
end

function ex_get_elem_var_vals(file::ex_file,time_step::Integer,elem_var::Integer,block_id)
  num_elem_in_blk = ex_get_elem_block(file,block_id)[2]
  values = Array{Float64}(num_elem_in_blk)
  ret = ccall((:ex_get_elem_var,"libexoIIv2"),
              Cint,
              (Cint,Cint,Cint,EntIDType,Int64,Ref{Float64}),
              file.fid,time_step,elem_var,block_id,num_elem_in_blk,values)
  handle_return(ret)
  return values
end

function ex_put_node_var(file::ex_file,time_step::Integer,node_var::Integer,vals)
  num_nodes = length(vals)
  ret = ccall((:ex_put_nodal_var,"libexoIIv2"),
              Cint,
              (Cint,Cint,Cint,Int64,Ptr{Float64}),
              file.fid,time_step,node_var,num_nodes,vals)
  handle_return(ret)
end

function ex_get_node_var_vals(file::ex_file,name::String,time_step::Integer)
  var_index = findfirst(ex_get_nodal_var_names(file).==name)
  if var_index==0
    error("Could not find nodal variable \"$(name)\" in exodusII file")
  end
  values = Array{Float64}(file.num_nodes)
  ret = ccall((:ex_get_nodal_var,"libexoIIv2"),
              Cint,
              (Cint,Cint,Cint,Int64,Ref{Float64}),
              file.fid,time_step,var_index,file.num_nodes,values)
  handle_return(ret)

  return values
end

end # module


text:
# Note that this script can accept some limited command-line arguments, run
# `julia build_tarballs.jl --help` to see a usage message.
using BinaryBuilder

name = "LibPQ"
version = v"14.3"
pg_version = string(version.major, '.', version.minor)
tzcode_version = "2021e"

# Collection of sources required to build LibPQ
sources = [
    ArchiveSource(
        "https://ftp.postgresql.org/pub/source/v$pg_version/postgresql-$pg_version.tar.gz",
        "18eff30438703dd7a5f2a7ca916741bce3c99eadb4025bc6268af268e8e909c5"
    ),
    ArchiveSource(
        "https://data.iana.org/time-zones/releases/tzcode$tzcode_version.tar.gz",
        "584666393a5424d13d27ec01183da17703273664742e049d4f62f62dab631775",
    ),
]

# Bash recipe for building across all platforms
# NOTE: readline and zlib are not used by libpq
script = raw"""
cd $WORKSPACE/srcdir
make CC=$BUILD_CC VERSION_DEPS= zic
export ZIC=$WORKSPACE/srcdir/zic
cd $WORKSPACE/srcdir/postgresql-*/
if [[ "${target}" == i686-linux-musl ]]; then
    # Small hack: swear that we're cross-compiling.  Our `i686-linux-musl` is
    # bugged and it can run only a few programs, with the result that the
    # configure test to check whether we're cross-compiling returns that we're
    # doing a native build, but then it fails to run a bunch of programs during
    # other tests.
    sed -i 's/cross_compiling=no/cross_compiling=yes/' configure
fi
FLAGS=()
if [[ "${target}" == *-linux-* ]] || [[ "${target}" == *-freebsd* ]]; then
    FLAGS+=(--with-gssapi)
    if [[ "${target}" == *-freebsd* ]]; then
        # Only for FreeBSD we need to hint that we need to libcom_err to get
        # functions `add_error_table` and `remove_error_table`
        export LIBS=-lcom_err
    fi
fi
./configure --prefix=${prefix} \
    --build=${MACHTYPE} \
    --host=${target} \
    --with-includes=${includedir} \
    --with-libraries=${libdir} \
    --without-readline \
    --without-zlib \
    --with-openssl \
    "${FLAGS[@]}"
make -C src/interfaces/libpq -j${nproc}
make -C src/interfaces/libpq install

# Delete static library
rm ${prefix}/lib/libpq.a
install_license COPYRIGHT
"""

# These are the platforms we will build for by default, unless further
# platforms are passed in on the command line
platforms = supported_platforms()

# The products that we will ensure are always built
products = [
    LibraryProduct("libpq", :LIBPQ_HANDLE)
]

# Dependencies that must be installed before this package can be built
dependencies = [
    Dependency("OpenSSL_jll"),
    Dependency("Kerberos_krb5_jll"; platforms=filter(p -> Sys.islinux(p) || Sys.isfreebsd(p), platforms)),
]

# Build the tarballs, and possibly a `build.jl` as well.
build_tarballs(ARGS, name, version, sources, script, platforms, products, dependencies; julia_compat="1.6")


text:
using Lazy, HTTP

import HTTP.Request

export respond, mux

# Utils

pre(f) = (app, req) -> app(f(req))
post(f) = (app, req) -> f(app(req))

# Request

function todict(req::Request)
  req′ = Dict()
  req′[:method]   = req.method
  req′[:headers]  = req.headers
  req′[:resource] = req.target
  req′[:data] = req.body
  req′[:uri] = URI(req.target)
  req′[:cookies]  = HTTP.Cookies.cookies(req)
  return req′
end

todict(app, req) = app(todict(req))

using HTTP.URIs: URI

function splitquery(app, req)
  uri = URI(req[:resource])
  delete!(req, :resource)
  req[:path] = splitpath(uri.path)
  req[:query] = uri.query
  app(req)
end

params!(req) = get!(req, :params, d())

# Response

Response(d::AbstractDict) =
    HTTP.Response(get(d, :status, 200),
            get(d, :headers, HTTP.Headers());
            body = get(d, :body, ""))

Response(o) = HTTP.Response(stringmime(MIME"text/html"(), o))

response(d) = d
response(s::AbstractString) = d(:body=>s)

toresponse(app, req) = Response(response(app(req)))

respond(res) = req -> response(res)

reskey(k, v) = post(res -> merge!(res, d(k=>v)))

status(s) = reskey(:status, s)

# Error handling

mux_css = """
  body { font-family: sans-serif; padding:50px; }
  .box { background: #fcfcff; padding:20px; border: 1px solid #ddd; border-radius:5px; white-space: pre-wrap; word-wrap: break-word; }
  pre { line-height:1.5 }
  a { text-decoration:none; color:#225; }
  a:hover { color:#336; }
  u { cursor: pointer }
  """

error_phrases = ["Looks like someone needs to pay their developers more."
                 "Someone order a thousand more monkeys! And a million more typewriters!"
                 "Maybe it's time for some sleep?"
                 "Don't bother debugging this one – it's almost definitely a quantum thingy."
                 "It probably won't happen again though, right?"
                 "F5! F5! F5!"
                 "F5! F5! FFS!"
                 "On the bright side, nothing has exploded. Yet."
                 "If this error has frustrated you, try clicking here."]

function basiccatch(app, req)
  try
    app(req)
  catch e
    io = IOBuffer()
    println(io, "")
    println(io, "
Internal Error
")
    println(io, "
$(error_phrases[rand(1:length(error_phrases))])
")
    println(io, "
")
    showerror(io, e, catch_backtrace())
    println(io, "
")
    return d(:status => 500, :body => codeunits(String(take!(io))))
  end
end


text:
import Pkg
Pkg.activate(".")
using DistancePlan
using Test
using StaticArrays

@testset "DistancePlan.jl" begin
    @test distance(SVector(0., 0.), SVector(1., 1.)) == sqrt(2)
    @test distance(SVector(0., 0.), Box(SVector(1., 1.), SVector(2., 2.))) <= sqrt(2)
    @test distance(SVector(0., 0.), Sphere(SVector(1., 1.), 0.5)) == sqrt(2) - 0.5
    @test distance(SVector(0., 0.), [SVector(0., 0.), SVector(1., 1.)]) == 0.
    @test distance(SVector(0., 0.), Box(SVector(-1., -1.), SVector(1., 1.))) < 0
    @test distance(SVector(-2., 0.), Box(SVector(-1., -1.), SVector(1., 1.))) == 1.
    @test distance(SVector(2., 0.), Box(SVector(-1., -1.), SVector(1., 1.))) == 1.
    @test distance(SVector(0., 2.), Box(SVector(-1., -1.), SVector(1., 1.))) == 1.
    @test distance(SVector(0., -2.), Box(SVector(-1., -1.), SVector(1., 1.))) == 1.
    @test distance(SVector(0., 0.), [SVector(1., 1.), SVector(-1., -1.)]) == sqrt(2)
    # Write your own tests here.
end

max_stars_repo_name: krzentner/DistancePlan

max_issues_repo_name: krzentner/DistancePlan

max_forks_repo_name: krzentner/DistancePlan


text:
#using SortingAlgorithms

fsortperm(x::T) where T = begin
    #@warn "SortingLab.jl: calling fsortperm does not confer an advantage as it's not optimsied for type $(T)"
    i = collect(1:length(x))
    sorttwo!(copy(x), i)
    i
end


text:
function hessian_replicates(dfns, d2fns, parms, pts, datav)
  hess = zeros(3,3)
  _S   = Symmetric([matern(x, y, parms) for x in pts, y in pts])
  S    = cholesky(_S)
  for j in 1:3
    dfj = dfns[j]
    Sj  = Symmetric([dfj(x, y, parms) for x in pts, y in pts])
    for k in j:3
      # first derivative matrix:
      dfk   = dfns[k]
      Sk    = Symmetric([dfk(x, y, parms)  for x in pts, y in pts])
      # second derivative matrix:
      dfjk  = d2fns[j][k-j+1]
      Sjk   = Symmetric([dfjk(x, y, parms) for x in pts, y in pts])
      # Compute the complicated derivative of the qform (not efficient or
      # thoughtful, so don't use this code for real somewhere):
      dqf   = -(S\(Sk*(S\(Sj*inv(_S)))) )
      dqf  += S\(Sjk*inv(_S))
      dqf  -= S\(Sj*(S\(Sk*inv(_S))))
      # compute the term:
      term  = (tr(S\Sjk) - tr(S\(Sj*(S\Sk))))*length(datav)/2
      term -= sum(z->dot(z, dqf, z), datav)/2
      hess[j,k] = term
      hess[k,j] = term
    end
  end
  hess
end


text:
    # props = laminar_body_quantities.(H_ks, M_es, Re_θs)
    # H_stars  = getindex.(props, 1)
    # H_star_stars  = getindex.(props, 2)
    # CFs  = getindex.(props, 3)
    # CDs  = getindex.(props, 4)

    # # Forward differencing boundary layer inputs using logarithmic derivatives

    # # Logarithmic differences
    # dlogUs   = @. log(Us[2:end] / Us[1:end-1])
    # dlogθs    = @. log(θs[2:end] / θs[1:end-1])
    # dlogH_stars  = @. log(H_stars[2:end] / H_stars[1:end-1])

    # # Differences
    # ΔTs  = @. Ts[2:end] - Ts[1:end-1]

    # # Points
    # M_e_sq_as  = weighted_vector(M_es[2:end], M_es[1:end-1], 0.5).^2 # Check Mₑ² term later
    # θ_as    = weighted_vector(θs[2:end], θs[1:end-1], 0.5)
    # H_as    = weighted_vector(Hs[2:end], Hs[1:end-1], 0.5)
    # H_k_as    = weighted_vector(H_ks[2:end], H_ks[1:end-1], 0.5)
    # CF_as    = weighted_vector(CFs[2:end], CFs[1:end-1], 0.5)
    # CD_as    = weighted_vector(CFs[2:end], CFs[1:end-1], 0.5)
    # H_star_as    = weighted_vector(H_stars[2:end], H_stars[1:end-1], 0.5)
    # H_star_star_as  = weighted_vector(H_star_stars[2:end], H_star_stars[1:end-1], 0.5)
    # δ_star_as  = weighted_vector(δ_stars[2:end], δ_stars[1:end-1], 0.5)

    # # Momentum equation residuals
    # R1    = momentum_fd.(dlogθs, dlogUs, ΔXs, θ_as, H_k_as, CF_as, M_e_sq_as)
    # # Shape parameter equation residuals
    # R2    = shape_fd.(dlogH_stars, dlogUs, ΔXs, θ_as, H_k_as, H_star_as, H_star_star_as, CF_as, CD_as)
    # # eⁿ amplification residuals
    # R3  = lam_turb.(Ts[1:end-1], Ts[2:end], ΔXs, dlogUs, θ_as, δ_star_as, H_as, H_k_as, H_star_as, CF_as, n_crit)

    # n  = length(θs)
    # H_stars = zeros(n)
    # H_star_stars = zeros(n)
    # CFs  = zeros(n)
    # CDs  = zeros(n)
    # U_s  = zeros(n)
    # c_τs  = zeros(n)
    # for i in 1:n
    #  if tags[i] <: Panel2D
    #  # Need to put transition checks
    #  H_stars[i], H_star_stars[i], CFs[i], CDs[i] = laminar_body_quantities(H_ks[i], M_es[i], Re_θs[i])
    #  else # Wake panel condition
    #  H_stars[i], H_star_stars[i], CFs[i], c_τs[i], U_s[i], CDs[i] = turbulent_body_quantities(H_ks[i], Hs[i], M_es[i], Re_θs[i])
    #  end
    # end

    # Laminar/transition/turbulence residuals
    # dlogc_τs  = @. log(c_τs[2:end] / c_τs[1:end-1])
    # c_τ_EQ_as  = weighted_vector(c_τs[2:end], c_τs[1:end-1], 0.5)

    # for i in 1:n
    #  if tags[i] <: Panel2D
    #  # Need to put transition checks
    #  R3[i] = amplification_fd(Δn, dlogs, H_as, θ_as)
    #  else # Wake panel condition
    #  R3[i] = stress_transport_fd.(c_τ_as, dlogc_τs, dlogUs, ΔXs, δ, δ_stars, CF_as, c_τ_EQ_as, H_as)
    #  end
    # end


text:
@testset "Serialization format" begin
    session = Session()
    test = "heyyyy"
    doms = [DOM.div("hey"), DOM.h1("heydude")]
    dublicate = rand(1000, 1000)
    duplicate_id = pointer_identity(dublicate)
    data = Dict(
        "array" => [1,2,3,4,5],
        "obsies" => [Observable(1), Observable([1,2,3,4])],
        "tuples" => (1,2,3,4),
        "double" => dublicate,
        "nested" => Dict(
            :symbols! => "string",
            :unicode => "πϕ♋",
            :node_array => doms,
            :jscode => js"heyy($(test))",
            :moah_nesting => dublicate
        )
    )

    bytes = serialize_binary(session, data)
    data_unpacked = MsgPack.unpack(transcode(GzipDecompressor, bytes))
    @test haskey(session.unique_object_cache, duplicate_id)
    @test isempty(data_unpacked["update_cache"]["to_remove"])
    @test length(data_unpacked["update_cache"]["to_register"]) == 1
    @test first(keys(data_unpacked["update_cache"]["to_register"])) == duplicate_id

    @test data_unpacked["data"]["nested"]["jscode"]["payload"]["source"] == "heyy('$(test)')"
    @test data_unpacked["data"]["nested"]["unicode"] == "πϕ♋"
    @test data_unpacked["data"]["nested"]["node_array"][1] == js_type("DomNode", uuid(doms[1]))
    @test data_unpacked["data"]["nested"]["node_array"][2] == js_type("DomNode", uuid(doms[2]))
    @test data_unpacked["data"]["nested"]["jscode"]["payload"]["source"] == "heyy('$(test)')"
    @test data_unpacked["data"]["nested"]["moah_nesting"]["__javascript_type__"] == "Reference"
    @test data_unpacked["data"]["nested"]["moah_nesting"]["payload"] == duplicate_id
    @test data_unpacked["data"]["double"] isa Vector

    bytes2 = serialize_binary(session, data)
    data_unpacked = MsgPack.unpack(transcode(GzipDecompressor, bytes2))
    @test data_unpacked["double"]["__javascript_type__"] == "Reference"
    @test data_unpacked["nested"]["moah_nesting"]["__javascript_type__"] == "Reference"
end


text:
using CairoMakie
using Distributed
proc_number = 4;
if nprocs() < proc_number
    addprocs(proc_number - nprocs())
end
@everywhere include("calc_settings.jl")
## Plotting
# Convert X and Y to Bohr radii. Reshape the arrays
xs = reduce(vcat, XS)
ys = reduce(vcat, YS)
#x and y axis of the spectral map
X = d1[1] .* xs + d2[1] .* ys
Y = d1[2] .* xs + d2[2] .* ys
res = @showprogress pmap((x, y) -> spectral_bulk(ω, Location(x, y), s), XS, YS) #Computation, Get the results
signal = reduce(vcat, res)
fig = Figure(resolution = (1000, 1000))
ax =
    fig[1, 1] = Axis(
        fig,
        xlabel = "x/nm",
        ylabel = "y/nm",
        xlabelpadding = 0,
        ylabelpadding = 0,
        xlabelsize = 16,
        ylabelsize = 16,
        title = "FO map",
        xticklabelsize = 14,
        yticklabelsize = 14,
        aspect = DataAspect(),
        xticklabelfont = "serif-roman",
        yticklabelfont = "serif-roman",
        xlabelfont = "serif-italic",
        ylabelfont = "serif-italic",
    )

sc = CairoMakie.scatter!(
    ax,
    X .* a0 / 10,
    Y .* a0 / 10,
    color = signal .- signal[1],
    strokewidth = 0,
    marker = '◼',
    markersize = 3,
    colormap = :vik,
    colorrange = (-.1, 0.1),
)
fig

save("Spectral_Single_Defect_005eV.pdf", fig)


text:
function litesample(m, spl, N; discard_initial=0, thinning=1, buffersize=50, exclude=[])
  # Run MCMC for `discard_initial` iterations.
  chain = sample(m, spl, 1, save_state=true, discard_initial=discard_initial);

  # Get parameter names.
  all_params = chain.name_map[:parameters]
  excluded_params = collect(Iterators.flatten(namesingroup(chain, p) for p in exclude))
  tracked_params = [filter(x -> !(x in excluded_params), all_params);
                    chain.name_map[:internals]]

  # Vector to store chains.
  cs = [chain[tracked_params]]

  # Sample in chunks. Every `buffersize` samples, discard the excluded parameters.
  remainder = mod(N - 1, buffersize)
  num_chunks = let
    nc = div(N - 1, buffersize)
    remainder == 0 ? nc : nc + 1
  end
  for i in ProgressBar(1:num_chunks)
    bs = (i == num_chunks && remainder > 0) ? remainder : buffersize
    chain = resume(chain, bs, save_state=true, thinning=thinning, progress=false)

    # Append current small chain (with only desired parameters) to `cs`.
    append!(cs, [chain[tracked_params]])
  end

  # Return the concatenated chain (with only tracked parameters).
  return cat(cs...)
end

max_stars_repo_name: luiarthur/CytofDensityEstimation

max_issues_repo_name: luiarthur/CytofDensityEstimation

max_forks_repo_name: luiarthur/CytofDensityEstimation