text:
using GeohashHilbert
using Random
using Test
using CSV

const GHH = GeohashHilbert
const ALL_BITS_PER_CHAR = [2, 4, 6]

randlat() = -90 + 180 * rand()
randlon() = -180 + 360 * rand()
randprec() = rand(1:10)

# converting between int/string and back should reproduce starting values
function test_int_str_conversion()
    for _ in 1:200 # 200 independent tests
        x = rand(0:50_000)
        bpc = rand([2,4,6])
        base = 2^bpc
        chars_needed = ceil(Int, log(base, x + 1))
        nchar = rand(chars_needed : (chars_needed + 5))
        x_str = GHH.int_to_str(x, nchar, bpc)
        @test length(x_str) == nchar
        x_prime = GHH.str_to_int(x_str, bpc)
        @test x == x_prime
    end
    return nothing
end

# converting between xy and integer should be lossless
function test_int_xy_conversion()
    # many independent random tests of normal behavior
    for _ in 1:1000
        k = rand(2:20)
        n = 2^k
        int = rand(0:(n^2 - 1))
        x, y = GHH.int_to_xy(int, n)
        int_prime = GHH.xy_to_int(x, y, n)
        @test int_prime == int
    end
    # test illegal input
    @test_throws DomainError GHH.int_to_xy(-1, 8) # t too small
    @test_throws DomainError GHH.int_to_xy(100, 8) # t too large
    return nothing
end

# For lat/lons which are centers of geohash cells, encoding then decoding
# should match input coordinates.
# We can find lat/lons which are centers of cells by encoding and then decoding
# random points.
function test_cell_centers_encode_decode(bits_per_char = 2)
    for _ in 1:50
        lon, lat = randlon(), randlat()
        prec = randprec()
        geohash = GHH.encode(lon, lat, prec, bits_per_char)
        cell_center = GHH.decode(geohash, bits_per_char)
        geohash2 = GHH.encode(cell_center..., prec, bits_per_char)
        @test geohash == geohash2
        cell_center2 = GHH.decode(geohash2, bits_per_char)
        @test cell_center2 == cell_center
    end
    return nothing
end

# Make sure we match Python geohash hilbert on encoding, particularly on edges
# and corners of cells.
function test_match_python_encode(bits_per_char = 2)
    # python_hashes.csv has columns lon, lat, prec, bpc [bits per char], geohash
    typedict = Dict(
        :lon => Float64,
        :lat => Float64,
        :prec => Int,
        :bpc => Int,
        :geohash => String
    )
    python_hashes = CSV.File(joinpath(@__DIR__, "python_hashes.csv"); types = typedict)
    for row in python_hashes
        julia_hash = GHH.encode(row.lon, row.lat, row.prec, row.bpc)
        @test julia_hash == row.geohash
    end
    return nothing
end

# Illegal arguments should raise exceptions.
# This is not an exhaustive list of all kinds of illegal args.
function test_illegal_arguments()
    @test_throws Exception GHH.int_to_str(5, 5, 3) # 3 illegal bits per char
    @test_throws Exception GHH.str_to_int("hey there", 2) # illegal characters
    @test_throws Exception GHH.str_to_int("0123123", 3) # illegal bits per char
    @test_throws DomainError encode(-200, 0, 4, 4) # illegal longitude
    @test_throws DomainError encode(0, 100, 4, 4) # illegal latitude
    @test_throws DomainError encode(0, 0, 0, 4) # illegal precision
    @test_throws DomainError encode(0, 0, 11, 6) # too much precision
    @test_throws Exception encode(0, 0, 2, -1) # illegal bits per char
    @test_throws DomainError GHH.int_to_xy(16, 4) # first argument is too large
    @test_throws DomainError GHH.find_quadrant(5, GHH.ULeft) # illegal quadrant
    @test_throws DomainError GHH.xy_to_int(5, 1, 4) # x too large
    @test_throws DomainError GHH.xy_to_int(2, 0, 4) # y too small
end

println("Greetings tester; your test will now begin.")
Random.seed!(47)
test_int_str_conversion()
test_int_xy_conversion()
for bpc in ALL_BITS_PER_CHAR
    test_cell_centers_encode_decode(bpc)
end
test_match_python_encode()
test_illegal_arguments()
println("Great job, you passed!")


text:
"""
This is the GLViualize Test suite.
It tests all examples in the example folder and has the options to create
docs from the examples.
"""
module GLTest

using GLAbstraction, GLWindow, GLVisualize
using FileIO, GeometryTypes, Reactive
#using GLVisualize.ComposeBackend

const number_of_frames = 360
const interactive_time = 2.0
const screencast_folder = joinpath(homedir(), "glvisualize_screencast")#Pkg.dir("GLVisualizeDocs", "docs", "media")
!isdir(screencast_folder) && mkdir(screencast_folder)

function render_fr(window)
    render_frame(window)
    pollevents()
    swapbuffers(window)
end

function record_test(window, timesignal, nframes=number_of_frames)
    push!(timesignal, 0f0)
    yield()
    render_fr(window) # make sure we start with a valid image
    yield()
    frames = []
    for frame in 1:nframes
        push!(timesignal, frame/nframes)
        render_fr(window)
        push!(frames, screenbuffer(window))
    end
    frames
end
function record_test_static(window)
    yield()
    render_fr(window) # make sure we start with a valid image
    sleep(0.1)
    yield()
    render_fr(window)
    yield()
    render_fr(window)
    return screenbuffer(window)
end
function record_test_interactive(window, timesignal, total_time=interactive_time)
    frames = []
    add_mouse(window)
    push!(timesignal, 0f0)
    for i=1:2 # warm up
        render_fr(window)
        yield()
    end
    start_time = time()
    while time()-start_time < total_time
        push!(timesignal, (start_time-time())/3.0)
        render_fr(window)
        push!(frames, screenbuffer(window))
    end

    frames
end

non_working_list = []

"""
 include the example in it's own module
 to avoid variable conflicts.
 this can be done only via eval.
"""
function include_in_module(name::Symbol, include_path)
    eval(:(
        module $(name)
            using GLTest, Reactive

            const runtests   = true
            const window     = GLTest.window
            const timesignal = Signal(0.0f0)

           # const composebackend = GLTest.composebackend

            include($include_path)
        end
    ))
end
function test_include(path, window)
    try
        println("trying to render $path")
        name = basename(path)[1:end-3] # remove .jl
        # include the example file in it's own module
        test_module = include_in_module(symbol(name), path)
        for (camname, cam) in window.cameras
            # don't center non standard cams
            !in(camname, (:perspective, :orthographic_pixel)) && continue
            center!(cam, renderlist(window))
        end
        # only when something was added to renderlist
        if !isempty(renderlist(window)) || !isempty(window.children)
            if isdefined(test_module, :record_interactive)
                frames = record_test_interactive(window, test_module.timesignal)
            elseif isdefined(test_module, :static_example)
                frames = record_test_static(window)
            else
                frames = record_test(window, test_module.timesignal)
            end
            println("recorded successfully: $name")
            create_video(frames, name, screencast_folder, 1)
        end
    catch e
        println("################################################################")
        bt = catch_backtrace()
        ex = CapturedException(e, bt)
        println("ERROR in $path")
        showerror(STDERR, ex)
        println("\n################################################################")
        push!(non_working_list, path)
    finally
        empty!(window.children)
        empty!(window)
        window.color = RGBA{Float32}(1,1,1,1)
        #empty!(window.cameras)
    end
end

function make_tests(path::AbstractString)
    if isdir(path)
        if basename(path) != "compose" && basename(path) != "gpgpu"
            make_tests(map(x->joinpath(path, x), readdir(path)))
        end
    elseif isfile(path) && endswith(path, ".jl")
        test_include(path, window)
    end
    nothing # ignore other cases
end
function make_tests(directories::Vector)
    for dir in directories
        make_tests(dir)
    end
end

include("mouse.jl")

window = glscreen(resolution=(300, 300))
#composebackend = ComposeBackend.GLVisualizeBackend(window)

const make_docs  = true
srand(777) # set rand seed, to get the same results for tests that use rand

make_tests(Pkg.dir("GLVisualize", "examples"))

isfile("non_working.txt") && rm("non_working.txt")
for elem in non_working_list
    println(elem)
end
open("non_working.txt", "w") do io
    for elem in non_working_list
        println(io, elem)
    end
end

end

using GLTest

ext: jl


text:
function OrderedEigenDecomposition(arg0::RealMatrix)
    return OrderedEigenDecomposition((RealMatrix,), arg0)
end

function get_vt(obj::OrderedEigenDecomposition)
    return jcall(obj, "getVT", RealMatrix, ())
end


text:
# ---
# title: 166. Fraction to Recurring Decimal
# id: problem166
# author: Tian Jun
# date: 2020-10-31
# difficulty: Medium
# categories: Hash Table, Math
# link: <https://leetcode.com/problems/fraction-to-recurring-decimal/description/>
# hidden: true
# ---
#
# Given two integers representing the `numerator` and `denominator` of a
# fraction, return _the fraction in string format_.
#
# If the fractional part is repeating, enclose the repeating part in
# parentheses.
#
# If multiple answers are possible, return **any of them**.
#
# It is **guaranteed** that the length of the answer string is less than `104`
# for all the given inputs.
#
#
#
# **Example 1:**
#
#
#
#     Input: numerator = 1, denominator = 2
#     Output: "0.5"
#
#
# **Example 2:**
#
#
#
#     Input: numerator = 2, denominator = 1
#     Output: "2"
#
#
# **Example 3:**
#
#
#
#     Input: numerator = 2, denominator = 3
#     Output: "0.(6)"
#
#
# **Example 4:**
#
#
#
#     Input: numerator = 4, denominator = 333
#     Output: "0.(012)"
#
#
# **Example 5:**
#
#
#
#     Input: numerator = 1, denominator = 5
#     Output: "0.2"
#
#
#
#
# **Constraints:**
#
#   * `-231 <= numerator, denominator <= 231 - 1`
#   * `denominator != 0`
#
#
## @lc code=start
using LeetCode

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


text:
@doc raw"""
`SPSDE`: Stratonovich Split Partitioned Stochastic Differential Equation

Defines a partitioned stochastic differential initial value problem
```math
\begin{align*}
\dq (t) &=   v(t, q(t)) \, dt + B(t, q(t)) \circ dW , & q(t_{0}) &= q_{0} ,
\dp (t) &= [ f1(t, q(t)) + f2(t, q(t)) ] \, dt + [ G1(t, q(t)) + G2(t, q(t)) ] \circ dW , & p(t_{0}) &= p_{0}
\end{align*}
```
with the drift vector fields ``v`` and ``fi``, diffusion matrices ``B`` and ``Gi``,
initial conditions ``q_{0}`` and ``p_{0}``, the dynamical variables ``(q,p)`` taking
values in ``\mathbb{R}^{d} \times \mathbb{R}^{d}``, and the m-dimensional Wiener process W

### Fields

* `d`:  dimension of dynamical variable ``q`` and the vector fields ``vi``
* `m`:  dimension of the Wiener process
* `ni`: number of initial conditions
* `ns`: number of sample paths
* `v` :  function computing the drift vector field for the position variable q
* `f1`:  function computing the drift vector field for the momentum variable p
* `f2`:  function computing the drift vector field for the momentum variable p
* `B` :  function computing the d x m diffusion matrix for the position variable q
* `G1`:  function computing the d x m diffusion matrix for the momentum variable p
* `G2`:  function computing the d x m diffusion matrix for the momentum variable p
* `t₀`: initial time
* `q₀`: initial condition for dynamical variable ``q`` (may be a random variable itself)
* `p₀`: initial condition for dynamical variable ``p`` (may be a random variable itself)

The functions `v`, `f`, 'B' and `G`, providing the drift vector fields and diffusion matrices, take four arguments,
`v(t, q, p, v)`, `f(t, q, p, f)`, `B(t, q, p,  B)` and `G(t, q, p, G)`, where `t` is the current time, `(q, p)` is the
current solution vector, and `v`, `f`, 'B' and `G` are the variables which hold the result
of evaluating the vector fields ``v``, ``f`` and the matrices ``B``, ``G`` on `t` and `(q,p)`.

### Example

```julia
    function v(λ, t, q, v)
        v[1] = λ*q[1]
        v[2] = λ*q[2]
    end

    function B(μ, t, q, B)
        B[1] = μ*q[1]
        B[2] = μ*q[2]
    end

    t₀ = 0.
    q₀ = [1., 1.]
    λ  = 2.
    μ  = 1.

    v_sde = (t, q, v) -> v(λ, t, q, v)
    B_sde = (t, q, B) -> B(μ, t, q, B)

    sde = SDE(v_sde, B_sde, t₀, q₀)
```
"""
struct SPSDE{dType <: Number, tType <: Number, vType <: Function, f1Type <: Function, f2Type <: Function, BType <: Function, G1Type <: Function, G2Type <: Function, pType, N} <: AbstractEquationPSDE{dType, tType}
    d::Int
    m::Int
    ni::Int
    ns::Int
    v ::vType
    f1::f1Type
    f2::f2Type
    B ::BType
    G1::G1Type
    G2::G2Type
    t₀::tType
    q₀::Array{dType, N}           #Initial condition: N=1 - single deterministic, N=2 - single random or multiple deterministic, N=3 - multiple deterministic
    p₀::Array{dType, N}
    parameters::pType
    periodicity::Vector{dType}

    function SPSDE(m, ns, v::vType, f1::f1Type, f2::f2Type,
                    B::BType, G1::G1Type, G2::G2Type, t₀::tType,
                    q₀::AbstractArray{dType}, p₀::AbstractArray{dType};
                    parameters=nothing, periodicity=zeros(dType,size(q₀,1))) where {
                    dType <: Number, tType <: Number, vType <: Function, f1Type <: Function, f2Type <: Function,
                    BType <: Function, G1Type <: Function, G2Type <: Function}

        @assert size(q₀)  == size(p₀)
        @assert ndims(q₀) == ndims(p₀)

        N  = ndims(q₀)
        d  = size(q₀,1)
        ni = size(q₀,2)

        @assert N ∈ (1,2)
        @assert ni ≥ 1
        @assert ns ≥ 1
        @assert ni == 1 || ns == 1
        # either multiple deterministic initial conditions and one sample path
        # or one deterministic initial condition and multiple sample paths

        if !(length(periodicity) == d)
            periodicity = zeros(dType, d)
        end

        new{dType,tType,vType,f1Type,f2Type,BType,G1Type,G2Type,typeof(parameters),N}(d, m, ni, ns, v, f1, f2, B, G1, G2, t₀, q₀, p₀, parameters, periodicity)
    end
end

function SPSDE(m::Int, ns::Int, v::Function, f1::Function, f2::Function,
                                B::Function, G1::Function, G2::Function,
                                q₀::AbstractArray{DT,N}, p₀::AbstractArray{DT,N}; kwargs...) where {DT,N}
    SPSDE(m, ns, v, f1, f2, B, G1, G2, zero(DT), q₀, p₀; kwargs...)
end

Base.hash(sde::SPSDE, h::UInt) = hash(sde.d, hash(sde.m, hash(sde.ni, hash(sde.ns,
                                 hash(sde.v, hash(sde.f1, hash(sde.f2, hash(sde.B, hash(sde.G1, hash(sde.G2,
                                 hash(sde.t₀, hash(sde.q₀, hash(sde.p₀, hash(sde.parameters, hash(sde.periodicity, h)))))))))))))))

Base.:(==)(sde1::SPSDE, sde2::SPSDE) = (
                                sde1.d == sde2.d
                             && sde1.m == sde2.m
                             && sde1.ni == sde2.ni
                             && sde1.ns == sde2.ns
                             && sde1.v  == sde2.v
                             && sde1.f1 == sde2.f1
                             && sde1.f2 == sde2.f2
                             && sde1.B  == sde2.B
                             && sde1.G1 == sde2.G1
                             && sde1.G2 == sde2.G2
                             && sde1.t₀ == sde2.t₀
                             && sde1.q₀ == sde2.q₀
                             && sde1.p₀ == sde2.p₀
                             && sde1.parameters  == sde2.parameters
                             && sde1.periodicity == sde2.periodicity)

function Base.similar(sde::SPSDE, q₀::AbstractArray, p₀::AbstractArray, ns::Int)
    similar(sde, sde.t₀, q₀, p₀, ns)
end

function Base.similar(sde::SPSDE, q₀::AbstractArray, p₀::AbstractArray)
    similar(sde, sde.t₀, q₀, p₀)
end

function Base.similar(sde::SPSDE, t₀::TT, q₀::AbstractArray{DT,N}, p₀::AbstractArray{DT,N}, ns::Int=(N > 1 ? 1 : sde.ns)) where {DT <: Number, TT <: Number, N}
    @assert size(q₀) == size(p₀)
    @assert sde.d == size(q₀,1)
    SPSDE(sde.m, ns, sde.v, sde.f1, sde.f2, sde.B, sde.G1, sde.G2, t₀, q₀, p₀; parameters=sde.parameters, periodicity=sde.periodicity)
end

@inline Base.ndims(sde::SPSDE) = sde.d

@inline periodicity(equation::SPSDE) = equation.periodicity


text:
export variational, gd, adagrad

# TODO: Check this interacts correctly with mem/store/XRP etc.

type Variational <: Ctx
    params::Dict # The variational parameters.
    gradients::Dict # Local gradients at each ERP.
    variationalscore::Float64
    score::Float64 # Score.
end

Variational() = Variational(Dict(), Dict(), 0, 0)

function sample(s::Store, k::Function, address, erp::ERP, ctx::Variational)
    if !haskey(ctx.params, address)
        # Initialize variational parameters. Distributions.jl returns
        # a tuple of params. Convert to an array in order to use + to
        # accumulate.
        ctx.params[address] = [params(erp)...]
    end

    # Distributions.jl is implemented such that the following will
    # always do the right thing.
    erpv = typeof(erp)(ctx.params[address]...)

    # Sample from the variational program.
    value = rand(erpv)

    @assert !haskey(ctx.gradients, address)
    ctx.gradients[address] = gradient(erpv, value)

    ctx.score += score(erp, value)
    ctx.variationalscore += score(erpv, value)

    k(s,value)
end

function factor(s::Store, k::Function, address, score, ctx::Variational)
    ctx.score += score
    k(s,nothing)
end

variational_exit(s::Store, value) = value

function variational(s::Store, k::Function, address, comp::Function, numsamples=10, maxsteps=100, optimizer=adagrad())
    global ctx
    ctxold, ctx = ctx, Variational()
    ctxreturn = nothing
    init_thunk = () -> comp(s, variational_exit, address)
    converged = false

    try
        for curstep in 1:maxsteps

            L = 0.0
            gradients = Dict()

            for _ in 1:numsamples
                # Reset context state ready for next execution of the
                # variational program, but retain the variational
                # parameters.
                empty!(ctx.gradients)
                ctx.variationalscore = ctx.score = 0.0

                # Run the program.
                value = trampoline(init_thunk)

                # Accumulate objective/gradients.
                weight = ctx.variationalscore - ctx.score
                L += weight
                for (addr, grad) in ctx.gradients
                    gradients[addr] = get(gradients, addr, 0.) + weight*grad
                end
            end

            L /= numsamples
            for (addr, _) in gradients
                gradients[addr] /= numsamples
            end

            #println(L)

            if optimizer(ctx.params, gradients)
                info("Variational inference converged after $curstep steps.")
                converged = true
                break
            end
        end

    finally
        ctx, ctxreturn = ctxold, ctx
    end

    converged || info("Variational inference did not converge after $maxsteps steps.")
    #println(ctxreturn.params)

    # I'm not at all convinced that this is a fully general solution
    # to the problem of creating a variational program from the
    # learned parameters and the thunk passed to inference. You can
    # use this to draw samples and you can pass it to enum, but I've
    # not thought carefully enough about it to be convinced it will
    # work elsewhere.

    partial(k,s)() do s::Store, k::Function, curaddress
        # This is the body of the returned variational program.
        global ctx
        rewritten_params = rewrite_param_addresses(ctxreturn.params, address, curaddress)
        ctx = VarExec(ctx, rewritten_params)
        partial(comp,s)(curaddress) do s2, value
            # This is the body of the continuation passed to the program.
            ctx = ctx.parent
            k(s2,value)
        end
    end

end

# The program returned by variational inference works by executing the
# original program in a context (co-routine in webppl) which
# intercepts calls to sample, substituting the original ERP for the
# variational ERP.

type VarExec <: Ctx
    parent::Ctx
    params::Dict
end

function sample(s::Store, k::Function, address, erp::ERP, varctx::VarExec)
    # Switch out the ERP for the variational ERP.
    erpv = typeof(erp)(varctx.params[address]...)
    partial(sample,s)(address,erpv,varctx.parent) do s2, value
        # When performing enumeration over a variational program the
        # context will have been reset when the variational program is
        # resumed. It's therefore necessary to reset the context to
        # the variational context here.
        global ctx
        ctx = varctx
        k(s2,value)
    end
end

factor(s::Store, k::Function, address, score, ctx::VarExec) = k(s,nothing)

# It's necessary to re-write the addresses of the params dictionary
# when executing the variational program returned by inference. This
# is because the variational program will be executed from a different
# point in the program than infererence was performed at. This needs
# to be accounted for when looking up the variational parameters for
# an ERP during execution of the learned variational program.

function rewrite_param_addresses(params, oldprefix, newprefix)
    oldp = reverse(oldprefix)
    newp = reverse(newprefix)
    rewrite = address -> reverse(rewrite_address(reverse(address), oldp, newp))
    newparams = Dict()
    for (addr, param) in params
        newparams[rewrite(addr)] = param
    end
    newparams
end

function rewrite_address(address, oldprefix, newprefix)
    # All 3 args are expected to be reversed by the caller.
    if isempty(oldprefix)
        cat(newprefix, address)
    else
        @assert first(oldprefix) == first(address)
        rewrite_address(tail(address), tail(oldprefix), newprefix)
    end
end

# Optimizers.

# Gradient descent.
gd(stepsize=0.1) = (params, gradients) -> gdstep!(params, gradients, stepsize)
gd(s::Store, k::Function, address, args...) = k(s, gd(args...))

function gdstep!(params, gradients, stepsize)
    for (addr, grad) in gradients
        params[addr] -= stepsize * grad
    end
    false # TODO: Test for convergence.
end

function adagrad(stepsize=0.1, eps=1e-6)
    history = Dict()
    delta_avg = 0. # Running averge of the magnitude of the step taken.
    (params, gradients) -> begin
        delta = adagradstep!(params, gradients, history, stepsize)
        delta_avg = 0.9*delta_avg + 0.1*delta
        delta_avg < eps # Convergence test.
    end
end

adagrad(s::Store, k::Function, address, args...) = k(s, adagrad(args...))

function adagradstep!(params, gradients, history, stepsize)
    # This assumes that any parameter not in the gradients dictionary
    # has gradient zero gradient.

    # TODO: Is there a better way to test for convergence? I'm not
    # sure this makes much sense for all parameter spaces. e.g. When a
    # parameters live in [0,1] rather than ℝ.

    # TODO: Figure out a principled (and generally applicable) way to
    # prevent updates setting parameters to nonsensical values.

    delta = 0.
    numdims = 0
    for (addr, grad) in gradients
        h = get(history, addr, 0.0) + grad.^2
        history[addr] = h
        step = (stepsize./√h) .* grad
        params[addr] -= step
        delta += sum(step.^2)
        numdims += length(step)
    end
    delta / numdims
end


text:
# This file contains functions for the Revenue Efficiency Hölder DEA model
"""
    RevenueHolderDEAModel
An data structure representing a revenue Hölder DEA model.
"""
struct RevenueHolderDEAModel <: AbstractRevenueDEAModel
    n::Int64
    m::Int64
    s::Int64
    l::Union{Int64,Float64}
    isweighted::Bool
    monetary::Bool
    dmunames::Union{Vector{String},Nothing}
    rts::Symbol
    eff::Vector
    lambda::SparseMatrixCSC{Float64, Int64}
    techeff::Vector
    alloceff::Vector
    normalization::Vector
    Xtarget::Matrix
    Ytarget::Matrix
end

"""
    dearevenueholder(X, Y, W; l)
Compute revenue efficiency using data envelopment analysis for
inputs `X`, outputs `Y` and price of outputs `P`.

# Hölder norm `l` specification
- `1`.
- `2`.
- `Inf`.

# Optional Arguments
- `rts=:VRS`: chooses variable returns to scale. For constant returns to scale choose `:CRS`.
- `names`: a vector of strings with the names of the decision making units.

# Examples
```jldoctest
julia> X = [1; 1; 1; 1; 1; 1; 1; 1];

julia> Y = [7 7; 4 8; 8 4; 3 5; 3 3; 8 2; 6 4; 1.5 5];

julia> P = [1 1; 1 1; 1 1; 1 1; 1 1; 1 1; 1 1; 1 1];

julia> dearevenueholder(X, Y, P, l = 1)
Revenue Hölder L1 DEA Model
DMUs = 8; Inputs = 1; Outputs = 2
Orientation = Output; Returns to Scale = VRS
─────────────────────────────────
   Revenue  Technical  Allocative
─────────────────────────────────
1      0.0        0.0         0.0
2      2.0        0.0         2.0
3      2.0        0.0         2.0
4      6.0        3.0         3.0
5      8.0        5.0         3.0
6      4.0        0.0         4.0
7      4.0        2.0         2.0
8      7.5        3.0         4.5
─────────────────────────────────
```
"""
function dearevenueholder(X::Union{Matrix,Vector}, Y::Union{Matrix,Vector},
    P::Union{Matrix,Vector};
    l::Union{Int64,Float64}, weight::Bool = false,
    rts::Symbol = :VRS, monetary::Bool = false,
    names::Union{Vector{String},Nothing} = nothing,
    optimizer::Union{DEAOptimizer,Nothing} = nothing)::RevenueHolderDEAModel

    # Check parameters
    nx, m = size(X, 1), size(X, 2)
    ny, s = size(Y, 1), size(Y, 2)

    np, sp = size(P, 1), size(P, 2)

    if nx != ny
        throw(DimensionMismatch("number of rows in X and Y ($nx, $ny) are not equal"));
    end
    if np != ny
        throw(DimensionMismatch("number of rows in P and Y ($np, $ny) are not equal"));
    end
    if sp != s
        throw(DimensionMismatch("number of columns in P and Y ($sp, $s) are not equal"));
    end

    if l != 1 && l != 2 && l != Inf
        throw(ArgumentError("l must by :1, :2, or :Inf"));
    end

    # Default optimizer
    if optimizer === nothing
        optimizer = DEAOptimizer(:LP)
    end

    # Get maximum revenue targets and lambdas
    n = nx

    Xtarget = X[:,:]
    Ytarget, rlambdaeff = deamaxrevenue(X, Y, P, rts = rts, dispos = :Strong, optimizer = optimizer)

    # Revenue, technical and allocative efficiency
    refficiency  = vec(sum(P .* Ytarget, dims = 2)  .- sum(P .* Y, dims = 2))

    if weight
        if l == 1
            normalization = maximum(P .* Y, dims = 2)
        elseif l == 2
            normalization = sqrt.(sum((P .* Y ).^2, dims = 2))
        elseif l == Inf
            normalization = sum(P .* Y, dims = 2)
        end
    else
        if l == 1
            normalization = maximum(P, dims = 2)
        elseif l == 2
            normalization = sqrt.(sum((P ).^2, dims = 2))
        elseif l == Inf
            normalization = sum(P, dims = 2)
        end
    end
    normalization = vec(normalization)

    techefficiency = efficiency(deaholder(X, Y, l = l, weight = weight, orient = :Output, rts = rts, slack = false, optimizer = optimizer))

    if monetary
        techefficiency = techefficiency .* normalization
    else
        refficiency = refficiency ./ normalization
    end

    allocefficiency = refficiency - techefficiency

    return RevenueHolderDEAModel(n, m, s, l, weight, monetary, names, rts, refficiency, rlambdaeff, techefficiency, allocefficiency, normalization, Xtarget, Ytarget)
end

function Base.show(io::IO, x::RevenueHolderDEAModel)
    compact = get(io, :compact, false)

    n = nobs(x)
    m = ninputs(x)
    s = noutputs(x)
    l = x.l
    isweighted = x.isweighted
    dmunames = names(x)

    eff = efficiency(x)
    techeff = efficiency(x, :Technical)
    alloceff = efficiency(x, :Allocative)

    if !compact
        print(io, "Revenue Hölder L", string(l), " DEA Model \n")
        print(io, "DMUs = ", n)
        print(io, "; Inputs = ", m)
        print(io, "; Outputs = ", s)
        print(io, "\n")
        print(io, "Orientation = Output")
        print(io, "; Returns to Scale = ", string(x.rts))
        print(io, "\n")
        if isweighted
            print(io, "Weighted (weakly) Hölder distance function \n")
        end
        show(io, CoefTable(hcat(eff, techeff, alloceff), ["Revenue", "Technical", "Allocative"], dmunames))
    end

end


text:
function week_test_unit()
    test_shift_count_validation()
    test_consecutive()
    test_consecutive_with_preceding()
    test_week_with_day_off()
    test_courier_incorrect_availability()
end

function test_shift_count_validation()
    # Shift counts have to be reasonable

    # Setup
    env = {
        "coverage"  => Array[
            [1*ones(Int, 8)],
            [1*ones(Int, 8)],
            [zeros(Int, 8)],
        ],
        "time_between_coverage" => 12,
    }

    # Shift count infeasible
    employees = {
        "a" => {
            "hours_min" => 14,
            "hours_max" => 18,
            "shift_count_min" => 2,
            "shift_count_max" => 2,
            "availability"  => Array[
                [ones(Int,8)],
                [ones(Int,8)],
                [zeros(Int,8)],
            ],
            "longest_availability" => 8*ones(Int, 8),
        },
    }

    # (don't overwrite our good variables)
    ok, message, _ = build_week(employees, env)
    # It should require shift_time_min and shift_time_max
    @test(!ok)

    env["shift_time_min"] = 7
    env["shift_time_max"] = 9
    ok, employees, env = build_week(employees, env)
    @test(ok)
    ok, message = validate_input(employees, env)
    @test(ok)

    # shift_count_min has to be in bounds
    employees["a"]["shift_count_min"] = 3
    ok, message = validate_input(employees, env)
    @test(!ok)

    # shift_count_max has to be shorter than week
    employees["a"]["shift_count_min"] = 2 # revert
    employees["a"]["shift_count_max"] = 4
    ok, message = validate_input(employees, env)
    @test(!ok)

    # Test hours constraint
    employees["a"]["shift_count_max"] = 3
    ok, message = validate_input(employees, env)
    @test(!ok)
end

function test_consecutive()
    # Make sure consecutive shifts work
    ok, _ = assign_employees_to_days(test_consecutive_employees, test_consecutive_env, true)
    @test ok == true
end

function test_consecutive_with_preceding()
    # Make sure consecutive_with_preceding shifts work
    ok, employees = assign_employees_to_days(test_consecutive_with_preceding_employees, test_consecutive_with_preceding_env, true)
    @test ok == true
    # It's set up so "e" muet work these days
    @test employees["e"]["days_assigned"][1] == 0
    @test employees["e"]["days_assigned"][2] == 1
    @test employees["e"]["days_assigned"][3] == 1
    @test employees["e"]["days_assigned"][4] == 0
end

function test_week_with_day_off()
    consec_days_off = false # by design
    empty_day = 3 # when there is zero coverage
    ok, employees = assign_employees_to_days(test_day_off_employees, test_day_off_env, consec_days_off)
    @test ok == true
    for e in keys(employees)
        @test employees[e]["days_assigned"][empty_day] == 0
    end
end

max_stars_repo_name: shdann/autoshift

max_issues_repo_name: shdann/autoshift

max_forks_repo_name: shdann/autoshift


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, Pkg

name = "TempestRemap"
version = v"2.1.1"
sources = [
    ArchiveSource("https://github.com/ClimateGlobalChange/tempestremap/archive/refs/tags/v$(version).tar.gz",
                  "f5ea21f82b358ba127550fc1f49e701cba0379d22ce030c274135109f678b980"),
]

script = raw"""
cd ${WORKSPACE}/srcdir/tempestremap*

export CPPFLAGS="-I${includedir}"
export LDFLAGS="-L${libdir}"
export LDFLAGS_MAKE="${LDFLAGS}"
CONFIGURE_OPTIONS=""

autoreconf -fiv
mkdir -p build && cd build

../configure \
  --prefix=${prefix} \
  --host=${target} \
  --with-blas=blastrampoline \
  --with-lapack=blastrampoline \
  --with-netcdf=${prefix} \
  --with-hdf5=${prefix} \
  --enable-shared \
  --disable-static

make LDFLAGS="${LDFLAGS_MAKE}" -j${nproc} all
make install

install_license ../LICENSE
"""

# Note: We are restricted to the platforms that NetCDF supports, the library is Unix only
platforms = [
    Platform("x86_64", "linux"),
    Platform("aarch64", "linux"; libc="glibc"),
    Platform("x86_64", "macos"),
]
platforms = expand_cxxstring_abis(platforms)

products = [
    LibraryProduct("libTempestRemap", :libTempestRemap),
    ExecutableProduct("AnalyzeMap", :AnalyzeMap_exe),
    ExecutableProduct("ApplyOfflineMap", :ApplyOfflineMap_exe),
    ExecutableProduct("CalculateDiffNorms",  :CalculateDiffNorms_exe),
    ExecutableProduct("CoarsenRectilinearData", :CoarsenRectilinearData_exe),
    ExecutableProduct("ConvertExodusToSCRIP", :ConvertExodusToSCRIP_exe),
    ExecutableProduct("ConvertSCRIPToExodus", :ConvertSCRIPToExodus_exe),
    ExecutableProduct("GenerateCSMesh", :GenerateCSMesh_exe),
    ExecutableProduct("GenerateGLLMetaData", :GenerateGLLMetaData_exe),
    ExecutableProduct("GenerateICOMesh", :GenerateICOMesh_exe),
    ExecutableProduct("GenerateLambertConfConicMesh", :GenerateLambertConfConicMesh_exe),
    ExecutableProduct("GenerateOfflineMap", :GenerateOfflineMap_exe),
    ExecutableProduct("GenerateOverlapMesh", :GenerateOverlapMesh_exe),
    ExecutableProduct("GenerateOverlapMesh_v1", :GenerateOverlapMesh_v1_exe),
    ExecutableProduct("GenerateRLLMesh", :GenerateRLLMesh_exe),
    ExecutableProduct("GenerateRectilinearMeshFromFile", :GenerateRectilinearMeshFromFile_exe),
    ExecutableProduct("GenerateStereographicMesh", :GenerateStereographicMesh_exe),
    ExecutableProduct("GenerateTestData",  :GenerateTestData_exe),
    ExecutableProduct("GenerateTransectMesh",  :GenerateTransectMesh_exe),
    ExecutableProduct("GenerateTransposeMap", :GenerateTransposeMap_exe),
    ExecutableProduct("GenerateUTMMesh", :GenerateUTMMesh_exe),
    ExecutableProduct("GenerateVolumetricMesh", :GenerateVolumetricMesh_exe),
    ExecutableProduct("MeshToTxt", :MeshToTxt_exe),
    ExecutableProduct("RestructureData", :RestructureData_exe),
    ExecutableProduct("ShpToMesh", :ShpToMesh_exe),
    ExecutableProduct("VerticalInterpolate", :VerticalInterpolate_exe),
]

dependencies = [
    Dependency("libblastrampoline_jll"),
    Dependency("NetCDF_jll"),
    Dependency("HDF5_jll"),
    # The following is adapted from NetCDF_jll
    BuildDependency(PackageSpec(; name="MbedTLS_jll", version="2.24.0")),
]

build_tarballs(ARGS, name, version, sources, script, platforms, products, dependencies;
    julia_compat="1.7",
)

max_stars_repo_name: sharanry/Yggdrasil

max_issues_repo_name: sharanry/Yggdrasil

max_forks_repo_name: sharanry/Yggdrasil


text:
using Luxor

#=
Gate ref:
- Quantum Circuit Diagrams in LATEX\P11\3.2 Gates
- [QASM: Qubit gate operations](https://www.quantum-inspire.com/kbase/qasm-qubit-gate-operations/)
- [Microsoft.Quantum.Primitive | Microsoft Docs](https://docs.microsoft.com/en-us/qsharp/api/prelude/microsoft.quantum.primitive?view=qsharp-preview)
- [Yao.jl/ConstGateGen.jl at master · QuantumBFS/Yao.jl](https://github.com/QuantumBFS/Yao.jl/blob/master/src/Blocks/ConstGateGen.jl)
=#

#=
    constant
=#
const GateSpacing = 30
const LineSpacing = 40
const ΔX = Point(GateSpacing, 0)
const ΔY = Point(0, LineSpacing)

#=
    help function
=#

"""
    P(x::Int, y::Int=1) :: Point

P function convert (x, y) coordinates to `Point()`.
"""
function P(x::Int, y::Int=1; dx=ΔX, dy=ΔY) :: Point
    @assert x > 0 "x ∈ [1 2 3 ...]"
    @assert y > 0 "y ∈ [1 2 3 ...]"

    O + dx*(x-1) + dy*(y-1)
end

"""
    P() = O

P function default point to origin point `O`.
"""
P() = O

"""
    init_qbit_line()

Draw n lines for n QBits.
"""
function init_qbit_line(nQBits=1, init_state=[]; dx=ΔX, dy=ΔY)

    if init_state != []
        @assert length(init_state)==nQBits "len(init_state) != nQBits"
        for i in 1:nQBits
            state = init_state[i]
            @assert state in [-1 0 1] "state[$i]: $state should use [-1, 0, 1]"
        end
    end

    states = [
        init_state == [] ?
            -1 :
            init_state[i] for
            i in 1:nQBits
    ]

    StartX = -20
    StartY = 0
    EndX = 190
    # TODO: Move those to parameter list.

    LineStartP = Point(StartX, StartY)
    LineEndP = Point(EndX, 0)
    for y in 1:nQBits
        line(LineStartP, LineEndP, :stroke)
        txtQbit(StartX-30, y, states[y])
        LineStartP += ΔY
        LineEndP += ΔY
    end
end

function sub(substr) :: AbstractString
    "$substr"
end

function sup(substr) :: AbstractString
    "$substr"
end

function txtQbit(StartX::Int, lines::Int, init::Int=-1; dy=ΔY)
    @assert lines >= 1 "lines >= 1"
    @assert init in [-1, 0, 1] "Init state should be 0 or 1"

    pos = Point(StartX, 0) + dy*(lines-1)
    initState = init==-1 ? "?" : string(init)
    text = "|" * string(initState) * ">" *
            sub("Q"*string(lines-1))
    # In fact it support HTML code `⟩`
    # ⟩, U+27E9

    # setfont("Helvetica", 24)
    settext(
        text, pos;
        halign = "center",
        valign = "center",
        angle  = 0, # degrees!
        markup = true
    )

end

#=
    Nodes
=#

"""
    NotControlCircle(C::Point, size=:9, color=:"white")

Draw white hollow point represent *Not Control Node*.
"""
function NotControlCircle(C::Point, d=18, color="white")
    r = d/2
    sethue(color)
    circle(C, r, :fill)
    sethue("black")
    circle(C, r, :stroke)
end

"""
    ControlCircle(C::Point, d=10)

Draw black solid point represent *Control Node*.
"""
function ControlCircle(C::Point, d=10)
    r = d/2
    color = "black"
    NotControlCircle(C, r, color)
end

"""
    Not(C::Point, d=18)

Draw a circle containing a cross represent *Not Gate*.
"""
function Not(C::Point, d=18)
    r = d/2
    dY = Point(0, r)
    circle(C, r, :stroke)
    line(C+dY, C-dY, :stroke)
end

function Cross(C::Point, width=18)
    Δ = width/2
    dx = Point(Δ, 0)
    dy = Point(0, Δ)
    lt = C - dx + dy
    rb = C + dx - dy
    line(lt, rb, :stroke)

    rt = C + Δ
    lb = C - Δ
    line(rt, lb, :stroke)
end

#=
    Gates
=#

"""
    gate(C::Point, edge_len=20, txt="H")

Draw simple gates with box.
"""
function gate(C::Point, txt="H", edge_len=20)
    # TODO: support long name gates
    # draw background
    sethue("white")
    box(C, edge_len, edge_len, :fill)

    # draw border
    sethue("black")
    box(C, edge_len, edge_len, :stroke)

    # write text in box
    # sethue("black")
    fontsize(edge_len)
    # fontface("Times New Roman")
    text(
        txt,
        C,
        halign = :center,
        valign = :middle
    )
end
gate(C::Point, txt::Char) = gate(C, string(txt))
gate(C::Point, txt::Char, edge_len) =
    gate(C, string(txt), edge_len)

#= Single Gates
- [ ] Measure

ConstantGate:

- [ ] H Gate: Hadamard transformation
- [ ] I2 Gate:identity operation (no-op)
- [ ] S/S-dag Gate: π/4 phase gate and its conjugate transpose
- [ ] T/T-dag Gate: π/8 phase gate and its conjugate transpose
- [ ] X/Y/Z Gate: Pauli-X/Y/Z Gate

- [ ] P0/P1 Gate
- [ ] Pd/Pu Gate

=#

function Measure(C::Point, high=20)
    # draw background
    sethue("white"); box(C, high*1.5, high, :fill)

    # draw border
    sethue("black"); box(C, high*1.5, high, :stroke)

    # draw arc
    lc = C + Point(0, high/2)
    arc(lc, high*0.6, pi*1.15, pi*1.85)

    # draw pointer
    p1 = C + Point(0, high*0.2)
    p2 = C + Point(high*0.4, -high*0.4)
    line(p1, p2, :stroke)
end

function End(C::Point, high=20)
    p1 = C + Point(high/2, -high/2)
    p2 = C + high/2
    line(p1, p2, :stroke)
end

"""
    MultiQBitGate(QBits::Dict, col::Int)

Draw general multi Qbits gate, you can draw single Qbit too.

Input dict format:
```julia
d = Dict(
    # Node
    1 => "",    # "" or "C" for "Control Node"
    2 => "C",
    3 => "NC"   # "NC" for "Not Control Node"
    6 => "X",   # "X" for "Cross Node"

    # Single Gate
    4 => "N",   # "N" for "Not Gate"
    7 => "SG:X" # start with "SG:", follow 1 char "X"
                # for type "X" single Gate
)
```
"""
function MultiQBitGate(QBits::Dict, col::Int)
    ks = collect(keys(QBits))
    upper = P(col, minimum(ks))
    lower = P(col, maximum(ks))
    line(upper, lower, :stroke)

    for (y, typ) in QBits
        if typ == "" || typ == "C"
            ControlCircle(P(col, y))
        elseif typ == "NC"
            NotControlCircle(P(col, y))
        elseif typ == "N"
            Not(P(col, y))
        elseif typ == "X"
            Cross(P(col, y))
        elseif startswith(typ, "SG:") && length(typ)==4
            gateType = typ[end]
            gate(P(col, y), gateType)
        end
    end
end

#=
ConstantGate
    - [ ] CNOT Gate[2-QBits]
    - [ ] SWAP Gate[2-QBits]
    - [ ] Toffoli Gate[3-QBits]

=#

function CNOT(NNode_y::Int, CNode_y::Int, col::Int)
    MultiQBitGate(
        Dict(NNode_y=>"N", CNode_y=>"C"),
        col
    )
end

function SWAP(d::Dict, col::Int=1)
    throw("Not implement")
end

function Toffoli(d::Dict, col::Int=1)
    throw("Not implement")
end

#=
    using
=#

# @svg begin
# rulers()
# init_qbit_line(8)
#
#
# gate(P(), "α")
# gate(P(2), 'H')
# gate(P(3), "U")
# gate(P(4), "-Z")
# gate(P(2,2), "H")
#
# NotControlCircle(P(1,2))
# ControlCircle(P(1,3))
# Not(P(1,4))
# Cross(P(1,5))
# Measure(P(6, 1))
# End(P(7, 1))
# Measure(P(6, 2))
# gate(P(7, 2), 'H')
#
# MultiQBitGate(Dict(2=>"",3=>"",4=>"NC",5=>"N"), 4)
# MultiQBitGate(
#     Dict(
#         1=>"X",  2=>"",  3=>"",
#         4=>"NC", 5=>"N", 6=>"SG:H",
#         7=>"SG:X", 8=>"SG:ρ"
#     ),
#     5
# )
# end

#= Demo
- [Prepare Greenberger–Horne–Zeilinger state with Quantum Circuit · Yao.jl](https://quantumbfs.github.io/Yao.jl/stable/tutorial/GHZ/#Prepare-Greenberger%E2%80%93Horne%E2%80%93Zeilinger-state-with-Quantum-Circuit-1)
=#
@svg begin

init_qbit_line(4, zeros(Int, 4))

gate(P(), "X")
[gate(P(1, i), 'H') for i in 2:4]
CNOT(1,2,2); CNOT(3,4,2)
CNOT(1,3,3)
CNOT(3,4,4)
[gate(P(5, i), 'H') for i in 1:4]
[Measure(P(6, i)) for i in 1:4]
[End(P(7, i)) for i in 1:4]

end 500 300


text:
#!/home/nmrbox/cwaudby/julia-1.5.0-beta1/bin/julia

function proc(inputname, outputname, Δp1, Δp2)
	td = 2048
	nrelax = 14

	# input phase cycle
	ϕ1 = [0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3, 4, 5, 6] * 2π / 7
	ϕ2 = [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2] * 2π / 3

	nphase = 21

	# sum up echo and anti-echo pathways
	ϕrx1 = -Δp1*ϕ1 - Δp2*ϕ2
	ϕrx2 =  Δp1*ϕ1 + Δp2*ϕ2

	ϕrx1 = exp.(1im * ϕrx1)
	ϕrx2 = exp.(1im * ϕrx2)

	npoints = Int(filesize(inputname)/4 - 512)
	ncomplex = Int(npoints / (td*nphase*2))
	# preallocate data (and dummy header)
	header = zeros(Float32, 512)
	y = zeros(Float32, npoints)

	# read the input file
	open(inputname) do f
	    read!(f, header)
	    read!(f, y)
	end

	y = reshape(y, td, 2, :)
	yc = y[:,1,:] + 1im * y[:,2,:]

	y = reshape(yc, td, nphase, :)
	ϕrx1 = reshape(ϕrx1, 1, nphase, 1)
	ϕrx2 = reshape(ϕrx2, 1, nphase, 1)
	y1 = sum(y .* ϕrx1, dims=2)
	y2 = sum(y .* ϕrx2, dims=2)
	y = y1 + y2
	y = reshape(y, td, ncomplex)

	# read the file
	open(outputname, "w") do f
	    write(f, header)
	    for i=1:ncomplex
			write(f, Float32.(real.(y[:,i])))
			write(f, Float32.(imag.(y[:,i])))
	    end
	end

	run(`sethdr $outputname -yN $nrelax -yT $nrelax`)
end

proc("cube.fid", "cubeQQ.fid", 3, -1)
proc("cube.fid", "cubeDQ.fid", 3, 1)

max_stars_repo_name: chriswaudby/qq-hahnecho

max_issues_repo_name: chriswaudby/qq-hahnecho

max_forks_repo_name: chriswaudby/qq-hahnecho


text:
should_precompile =   true

# Don't edit the following! Instead change the script for `snoop_bot`.
ismultios = true
ismultiversion = true
# precompile_enclosure
@static if !should_precompile
    # nothing
elseif !ismultios && !ismultiversion
    @static if isfile(joinpath(@__DIR__, "../deps/SnoopCompile/precompile/precompile_MartaCT.jl"))
        include("../deps/SnoopCompile/precompile/precompile_MartaCT.jl")
        _precompile_()
    end
else
    @static if Sys.islinux()
    @static if v"1.5.0-DEV" <= VERSION <= v"1.5.9"
    @static if isfile(joinpath(@__DIR__, "../deps/SnoopCompile/precompile/linux/1.5/precompile_MartaCT.jl"))
        include("../deps/SnoopCompile/precompile/linux/1.5/precompile_MartaCT.jl")
        _precompile_()
    end
else
    @static if isfile(joinpath(@__DIR__, "../deps/SnoopCompile/precompile/linux/1.5/precompile_MartaCT.jl"))
        include("../deps/SnoopCompile/precompile/linux/1.5/precompile_MartaCT.jl")
        _precompile_()
    end
    end

elseif Sys.isapple()
    @static if v"1.5.0-DEV" <= VERSION <= v"1.5.9"
    @static if isfile(joinpath(@__DIR__, "../deps/SnoopCompile/precompile/apple/1.5/precompile_MartaCT.jl"))
        include("../deps/SnoopCompile/precompile/apple/1.5/precompile_MartaCT.jl")
        _precompile_()
    end
else
    @static if isfile(joinpath(@__DIR__, "../deps/SnoopCompile/precompile/apple/1.5/precompile_MartaCT.jl"))
        include("../deps/SnoopCompile/precompile/apple/1.5/precompile_MartaCT.jl")
        _precompile_()
    end
    end

elseif Sys.iswindows()
    @static if v"1.5.0-DEV" <= VERSION <= v"1.5.9"
    @static if isfile(joinpath(@__DIR__, "../deps/SnoopCompile/precompile/windows/1.5/precompile_MartaCT.jl"))
        include("../deps/SnoopCompile/precompile/windows/1.5/precompile_MartaCT.jl")
        _precompile_()
    end
else
    @static if isfile(joinpath(@__DIR__, "../deps/SnoopCompile/precompile/windows/1.5/precompile_MartaCT.jl"))
        include("../deps/SnoopCompile/precompile/windows/1.5/precompile_MartaCT.jl")
        _precompile_()
    end
    end

else
    @static if v"1.5.0-DEV" <= VERSION <= v"1.5.9"
    @static if isfile(joinpath(@__DIR__, "../deps/SnoopCompile/precompile/linux/1.5/precompile_MartaCT.jl"))
        include("../deps/SnoopCompile/precompile/linux/1.5/precompile_MartaCT.jl")
        _precompile_()
    end
else
    @static if isfile(joinpath(@__DIR__, "../deps/SnoopCompile/precompile/linux/1.5/precompile_MartaCT.jl"))
        include("../deps/SnoopCompile/precompile/linux/1.5/precompile_MartaCT.jl")
        _precompile_()
    end
    end

    end

end # precompile_enclosure


text:
# Julia wrapper for header: pngconf.h
# Automatically generated using Clang.jl

# Julia wrapper for header: pnglibconf.h
# Automatically generated using Clang.jl

# Julia wrapper for header: png.h
# Automatically generated using Clang.jl

function png_access_version_number()
    ccall((:png_access_version_number, libpng), png_uint_32, ())
end

function png_set_sig_bytes(png_ptr, num_bytes)
    ccall((:png_set_sig_bytes, libpng), Cvoid, (png_structrp, Cint), png_ptr, num_bytes)
end

function png_sig_cmp(sig, start, num_to_check)
    ccall((:png_sig_cmp, libpng), Cint, (png_const_bytep, Csize_t, Csize_t), sig, start, num_to_check)
end

function png_create_read_struct(user_png_ver, error_ptr, error_fn, warn_fn)
    ccall((:png_create_read_struct, libpng), png_structp, (png_const_charp, png_voidp, png_error_ptr, png_error_ptr), user_png_ver, error_ptr, error_fn, warn_fn)
end

function png_create_write_struct(user_png_ver, error_ptr, error_fn, warn_fn)
    ccall((:png_create_write_struct, libpng), png_structp, (png_const_charp, png_voidp, png_error_ptr, png_error_ptr), user_png_ver, error_ptr, error_fn, warn_fn)
end

function png_get_compression_buffer_size(png_ptr)
    ccall((:png_get_compression_buffer_size, libpng), Csize_t, (png_const_structrp,), png_ptr)
end

function png_set_compression_buffer_size(png_ptr, size)
    ccall((:png_set_compression_buffer_size, libpng), Cvoid, (png_structrp, Csize_t), png_ptr, size)
end

function png_set_longjmp_fn()
    ccall((:png_set_longjmp_fn, libpng), Ptr{Cint}, ())
end

function png_longjmp(png_ptr, val)
    ccall((:png_longjmp, libpng), Cvoid, (png_const_structrp, Cint), png_ptr, val)
end

function png_reset_zstream(png_ptr)
    ccall((:png_reset_zstream, libpng), Cint, (png_structrp,), png_ptr)
end

function png_create_read_struct_2(user_png_ver, error_ptr, error_fn, warn_fn, mem_ptr, malloc_fn, free_fn)
    ccall((:png_create_read_struct_2, libpng), png_structp, (png_const_charp, png_voidp, png_error_ptr, png_error_ptr, png_voidp, png_malloc_ptr, png_free_ptr), user_png_ver, error_ptr, error_fn, warn_fn, mem_ptr, malloc_fn, free_fn)
end

function png_create_write_struct_2(user_png_ver, error_ptr, error_fn, warn_fn, mem_ptr, malloc_fn, free_fn)
    ccall((:png_create_write_struct_2, libpng), png_structp, (png_const_charp, png_voidp, png_error_ptr, png_error_ptr, png_voidp, png_malloc_ptr, png_free_ptr), user_png_ver, error_ptr, error_fn, warn_fn, mem_ptr, malloc_fn, free_fn)
end

function png_write_sig(png_ptr)
    ccall((:png_write_sig, libpng), Cvoid, (png_structrp,), png_ptr)
end

function png_write_chunk(png_ptr, chunk_name, data, length)
    ccall((:png_write_chunk, libpng), Cvoid, (png_structrp, png_const_bytep, png_const_bytep, Csize_t), png_ptr, chunk_name, data, length)
end

function png_write_chunk_start(png_ptr, chunk_name, length)
    ccall((:png_write_chunk_start, libpng), Cvoid, (png_structrp, png_const_bytep, png_uint_32), png_ptr, chunk_name, length)
end

function png_write_chunk_data(png_ptr, data, length)
    ccall((:png_write_chunk_data, libpng), Cvoid, (png_structrp, png_const_bytep, Csize_t), png_ptr, data, length)
end

function png_write_chunk_end(png_ptr)
    ccall((:png_write_chunk_end, libpng), Cvoid, (png_structrp,), png_ptr)
end

function png_create_info_struct(png_ptr)
    ccall((:png_create_info_struct, libpng), png_infop, (png_const_structrp,), png_ptr)
end

function png_info_init_3(info_ptr, png_info_struct_size)
    ccall((:png_info_init_3, libpng), Cvoid, (png_infopp, Csize_t), info_ptr, png_info_struct_size)
end

function png_write_info_before_PLTE(png_ptr, info_ptr)
    ccall((:png_write_info_before_PLTE, libpng), Cvoid, (png_structrp, png_const_inforp), png_ptr, info_ptr)
end

function png_write_info(png_ptr, info_ptr)
    ccall((:png_write_info, libpng), Cvoid, (png_structrp, png_const_inforp), png_ptr, info_ptr)
end

function png_read_info(png_ptr, info_ptr)
    ccall((:png_read_info, libpng), Cvoid, (png_structrp, png_inforp), png_ptr, info_ptr)
end

function png_convert_to_rfc1123(png_ptr, ptime)
    ccall((:png_convert_to_rfc1123, libpng), png_const_charp, (png_structrp, png_const_timep), png_ptr, ptime)
end

function png_convert_to_rfc1123_buffer(out, ptime)
    ccall((:png_convert_to_rfc1123_buffer, libpng), Cint, (Ptr{UInt8}, png_const_timep), out, ptime)
end

function png_convert_from_struct_tm(ptime, ttime)
    ccall((:png_convert_from_struct_tm, libpng), Cvoid, (png_timep, Ptr{Ctm}), ptime, ttime)
end

function png_convert_from_time_t(ptime, ttime)
    ccall((:png_convert_from_time_t, libpng), Cvoid, (png_timep, Cint), ptime, ttime)
end

function png_set_expand(png_ptr)
    ccall((:png_set_expand, libpng), Cvoid, (png_structrp,), png_ptr)
end

function png_set_expand_gray_1_2_4_to_8(png_ptr)
    ccall((:png_set_expand_gray_1_2_4_to_8, libpng), Cvoid, (png_structrp,), png_ptr)
end

function png_set_palette_to_rgb(png_ptr)
    ccall((:png_set_palette_to_rgb, libpng), Cvoid, (png_structrp,), png_ptr)
end

function png_set_tRNS_to_alpha(png_ptr)
    ccall((:png_set_tRNS_to_alpha, libpng), Cvoid, (png_structrp,), png_ptr)
end

function png_set_expand_16(png_ptr)
    ccall((:png_set_expand_16, libpng), Cvoid, (png_structrp,), png_ptr)
end

function png_set_bgr(png_ptr)
    ccall((:png_set_bgr, libpng), Cvoid, (png_structrp,), png_ptr)
end

function png_set_gray_to_rgb(png_ptr)
    ccall((:png_set_gray_to_rgb, libpng), Cvoid, (png_structrp,), png_ptr)
end

function png_set_rgb_to_gray(png_ptr, error_action, red, green)
    ccall((:png_set_rgb_to_gray, libpng), Cvoid, (png_structrp, Cint, Cdouble, Cdouble), png_ptr, error_action, red, green)
end

function png_set_rgb_to_gray_fixed(png_ptr, error_action, red, green)
    ccall((:png_set_rgb_to_gray_fixed, libpng), Cvoid, (png_structrp, Cint, png_fixed_point, png_fixed_point), png_ptr, error_action, red, green)
end

function png_get_rgb_to_gray_status(png_ptr)
    ccall((:png_get_rgb_to_gray_status, libpng), png_byte, (png_const_structrp,), png_ptr)
end

function png_build_grayscale_palette(bit_depth, palette)
    ccall((:png_build_grayscale_palette, libpng), Cvoid, (Cint, png_colorp), bit_depth, palette)
end

function png_set_alpha_mode(png_ptr, mode, output_gamma)
    ccall((:png_set_alpha_mode, libpng), Cvoid, (png_structrp, Cint, Cdouble), png_ptr, mode, output_gamma)
end

function png_set_alpha_mode_fixed(png_ptr, mode, output_gamma)
    ccall((:png_set_alpha_mode_fixed, libpng), Cvoid, (png_structrp, Cint, png_fixed_point), png_ptr, mode, output_gamma)
end

function png_set_strip_alpha(png_ptr)
    ccall((:png_set_strip_alpha, libpng), Cvoid, (png_structrp,), png_ptr)
end

function png_set_swap_alpha(png_ptr)
    ccall((:png_set_swap_alpha, libpng), Cvoid, (png_structrp,), png_ptr)
end

function png_set_invert_alpha(png_ptr)
    ccall((:png_set_invert_alpha, libpng), Cvoid, (png_structrp,), png_ptr)
end

function png_set_filler(png_ptr, filler, flags)
    ccall((:png_set_filler, libpng), Cvoid, (png_structrp, png_uint_32, Cint), png_ptr, filler, flags)
end

function png_set_add_alpha(png_ptr, filler, flags)
    ccall((:png_set_add_alpha, libpng), Cvoid, (png_structrp, png_uint_32, Cint), png_ptr, filler, flags)
end

function png_set_swap(png_ptr)
    ccall((:png_set_swap, libpng), Cvoid, (png_structrp,), png_ptr)
end

function png_set_packing(png_ptr)
    ccall((:png_set_packing, libpng), Cvoid, (png_structrp,), png_ptr)
end

function png_set_packswap(png_ptr)
    ccall((:png_set_packswap, libpng), Cvoid, (png_structrp,), png_ptr)
end

function png_set_shift(png_ptr, true_bits)
    ccall((:png_set_shift, libpng), Cvoid, (png_structrp, png_const_color_8p), png_ptr, true_bits)
end

function png_set_interlace_handling(png_ptr)
    ccall((:png_set_interlace_handling, libpng), Cint, (png_structrp,), png_ptr)
end

function png_set_invert_mono(png_ptr)
    ccall((:png_set_invert_mono, libpng), Cvoid, (png_structrp,), png_ptr)
end

function png_set_background(png_ptr, background_color, background_gamma_code, need_expand, background_gamma)
    ccall((:png_set_background, libpng), Cvoid, (png_structrp, png_const_color_16p, Cint, Cint, Cdouble), png_ptr, background_color, background_gamma_code, need_expand, background_gamma)
end

function png_set_background_fixed(png_ptr, background_color, background_gamma_code, need_expand, background_gamma)
    ccall((:png_set_background_fixed, libpng), Cvoid, (png_structrp, png_const_color_16p, Cint, Cint, png_fixed_point), png_ptr, background_color, background_gamma_code, need_expand, background_gamma)
end

function png_set_scale_16(png_ptr)
    ccall((:png_set_scale_16, libpng), Cvoid, (png_structrp,), png_ptr)
end

function png_set_strip_16(png_ptr)
    ccall((:png_set_strip_16, libpng), Cvoid, (png_structrp,), png_ptr)
end

function png_set_quantize(png_ptr, palette, num_palette, maximum_colors, histogram, full_quantize)
    ccall((:png_set_quantize, libpng), Cvoid, (png_structrp, png_colorp, Cint, Cint, png_const_uint_16p, Cint), png_ptr, palette, num_palette, maximum_colors, histogram, full_quantize)
end

function png_set_gamma(png_ptr, screen_gamma, override_file_gamma)
    ccall((:png_set_gamma, libpng), Cvoid, (png_structrp, Cdouble, Cdouble), png_ptr, screen_gamma, override_file_gamma)
end

function png_set_gamma_fixed(png_ptr, screen_gamma, override_file_gamma)
    ccall((:png_set_gamma_fixed, libpng), Cvoid, (png_structrp, png_fixed_point, png_fixed_point), png_ptr, screen_gamma, override_file_gamma)
end

function png_set_flush(png_ptr, nrows)
    ccall((:png_set_flush, libpng), Cvoid, (png_structrp, Cint), png_ptr, nrows)
end

function png_write_flush(png_ptr)
    ccall((:png_write_flush, libpng), Cvoid, (png_structrp,), png_ptr)
end

function png_start_read_image(png_ptr)
    ccall((:png_start_read_image, libpng), Cvoid, (png_structrp,), png_ptr)
end

function png_read_update_info(png_ptr, info_ptr)
    ccall((:png_read_update_info, libpng), Cvoid, (png_structrp, png_inforp), png_ptr, info_ptr)
end

function png_read_rows(png_ptr, row, display_row, num_rows)
    ccall((:png_read_rows, libpng), Cvoid, (png_structrp, png_bytepp, png_bytepp, png_uint_32), png_ptr, row, display_row, num_rows)
end

function png_read_row(png_ptr, row, display_row)
    ccall((:png_read_row, libpng), Cvoid, (png_structrp, png_bytep, png_bytep), png_ptr, row, display_row)
end

function png_read_image(png_ptr, image)
    ccall((:png_read_image, libpng), Cvoid, (png_structrp, png_bytepp), png_ptr, image)
end

function png_write_row(png_ptr, row)
    ccall((:png_write_row, libpng), Cvoid, (png_structrp, png_const_bytep), png_ptr, row)
end

function png_write_rows(png_ptr, row, num_rows)
    ccall((:png_write_rows, libpng), Cvoid, (png_structrp, png_bytepp, png_uint_32), png_ptr, row, num_rows)
end

function png_write_image(png_ptr, image)
    ccall((:png_write_image, libpng), Cvoid, (png_structrp, png_bytepp), png_ptr, image)
end

function png_write_end(png_ptr, info_ptr)
    ccall((:png_write_end, libpng), Cvoid, (png_structrp, png_inforp), png_ptr, info_ptr)
end

function png_read_end(png_ptr, info_ptr)
    ccall((:png_read_end, libpng), Cvoid, (png_structrp, png_inforp), png_ptr, info_ptr)
end

function png_destroy_info_struct(png_ptr, info_ptr_ptr)
    ccall((:png_destroy_info_struct, libpng), Cvoid, (png_const_structrp, png_infopp), png_ptr, info_ptr_ptr)
end

function png_destroy_read_struct(png_ptr_ptr, info_ptr_ptr, end_info_ptr_ptr)
    ccall((:png_destroy_read_struct, libpng), Cvoid, (png_structpp, png_infopp, png_infopp), png_ptr_ptr, info_ptr_ptr, end_info_ptr_ptr)
end

function png_destroy_write_struct(png_ptr_ptr, info_ptr_ptr)
    ccall((:png_destroy_write_struct, libpng), Cvoid, (png_structpp, png_infopp), png_ptr_ptr, info_ptr_ptr)
end

function png_set_crc_action(png_ptr, crit_action, ancil_action)
    ccall((:png_set_crc_action, libpng), Cvoid, (png_structrp, Cint, Cint), png_ptr, crit_action, ancil_action)
end

function png_set_filter(png_ptr, method, filters)
    ccall((:png_set_filter, libpng), Cvoid, (png_structrp, Cint, Cint), png_ptr, method, filters)
end

function png_set_filter_heuristics(png_ptr, heuristic_method, num_weights, filter_weights, filter_costs)
    ccall((:png_set_filter_heuristics, libpng), Cvoid, (png_structrp, Cint, Cint, png_const_doublep, png_const_doublep), png_ptr, heuristic_method, num_weights, filter_weights, filter_costs)
end

function png_set_filter_heuristics_fixed(png_ptr, heuristic_method, num_weights, filter_weights, filter_costs)
    ccall((:png_set_filter_heuristics_fixed, libpng), Cvoid, (png_structrp, Cint, Cint, png_const_fixed_point_p, png_const_fixed_point_p), png_ptr, heuristic_method, num_weights, filter_weights, filter_costs)
end

function png_set_compression_level(png_ptr, level)
    ccall((:png_set_compression_level, libpng), Cvoid, (png_structrp, Cint), png_ptr, level)
end

function png_set_compression_mem_level(png_ptr, mem_level)
    ccall((:png_set_compression_mem_level, libpng), Cvoid, (png_structrp, Cint), png_ptr, mem_level)
end

function png_set_compression_strategy(png_ptr, strategy)
    ccall((:png_set_compression_strategy, libpng), Cvoid, (png_structrp, Cint), png_ptr, strategy)
end

function png_set_compression_window_bits(png_ptr, window_bits)
    ccall((:png_set_compression_window_bits, libpng), Cvoid, (png_structrp, Cint), png_ptr, window_bits)
end

function png_set_compression_method(png_ptr, method)
    ccall((:png_set_compression_method, libpng), Cvoid, (png_structrp, Cint), png_ptr, method)
end

function png_set_text_compression_level(png_ptr, level)
    ccall((:png_set_text_compression_level, libpng), Cvoid, (png_structrp, Cint), png_ptr, level)
end

function png_set_text_compression_mem_level(png_ptr, mem_level)
    ccall((:png_set_text_compression_mem_level, libpng), Cvoid, (png_structrp, Cint), png_ptr, mem_level)
end

function png_set_text_compression_strategy(png_ptr, strategy)
    ccall((:png_set_text_compression_strategy, libpng), Cvoid, (png_structrp, Cint), png_ptr, strategy)
end

function png_set_text_compression_window_bits(png_ptr, window_bits)
    ccall((:png_set_text_compression_window_bits, libpng), Cvoid, (png_structrp, Cint), png_ptr, window_bits)
end

function png_set_text_compression_method(png_ptr, method)
    ccall((:png_set_text_compression_method, libpng), Cvoid, (png_structrp, Cint), png_ptr, method)
end

function png_init_io(png_ptr, fp)
    ccall((:png_init_io, libpng), Cvoid, (png_structrp, png_FILE_p), png_ptr, fp)
end

function png_set_error_fn(png_ptr, error_ptr, error_fn, warning_fn)
    ccall((:png_set_error_fn, libpng), Cvoid, (png_structrp, png_voidp, png_error_ptr, png_error_ptr), png_ptr, error_ptr, error_fn, warning_fn)
end

function png_get_error_ptr(png_ptr)
    ccall((:png_get_error_ptr, libpng), png_voidp, (png_const_structrp,), png_ptr)
end

function png_set_write_fn(png_ptr, io_ptr, write_data_fn, output_flush_fn)
    ccall((:png_set_write_fn, libpng), Cvoid, (png_structrp, png_voidp, png_rw_ptr, png_flush_ptr), png_ptr, io_ptr, write_data_fn, output_flush_fn)
end

function png_set_read_fn(png_ptr, io_ptr, read_data_fn)
    ccall((:png_set_read_fn, libpng), Cvoid, (png_structrp, png_voidp, png_rw_ptr), png_ptr, io_ptr, read_data_fn)
end

function png_get_io_ptr(png_ptr)
    ccall((:png_get_io_ptr, libpng), png_voidp, (png_const_structrp,), png_ptr)
end

function png_set_read_status_fn(png_ptr, read_row_fn)
    ccall((:png_set_read_status_fn, libpng), Cvoid, (png_structrp, png_read_status_ptr), png_ptr, read_row_fn)
end

function png_set_write_status_fn(png_ptr, write_row_fn)
    ccall((:png_set_write_status_fn, libpng), Cvoid, (png_structrp, png_write_status_ptr), png_ptr, write_row_fn)
end

function png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn)
    ccall((:png_set_mem_fn, libpng), Cvoid, (png_structrp, png_voidp, png_malloc_ptr, png_free_ptr), png_ptr, mem_ptr, malloc_fn, free_fn)
end

function png_get_mem_ptr(png_ptr)
    ccall((:png_get_mem_ptr, libpng), png_voidp, (png_const_structrp,), png_ptr)
end

function png_set_read_user_transform_fn(png_ptr, read_user_transform_fn)
    ccall((:png_set_read_user_transform_fn, libpng), Cvoid, (png_structrp, png_user_transform_ptr), png_ptr, read_user_transform_fn)
end

function png_set_write_user_transform_fn(png_ptr, write_user_transform_fn)
    ccall((:png_set_write_user_transform_fn, libpng), Cvoid, (png_structrp, png_user_transform_ptr), png_ptr, write_user_transform_fn)
end

function png_set_user_transform_info(png_ptr, user_transform_ptr, user_transform_depth, user_transform_channels)
    ccall((:png_set_user_transform_info, libpng), Cvoid, (png_structrp, png_voidp, Cint, Cint), png_ptr, user_transform_ptr, user_transform_depth, user_transform_channels)
end

function png_get_user_transform_ptr(png_ptr)
    ccall((:png_get_user_transform_ptr, libpng), png_voidp, (png_const_structrp,), png_ptr)
end

function png_get_current_row_number(arg1)
    ccall((:png_get_current_row_number, libpng), png_uint_32, (png_const_structrp,), arg1)
end

function png_get_current_pass_number(arg1)
    ccall((:png_get_current_pass_number, libpng), png_byte, (png_const_structrp,), arg1)
end

function png_set_read_user_chunk_fn(png_ptr, user_chunk_ptr, read_user_chunk_fn)
    ccall((:png_set_read_user_chunk_fn, libpng), Cvoid, (png_structrp, png_voidp, png_user_chunk_ptr), png_ptr, user_chunk_ptr, read_user_chunk_fn)
end

function png_get_user_chunk_ptr(png_ptr)
    ccall((:png_get_user_chunk_ptr, libpng), png_voidp, (png_const_structrp,), png_ptr)
end

function png_set_progressive_read_fn(png_ptr, progressive_ptr, info_fn, row_fn, end_fn)
    ccall((:png_set_progressive_read_fn, libpng), Cvoid, (png_structrp, png_voidp, png_progressive_info_ptr, png_progressive_row_ptr, png_progressive_end_ptr), png_ptr, progressive_ptr, info_fn, row_fn, end_fn)
end

function png_get_progressive_ptr(png_ptr)
    ccall((:png_get_progressive_ptr, libpng), png_voidp, (png_const_structrp,), png_ptr)
end

function png_process_data(png_ptr, info_ptr, buffer, buffer_size)
    ccall((:png_process_data, libpng), Cvoid, (png_structrp, png_inforp, png_bytep, Csize_t), png_ptr, info_ptr, buffer, buffer_size)
end

function png_process_data_pause(arg1, save)
    ccall((:png_process_data_pause, libpng), Csize_t, (png_structrp, Cint), arg1, save)
end

function png_process_data_skip(arg1)
    ccall((:png_process_data_skip, libpng), png_uint_32, (png_structrp,), arg1)
end

function png_progressive_combine_row(png_ptr, old_row, new_row)
    ccall((:png_progressive_combine_row, libpng), Cvoid, (png_const_structrp, png_bytep, png_const_bytep), png_ptr, old_row, new_row)
end

function png_malloc(png_ptr, size)
    ccall((:png_malloc, libpng), png_voidp, (png_const_structrp, png_alloc_size_t), png_ptr, size)
end

function png_calloc(png_ptr, size)
    ccall((:png_calloc, libpng), png_voidp, (png_const_structrp, png_alloc_size_t), png_ptr, size)
end

function png_malloc_warn(png_ptr, size)
    ccall((:png_malloc_warn, libpng), png_voidp, (png_const_structrp, png_alloc_size_t), png_ptr, size)
end

function png_free(png_ptr, ptr)
    ccall((:png_free, libpng), Cvoid, (png_const_structrp, png_voidp), png_ptr, ptr)
end

function png_free_data(png_ptr, info_ptr, free_me, num)
    ccall((:png_free_data, libpng), Cvoid, (png_const_structrp, png_inforp, png_uint_32, Cint), png_ptr, info_ptr, free_me, num)
end

function png_data_freer(png_ptr, info_ptr, freer, mask)
    ccall((:png_data_freer, libpng), Cvoid, (png_const_structrp, png_inforp, Cint, png_uint_32), png_ptr, info_ptr, freer, mask)
end

function png_malloc_default(png_ptr, size)
    ccall((:png_malloc_default, libpng), png_voidp, (png_const_structrp, png_alloc_size_t), png_ptr, size)
end

function png_free_default(png_ptr, ptr)
    ccall((:png_free_default, libpng), Cvoid, (png_const_structrp, png_voidp), png_ptr, ptr)
end

function png_error(png_ptr, error_message)
    ccall((:png_error, libpng), Cvoid, (png_const_structrp, png_const_charp), png_ptr, error_message)
end

function png_chunk_error(png_ptr, error_message)
    ccall((:png_chunk_error, libpng), Cvoid, (png_const_structrp, png_const_charp), png_ptr, error_message)
end

function png_warning(png_ptr, warning_message)
    ccall((:png_warning, libpng), Cvoid, (png_const_structrp, png_const_charp), png_ptr, warning_message)
end

function png_chunk_warning(png_ptr, warning_message)
    ccall((:png_chunk_warning, libpng), Cvoid, (png_const_structrp, png_const_charp), png_ptr, warning_message)
end

function png_benign_error(png_ptr, warning_message)
    ccall((:png_benign_error, libpng), Cvoid, (png_const_structrp, png_const_charp), png_ptr, warning_message)
end

function png_chunk_benign_error(png_ptr, warning_message)
    ccall((:png_chunk_benign_error, libpng), Cvoid, (png_const_structrp, png_const_charp), png_ptr, warning_message)
end

function png_set_benign_errors(png_ptr, allowed)
    ccall((:png_set_benign_errors, libpng), Cvoid, (png_structrp, Cint), png_ptr, allowed)
end

function png_get_valid(png_ptr, info_ptr, flag)
    ccall((:png_get_valid, libpng), png_uint_32, (png_const_structrp, png_const_inforp, png_uint_32), png_ptr, info_ptr, flag)
end

function png_get_rowbytes(png_ptr, info_ptr)
    ccall((:png_get_rowbytes, libpng), Csize_t, (png_const_structrp, png_const_inforp), png_ptr, info_ptr)
end

function png_get_rows(png_ptr, info_ptr)
    ccall((:png_get_rows, libpng), png_bytepp, (png_const_structrp, png_const_inforp), png_ptr, info_ptr)
end

function png_set_rows(png_ptr, info_ptr, row_pointers)
    ccall((:png_set_rows, libpng), Cvoid, (png_const_structrp, png_inforp, png_bytepp), png_ptr, info_ptr, row_pointers)
end

function png_get_channels(png_ptr, info_ptr)
    ccall((:png_get_channels, libpng), png_byte, (png_const_structrp, png_const_inforp), png_ptr, info_ptr)
end

function png_get_image_width(png_ptr, info_ptr)
    ccall((:png_get_image_width, libpng), png_uint_32, (png_const_structrp, png_const_inforp), png_ptr, info_ptr)
end

function png_get_image_height(png_ptr, info_ptr)
    ccall((:png_get_image_height, libpng), png_uint_32, (png_const_structrp, png_const_inforp), png_ptr, info_ptr)
end

function png_get_bit_depth(png_ptr, info_ptr)
    ccall((:png_get_bit_depth, libpng), png_byte, (png_const_structrp, png_const_inforp), png_ptr, info_ptr)
end

function png_get_color_type(png_ptr, info_ptr)
    ccall((:png_get_color_type, libpng), png_byte, (png_const_structrp, png_const_inforp), png_ptr, info_ptr)
end

function png_get_filter_type(png_ptr, info_ptr)
    ccall((:png_get_filter_type, libpng), png_byte, (png_const_structrp, png_const_inforp), png_ptr, info_ptr)
end

function png_get_interlace_type(png_ptr, info_ptr)
    ccall((:png_get_interlace_type, libpng), png_byte, (png_const_structrp, png_const_inforp), png_ptr, info_ptr)
end

function png_get_compression_type(png_ptr, info_ptr)
    ccall((:png_get_compression_type, libpng), png_byte, (png_const_structrp, png_const_inforp), png_ptr, info_ptr)
end

function png_get_pixels_per_meter(png_ptr, info_ptr)
    ccall((:png_get_pixels_per_meter, libpng), png_uint_32, (png_const_structrp, png_const_inforp), png_ptr, info_ptr)
end

function png_get_x_pixels_per_meter(png_ptr, info_ptr)
    ccall((:png_get_x_pixels_per_meter, libpng), png_uint_32, (png_const_structrp, png_const_inforp), png_ptr, info_ptr)
end

function png_get_y_pixels_per_meter(png_ptr, info_ptr)
    ccall((:png_get_y_pixels_per_meter, libpng), png_uint_32, (png_const_structrp, png_const_inforp), png_ptr, info_ptr)
end

function png_get_pixel_aspect_ratio(png_ptr, info_ptr)
    ccall((:png_get_pixel_aspect_ratio, libpng), Cfloat, (png_const_structrp, png_const_inforp), png_ptr, info_ptr)
end

function png_get_pixel_aspect_ratio_fixed(png_ptr, info_ptr)
    ccall((:png_get_pixel_aspect_ratio_fixed, libpng), png_fixed_point, (png_const_structrp, png_const_inforp), png_ptr, info_ptr)
end

function png_get_x_offset_pixels(png_ptr, info_ptr)
    ccall((:png_get_x_offset_pixels, libpng), png_int_32, (png_const_structrp, png_const_inforp), png_ptr, info_ptr)
end

function png_get_y_offset_pixels(png_ptr, info_ptr)
    ccall((:png_get_y_offset_pixels, libpng), png_int_32, (png_const_structrp, png_const_inforp), png_ptr, info_ptr)
end

function png_get_x_offset_microns(png_ptr, info_ptr)
    ccall((:png_get_x_offset_microns, libpng), png_int_32, (png_const_structrp, png_const_inforp), png_ptr, info_ptr)
end

function png_get_y_offset_microns(png_ptr, info_ptr)
    ccall((:png_get_y_offset_microns, libpng), png_int_32, (png_const_structrp, png_const_inforp), png_ptr, info_ptr)
end

function png_get_signature(png_ptr, info_ptr)
    ccall((:png_get_signature, libpng), png_const_bytep, (png_const_structrp, png_const_inforp), png_ptr, info_ptr)
end

function png_get_bKGD(png_ptr, info_ptr, background)
    ccall((:png_get_bKGD, libpng), png_uint_32, (png_const_structrp, png_inforp, Ptr{png_color_16p}), png_ptr, info_ptr, background)
end

function png_set_bKGD(png_ptr, info_ptr, background)
    ccall((:png_set_bKGD, libpng), Cvoid, (png_const_structrp, png_inforp, png_const_color_16p), png_ptr, info_ptr, background)
end

function png_get_cHRM(png_ptr, info_ptr, white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y)
    ccall((:png_get_cHRM, libpng), png_uint_32, (png_const_structrp, png_const_inforp, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}), png_ptr, info_ptr, white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y)
end

function png_get_cHRM_XYZ(png_ptr, info_ptr, red_X, red_Y, red_Z, green_X, green_Y, green_Z, blue_X, blue_Y, blue_Z)
    ccall((:png_get_cHRM_XYZ, libpng), png_uint_32, (png_const_structrp, png_const_inforp, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}), png_ptr, info_ptr, red_X, red_Y, red_Z, green_X, green_Y, green_Z, blue_X, blue_Y, blue_Z)
end

function png_get_cHRM_fixed(png_ptr, info_ptr, int_white_x, int_white_y, int_red_x, int_red_y, int_green_x, int_green_y, int_blue_x, int_blue_y)
    ccall((:png_get_cHRM_fixed, libpng), png_uint_32, (png_const_structrp, png_const_inforp, Ptr{png_fixed_point}, Ptr{png_fixed_point}, Ptr{png_fixed_point}, Ptr{png_fixed_point}, Ptr{png_fixed_point}, Ptr{png_fixed_point}, Ptr{png_fixed_point}, Ptr{png_fixed_point}), png_ptr, info_ptr, int_white_x, int_white_y, int_red_x, int_red_y, int_green_x, int_green_y, int_blue_x, int_blue_y)
end

function png_get_cHRM_XYZ_fixed(png_ptr, info_ptr, int_red_X, int_red_Y, int_red_Z, int_green_X, int_green_Y, int_green_Z, int_blue_X, int_blue_Y, int_blue_Z)
    ccall((:png_get_cHRM_XYZ_fixed, libpng), png_uint_32, (png_const_structrp, png_const_inforp, Ptr{png_fixed_point}, Ptr{png_fixed_point}, Ptr{png_fixed_point}, Ptr{png_fixed_point}, Ptr{png_fixed_point}, Ptr{png_fixed_point}, Ptr{png_fixed_point}, Ptr{png_fixed_point}, Ptr{png_fixed_point}), png_ptr, info_ptr, int_red_X, int_red_Y, int_red_Z, int_green_X, int_green_Y, int_green_Z, int_blue_X, int_blue_Y, int_blue_Z)
end

function png_set_cHRM(png_ptr, info_ptr, white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y)
    ccall((:png_set_cHRM, libpng), Cvoid, (png_const_structrp, png_inforp, Cdouble, Cdouble, Cdouble, Cdouble, Cdouble, Cdouble, Cdouble, Cdouble), png_ptr, info_ptr, white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y)
end

function png_set_cHRM_XYZ(png_ptr, info_ptr, red_X, red_Y, red_Z, green_X, green_Y, green_Z, blue_X, blue_Y, blue_Z)
    ccall((:png_set_cHRM_XYZ, libpng), Cvoid, (png_const_structrp, png_inforp, Cdouble, Cdouble, Cdouble, Cdouble, Cdouble, Cdouble, Cdouble, Cdouble, Cdouble), png_ptr, info_ptr, red_X, red_Y, red_Z, green_X, green_Y, green_Z, blue_X, blue_Y, blue_Z)
end

function png_set_cHRM_fixed(png_ptr, info_ptr, int_white_x, int_white_y, int_red_x, int_red_y, int_green_x, int_green_y, int_blue_x, int_blue_y)
    ccall((:png_set_cHRM_fixed, libpng), Cvoid, (png_const_structrp, png_inforp, png_fixed_point, png_fixed_point, png_fixed_point, png_fixed_point, png_fixed_point, png_fixed_point, png_fixed_point, png_fixed_point), png_ptr, info_ptr, int_white_x, int_white_y, int_red_x, int_red_y, int_green_x, int_green_y, int_blue_x, int_blue_y)
end

function png_set_cHRM_XYZ_fixed(png_ptr, info_ptr, int_red_X, int_red_Y, int_red_Z, int_green_X, int_green_Y, int_green_Z, int_blue_X, int_blue_Y, int_blue_Z)
    ccall((:png_set_cHRM_XYZ_fixed, libpng), Cvoid, (png_const_structrp, png_inforp, png_fixed_point, png_fixed_point, png_fixed_point, png_fixed_point, png_fixed_point, png_fixed_point, png_fixed_point, png_fixed_point, png_fixed_point), png_ptr, info_ptr, int_red_X, int_red_Y, int_red_Z, int_green_X, int_green_Y, int_green_Z, int_blue_X, int_blue_Y, int_blue_Z)
end

function png_get_eXIf(png_ptr, info_ptr, exif)
    ccall((:png_get_eXIf, libpng), png_uint_32, (png_const_structrp, png_inforp, Ptr{png_bytep}), png_ptr, info_ptr, exif)
end

function png_set_eXIf(png_ptr, info_ptr, exif)
    ccall((:png_set_eXIf, libpng), Cvoid, (png_const_structrp, png_inforp, png_bytep), png_ptr, info_ptr, exif)
end

function png_get_eXIf_1(png_ptr, info_ptr, num_exif, exif)
    ccall((:png_get_eXIf_1, libpng), png_uint_32, (png_const_structrp, png_const_inforp, Ptr{png_uint_32}, Ptr{png_bytep}), png_ptr, info_ptr, num_exif, exif)
end

function png_set_eXIf_1(png_ptr, info_ptr, num_exif, exif)
    ccall((:png_set_eXIf_1, libpng), Cvoid, (png_const_structrp, png_inforp, png_uint_32, png_bytep), png_ptr, info_ptr, num_exif, exif)
end

function png_get_gAMA(png_ptr, info_ptr, file_gamma)
    ccall((:png_get_gAMA, libpng), png_uint_32, (png_const_structrp, png_const_inforp, Ptr{Cdouble}), png_ptr, info_ptr, file_gamma)
end

function png_get_gAMA_fixed(png_ptr, info_ptr, int_file_gamma)
    ccall((:png_get_gAMA_fixed, libpng), png_uint_32, (png_const_structrp, png_const_inforp, Ptr{png_fixed_point}), png_ptr, info_ptr, int_file_gamma)
end

function png_set_gAMA(png_ptr, info_ptr, file_gamma)
    ccall((:png_set_gAMA, libpng), Cvoid, (png_const_structrp, png_inforp, Cdouble), png_ptr, info_ptr, file_gamma)
end

function png_set_gAMA_fixed(png_ptr, info_ptr, int_file_gamma)
    ccall((:png_set_gAMA_fixed, libpng), Cvoid, (png_const_structrp, png_inforp, png_fixed_point), png_ptr, info_ptr, int_file_gamma)
end

function png_get_hIST(png_ptr, info_ptr, hist)
    ccall((:png_get_hIST, libpng), png_uint_32, (png_const_structrp, png_inforp, Ptr{png_uint_16p}), png_ptr, info_ptr, hist)
end

function png_set_hIST(png_ptr, info_ptr, hist)
    ccall((:png_set_hIST, libpng), Cvoid, (png_const_structrp, png_inforp, png_const_uint_16p), png_ptr, info_ptr, hist)
end

function png_get_IHDR(png_ptr, info_ptr, width, height, bit_depth, color_type, interlace_method, compression_method, filter_method)
    ccall((:png_get_IHDR, libpng), png_uint_32, (png_const_structrp, png_const_inforp, Ptr{png_uint_32}, Ptr{png_uint_32}, Ptr{Cint}, Ptr{Cint}, Ptr{Cint}, Ptr{Cint}, Ptr{Cint}), png_ptr, info_ptr, width, height, bit_depth, color_type, interlace_method, compression_method, filter_method)
end

function png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth, color_type, interlace_method, compression_method, filter_method)
    ccall((:png_set_IHDR, libpng), Cvoid, (png_const_structrp, png_inforp, png_uint_32, png_uint_32, Cint, Cint, Cint, Cint, Cint), png_ptr, info_ptr, width, height, bit_depth, color_type, interlace_method, compression_method, filter_method)
end

function png_get_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type)
    ccall((:png_get_oFFs, libpng), png_uint_32, (png_const_structrp, png_const_inforp, Ptr{png_int_32}, Ptr{png_int_32}, Ptr{Cint}), png_ptr, info_ptr, offset_x, offset_y, unit_type)
end

function png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type)
    ccall((:png_set_oFFs, libpng), Cvoid, (png_const_structrp, png_inforp, png_int_32, png_int_32, Cint), png_ptr, info_ptr, offset_x, offset_y, unit_type)
end

function png_get_pCAL(png_ptr, info_ptr, purpose, X0, X1, type, nparams, units, params)
    ccall((:png_get_pCAL, libpng), png_uint_32, (png_const_structrp, png_inforp, Ptr{png_charp}, Ptr{png_int_32}, Ptr{png_int_32}, Ptr{Cint}, Ptr{Cint}, Ptr{png_charp}, Ptr{png_charpp}), png_ptr, info_ptr, purpose, X0, X1, type, nparams, units, params)
end

function png_set_pCAL(png_ptr, info_ptr, purpose, X0, X1, type, nparams, units, params)
    ccall((:png_set_pCAL, libpng), Cvoid, (png_const_structrp, png_inforp, png_const_charp, png_int_32, png_int_32, Cint, Cint, png_const_charp, png_charpp), png_ptr, info_ptr, purpose, X0, X1, type, nparams, units, params)
end

function png_get_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type)
    ccall((:png_get_pHYs, libpng), png_uint_32, (png_const_structrp, png_const_inforp, Ptr{png_uint_32}, Ptr{png_uint_32}, Ptr{Cint}), png_ptr, info_ptr, res_x, res_y, unit_type)
end

function png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type)
    ccall((:png_set_pHYs, libpng), Cvoid, (png_const_structrp, png_inforp, png_uint_32, png_uint_32, Cint), png_ptr, info_ptr, res_x, res_y, unit_type)
end

function png_get_PLTE(png_ptr, info_ptr, palette, num_palette)
    ccall((:png_get_PLTE, libpng), png_uint_32, (png_const_structrp, png_inforp, Ptr{png_colorp}, Ptr{Cint}), png_ptr, info_ptr, palette, num_palette)
end

function png_set_PLTE(png_ptr, info_ptr, palette, num_palette)
    ccall((:png_set_PLTE, libpng), Cvoid, (png_structrp, png_inforp, png_const_colorp, Cint), png_ptr, info_ptr, palette, num_palette)
end

function png_get_sBIT(png_ptr, info_ptr, sig_bit)
    ccall((:png_get_sBIT, libpng), png_uint_32, (png_const_structrp, png_inforp, Ptr{png_color_8p}), png_ptr, info_ptr, sig_bit)
end

function png_set_sBIT(png_ptr, info_ptr, sig_bit)
    ccall((:png_set_sBIT, libpng), Cvoid, (png_const_structrp, png_inforp, png_const_color_8p), png_ptr, info_ptr, sig_bit)
end

function png_get_sRGB(png_ptr, info_ptr, file_srgb_intent)
    ccall((:png_get_sRGB, libpng), png_uint_32, (png_const_structrp, png_const_inforp, Ptr{Cint}), png_ptr, info_ptr, file_srgb_intent)
end

function png_set_sRGB(png_ptr, info_ptr, srgb_intent)
    ccall((:png_set_sRGB, libpng), Cvoid, (png_const_structrp, png_inforp, Cint), png_ptr, info_ptr, srgb_intent)
end

function png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr, srgb_intent)
    ccall((:png_set_sRGB_gAMA_and_cHRM, libpng), Cvoid, (png_const_structrp, png_inforp, Cint), png_ptr, info_ptr, srgb_intent)
end

function png_get_iCCP(png_ptr, info_ptr, name, compression_type, profile, proflen)
    ccall((:png_get_iCCP, libpng), png_uint_32, (png_const_structrp, png_inforp, png_charpp, Ptr{Cint}, png_bytepp, Ptr{png_uint_32}), png_ptr, info_ptr, name, compression_type, profile, proflen)
end

function png_set_iCCP(png_ptr, info_ptr, name, compression_type, profile, proflen)
    ccall((:png_set_iCCP, libpng), Cvoid, (png_const_structrp, png_inforp, png_const_charp, Cint, png_const_bytep, png_uint_32), png_ptr, info_ptr, name, compression_type, profile, proflen)
end

function png_get_sPLT(png_ptr, info_ptr, entries)
    ccall((:png_get_sPLT, libpng), Cint, (png_const_structrp, png_inforp, png_sPLT_tpp), png_ptr, info_ptr, entries)
end

function png_set_sPLT(png_ptr, info_ptr, entries, nentries)
    ccall((:png_set_sPLT, libpng), Cvoid, (png_const_structrp, png_inforp, png_const_sPLT_tp, Cint), png_ptr, info_ptr, entries, nentries)
end

function png_get_text(png_ptr, info_ptr, text_ptr, num_text)
    ccall((:png_get_text, libpng), Cint, (png_const_structrp, png_inforp, Ptr{png_textp}, Ptr{Cint}), png_ptr, info_ptr, text_ptr, num_text)
end

function png_set_text(png_ptr, info_ptr, text_ptr, num_text)
    ccall((:png_set_text, libpng), Cvoid, (png_const_structrp, png_inforp, png_const_textp, Cint), png_ptr, info_ptr, text_ptr, num_text)
end

function png_get_tIME(png_ptr, info_ptr, mod_time)
    ccall((:png_get_tIME, libpng), png_uint_32, (png_const_structrp, png_inforp, Ptr{png_timep}), png_ptr, info_ptr, mod_time)
end

function png_set_tIME(png_ptr, info_ptr, mod_time)
    ccall((:png_set_tIME, libpng), Cvoid, (png_const_structrp, png_inforp, png_const_timep), png_ptr, info_ptr, mod_time)
end

function png_get_tRNS(png_ptr, info_ptr, trans_alpha, num_trans, trans_color)
    ccall((:png_get_tRNS, libpng), png_uint_32, (png_const_structrp, png_inforp, Ptr{png_bytep}, Ptr{Cint}, Ptr{png_color_16p}), png_ptr, info_ptr, trans_alpha, num_trans, trans_color)
end

function png_set_tRNS(png_ptr, info_ptr, trans_alpha, num_trans, trans_color)
    ccall((:png_set_tRNS, libpng), Cvoid, (png_structrp, png_inforp, png_const_bytep, Cint, png_const_color_16p), png_ptr, info_ptr, trans_alpha, num_trans, trans_color)
end

function png_get_sCAL(png_ptr, info_ptr, unit, width, height)
    ccall((:png_get_sCAL, libpng), png_uint_32, (png_const_structrp, png_const_inforp, Ptr{Cint}, Ptr{Cdouble}, Ptr{Cdouble}), png_ptr, info_ptr, unit, width, height)
end

function png_get_sCAL_fixed(png_ptr, info_ptr, unit, width, height)
    ccall((:png_get_sCAL_fixed, libpng), png_uint_32, (png_const_structrp, png_const_inforp, Ptr{Cint}, Ptr{png_fixed_point}, Ptr{png_fixed_point}), png_ptr, info_ptr, unit, width, height)
end

function png_get_sCAL_s(png_ptr, info_ptr, unit, swidth, sheight)
    ccall((:png_get_sCAL_s, libpng), png_uint_32, (png_const_structrp, png_const_inforp, Ptr{Cint}, png_charpp, png_charpp), png_ptr, info_ptr, unit, swidth, sheight)
end

function png_set_sCAL(png_ptr, info_ptr, unit, width, height)
    ccall((:png_set_sCAL, libpng), Cvoid, (png_const_structrp, png_inforp, Cint, Cdouble, Cdouble), png_ptr, info_ptr, unit, width, height)
end

function png_set_sCAL_fixed(png_ptr, info_ptr, unit, width, height)
    ccall((:png_set_sCAL_fixed, libpng), Cvoid, (png_const_structrp, png_inforp, Cint, png_fixed_point, png_fixed_point), png_ptr, info_ptr, unit, width, height)
end

function png_set_sCAL_s(png_ptr, info_ptr, unit, swidth, sheight)
    ccall((:png_set_sCAL_s, libpng), Cvoid, (png_const_structrp, png_inforp, Cint, png_const_charp, png_const_charp), png_ptr, info_ptr, unit, swidth, sheight)
end

function png_set_keep_unknown_chunks(png_ptr, keep, chunk_list, num_chunks)
    ccall((:png_set_keep_unknown_chunks, libpng), Cvoid, (png_structrp, Cint, png_const_bytep, Cint), png_ptr, keep, chunk_list, num_chunks)
end

function png_handle_as_unknown(png_ptr, chunk_name)
    ccall((:png_handle_as_unknown, libpng), Cint, (png_const_structrp, png_const_bytep), png_ptr, chunk_name)
end

function png_set_unknown_chunks(png_ptr, info_ptr, unknowns, num_unknowns)
    ccall((:png_set_unknown_chunks, libpng), Cvoid, (png_const_structrp, png_inforp, png_const_unknown_chunkp, Cint), png_ptr, info_ptr, unknowns, num_unknowns)
end

function png_set_unknown_chunk_location(png_ptr, info_ptr, chunk, location)
    ccall((:png_set_unknown_chunk_location, libpng), Cvoid, (png_const_structrp, png_inforp, Cint, Cint), png_ptr, info_ptr, chunk, location)
end

function png_get_unknown_chunks(png_ptr, info_ptr, entries)
    ccall((:png_get_unknown_chunks, libpng), Cint, (png_const_structrp, png_inforp, png_unknown_chunkpp), png_ptr, info_ptr, entries)
end

function png_set_invalid(png_ptr, info_ptr, mask)
    ccall((:png_set_invalid, libpng), Cvoid, (png_const_structrp, png_inforp, Cint), png_ptr, info_ptr, mask)
end

function png_read_png(png_ptr, info_ptr, transforms, params)
    ccall((:png_read_png, libpng), Cvoid, (png_structrp, png_inforp, Cint, png_voidp), png_ptr, info_ptr, transforms, params)
end

function png_write_png(png_ptr, info_ptr, transforms, params)
    ccall((:png_write_png, libpng), Cvoid, (png_structrp, png_inforp, Cint, png_voidp), png_ptr, info_ptr, transforms, params)
end

function png_get_copyright(png_ptr)
    ccall((:png_get_copyright, libpng), png_const_charp, (png_const_structrp,), png_ptr)
end

function png_get_header_ver(png_ptr)
    ccall((:png_get_header_ver, libpng), png_const_charp, (png_const_structrp,), png_ptr)
end

function png_get_header_version(png_ptr)
    ccall((:png_get_header_version, libpng), png_const_charp, (png_const_structrp,), png_ptr)
end

function png_get_libpng_ver(png_ptr)
    ccall((:png_get_libpng_ver, libpng), png_const_charp, (png_const_structrp,), png_ptr)
end

function png_permit_mng_features(png_ptr, mng_features_permitted)
    ccall((:png_permit_mng_features, libpng), png_uint_32, (png_structrp, png_uint_32), png_ptr, mng_features_permitted)
end

function png_set_user_limits(png_ptr, user_width_max, user_height_max)
    ccall((:png_set_user_limits, libpng), Cvoid, (png_structrp, png_uint_32, png_uint_32), png_ptr, user_width_max, user_height_max)
end

function png_get_user_width_max(png_ptr)
    ccall((:png_get_user_width_max, libpng), png_uint_32, (png_const_structrp,), png_ptr)
end

function png_get_user_height_max(png_ptr)
    ccall((:png_get_user_height_max, libpng), png_uint_32, (png_const_structrp,), png_ptr)
end

function png_set_chunk_cache_max(png_ptr, user_chunk_cache_max)
    ccall((:png_set_chunk_cache_max, libpng), Cvoid, (png_structrp, png_uint_32), png_ptr, user_chunk_cache_max)
end

function png_get_chunk_cache_max(png_ptr)
    ccall((:png_get_chunk_cache_max, libpng), png_uint_32, (png_const_structrp,), png_ptr)
end

function png_set_chunk_malloc_max(png_ptr, user_chunk_cache_max)
    ccall((:png_set_chunk_malloc_max, libpng), Cvoid, (png_structrp, png_alloc_size_t), png_ptr, user_chunk_cache_max)
end

function png_get_chunk_malloc_max(png_ptr)
    ccall((:png_get_chunk_malloc_max, libpng), png_alloc_size_t, (png_const_structrp,), png_ptr)
end

function png_get_pixels_per_inch(png_ptr, info_ptr)
    ccall((:png_get_pixels_per_inch, libpng), png_uint_32, (png_const_structrp, png_const_inforp), png_ptr, info_ptr)
end

function png_get_x_pixels_per_inch(png_ptr, info_ptr)
    ccall((:png_get_x_pixels_per_inch, libpng), png_uint_32, (png_const_structrp, png_const_inforp), png_ptr, info_ptr)
end

function png_get_y_pixels_per_inch(png_ptr, info_ptr)
    ccall((:png_get_y_pixels_per_inch, libpng), png_uint_32, (png_const_structrp, png_const_inforp), png_ptr, info_ptr)
end

function png_get_x_offset_inches(png_ptr, info_ptr)
    ccall((:png_get_x_offset_inches, libpng), Cfloat, (png_const_structrp, png_const_inforp), png_ptr, info_ptr)
end

function png_get_x_offset_inches_fixed(png_ptr, info_ptr)
    ccall((:png_get_x_offset_inches_fixed, libpng), png_fixed_point, (png_const_structrp, png_const_inforp), png_ptr, info_ptr)
end

function png_get_y_offset_inches(png_ptr, info_ptr)
    ccall((:png_get_y_offset_inches, libpng), Cfloat, (png_const_structrp, png_const_inforp), png_ptr, info_ptr)
end

function png_get_y_offset_inches_fixed(png_ptr, info_ptr)
    ccall((:png_get_y_offset_inches_fixed, libpng), png_fixed_point, (png_const_structrp, png_const_inforp), png_ptr, info_ptr)
end

function png_get_pHYs_dpi(png_ptr, info_ptr, res_x, res_y, unit_type)
    ccall((:png_get_pHYs_dpi, libpng), png_uint_32, (png_const_structrp, png_const_inforp, Ptr{png_uint_32}, Ptr{png_uint_32}, Ptr{Cint}), png_ptr, info_ptr, res_x, res_y, unit_type)
end

function png_get_io_state(png_ptr)
    ccall((:png_get_io_state, libpng), png_uint_32, (png_const_structrp,), png_ptr)
end

function png_get_io_chunk_type(png_ptr)
    ccall((:png_get_io_chunk_type, libpng), png_uint_32, (png_const_structrp,), png_ptr)
end

function png_get_uint_32(buf)
    ccall((:png_get_uint_32, libpng), png_uint_32, (png_const_bytep,), buf)
end

function png_get_uint_16(buf)
    ccall((:png_get_uint_16, libpng), png_uint_16, (png_const_bytep,), buf)
end

function png_get_int_32(buf)
    ccall((:png_get_int_32, libpng), png_int_32, (png_const_bytep,), buf)
end

function png_get_uint_31(png_ptr, buf)
    ccall((:png_get_uint_31, libpng), png_uint_32, (png_const_structrp, png_const_bytep), png_ptr, buf)
end

function png_save_uint_32(buf, i)
    ccall((:png_save_uint_32, libpng), Cvoid, (png_bytep, png_uint_32), buf, i)
end

function png_save_int_32(buf, i)
    ccall((:png_save_int_32, libpng), Cvoid, (png_bytep, png_int_32), buf, i)
end

function png_save_uint_16(buf, i)
    ccall((:png_save_uint_16, libpng), Cvoid, (png_bytep, UInt32), buf, i)
end

function png_set_check_for_invalid_index(png_ptr, allowed)
    ccall((:png_set_check_for_invalid_index, libpng), Cvoid, (png_structrp, Cint), png_ptr, allowed)
end

function png_get_palette_max(png_ptr, info_ptr)
    ccall((:png_get_palette_max, libpng), Cint, (png_const_structp, png_const_infop), png_ptr, info_ptr)
end

function png_image_begin_read_from_file(image, file_name)
    ccall((:png_image_begin_read_from_file, libpng), Cint, (png_imagep, Cstring), image, file_name)
end

function png_image_begin_read_from_stdio(image, file)
    ccall((:png_image_begin_read_from_stdio, libpng), Cint, (png_imagep, Ptr{Cint}), image, file)
end

function png_image_begin_read_from_memory(image, memory, size)
    ccall((:png_image_begin_read_from_memory, libpng), Cint, (png_imagep, png_const_voidp, Csize_t), image, memory, size)
end

function png_image_finish_read(image, background, buffer, row_stride, colormap)
    ccall((:png_image_finish_read, libpng), Cint, (png_imagep, png_const_colorp, Ptr{Cvoid}, png_int_32, Ptr{Cvoid}), image, background, buffer, row_stride, colormap)
end

function png_image_free(image)
    ccall((:png_image_free, libpng), Cvoid, (png_imagep,), image)
end

function png_image_write_to_file(image, file, convert_to_8bit, buffer, row_stride, colormap)
    ccall((:png_image_write_to_file, libpng), Cint, (png_imagep, Cstring, Cint, Ptr{Cvoid}, png_int_32, Ptr{Cvoid}), image, file, convert_to_8bit, buffer, row_stride, colormap)
end

function png_image_write_to_stdio(image, file, convert_to_8_bit, buffer, row_stride, colormap)
    ccall((:png_image_write_to_stdio, libpng), Cint, (png_imagep, Ptr{Cint}, Cint, Ptr{Cvoid}, png_int_32, Ptr{Cvoid}), image, file, convert_to_8_bit, buffer, row_stride, colormap)
end

function png_image_write_to_memory(image, memory, memory_bytes, convert_to_8_bit, buffer, row_stride, colormap)
    ccall((:png_image_write_to_memory, libpng), Cint, (png_imagep, Ptr{Cvoid}, Ptr{png_alloc_size_t}, Cint, Ptr{Cvoid}, png_int_32, Ptr{Cvoid}), image, memory, memory_bytes, convert_to_8_bit, buffer, row_stride, colormap)
end

function png_set_option(png_ptr, option, onoff)
    ccall((:png_set_option, libpng), Cint, (png_structrp, Cint, Cint), png_ptr, option, onoff)
end


text:
    function PLacExampleUtility(ins)

        # Definition of the inputs for the ODEs
        if length(ins) == 1
            IPTG2,IPTG3 = ins[1];
        else
            IPTG2,IPTG3 = ins;
        end
        inputsMC = [0,IPTG2,IPTG3];

        # Solve ODEs
        solMC = PLacExample_SolveAll(tsMC, pD1MC, spMC, inputsMC, ivss1MC, sampsMC, pre1MC);

        # Extracte wanted vectors (observables) with time reduction
        Obs1_MC = solMC[:,2,:];
    Obs2_MC = 3 .*solMC[:,4,:];

        LowqObs1_MC = zeros(size(solMC)[1]);
    LowqObs2_MC = zeros(size(solMC)[1]);

        HighqObs1_MC = zeros(size(solMC)[1]);
    HighqObs2_MC = zeros(size(solMC)[1]);

        for i in 1:size(solMC)[1]
            LowqObs1_MC[i] = percentile(Obs1_MC[i,:],0.5);
    LowqObs2_MC[i] = percentile(Obs2_MC[i,:],0.5);

            HighqObs1_MC[i] = percentile(Obs1_MC[i,:],99.5);
    HighqObs2_MC[i] = percentile(Obs2_MC[i,:],99.5);

        end

        # Compute Euclidean distances
        EuObs1_MC = sqrt(sum((LowqObs1_MC-HighqObs1_MC).^2));
    EuObs2_MC = sqrt(sum((LowqObs2_MC-HighqObs2_MC).^2));

        util = (EuObs1_MC+EuObs2_MC)*(1/2);

        return(util)
    end

max_stars_repo_name: DavidGomezC/BOMBSbeta

max_issues_repo_name: DavidGomezC/BOMBSbeta

max_forks_repo_name: DavidGomezC/BOMBSbeta


text:
@coeff function solve!(reactor::Reactor, R_0_guess=nothing)
  @assert !reactor.solved

  @assert isa(R_0, SymEngine.Basic)
  @assert !isa(B_0, SymEngine.Basic)

  if reactor.steady
    solve_steady!(reactor)
  else
    solve_pulsed!(reactor, R_0_guess)
  end

  if isnan(reactor.R_0)
    reactor.valid = false
  else
    update!(reactor)
  end

  reactor.solved = true

  reactor
end


text:
module adapters_postgresql_repo_test

using Test # @test
using Octo.Adapters.PostgreSQL # Repo Schema Raw

struct Employee
end
Schema.model(Employee, table_name="Employee", primary_key="ID")

Repo.debug_sql()

@test_throws Repo.NeedsConnectError Repo.get(Employee, 2)

Repo.connect(
    adapter = Octo.Adapters.PostgreSQL,
    dbname = "postgresqltest",
    user = "postgres",
)

Repo.execute([DROP TABLE IF EXISTS Employee])
Repo.execute(Raw("""
    CREATE TABLE Employee (
        ID SERIAL,
        Name VARCHAR(255),
        Salary FLOAT(8),
        PRIMARY KEY (ID)
    )"""))

changes = (Name="John", Salary=10000.50)
Repo.insert!(Employee, changes)

Repo.execute(Raw("""INSERT INTO Employee (Name, Salary) VALUES (\$1, \$2)"""), changes)

multiple_changes = [
    (Name="Tom", Salary=20000.25),
    (Name="Jim", Salary=30000.00),
]
Repo.insert!(Employee, multiple_changes)

Repo.execute(Raw("""INSERT INTO Employee (Name, Salary) VALUES (\$1, \$2)"""), multiple_changes)

df = Repo.query(Employee)
@test size(df,) == (6,)

df = Repo.get(Employee, 2)
@test size(df) == (1,)
@test df[1].name == "John"

df = Repo.get(Employee, (Name="Tom",))
@test size(df) == (2,)
@test df[1].name == "Tom"

changes = (Name="Tim", Salary=15000.50)
Repo.insert!(Employee, changes)
df = Repo.query(Employee)
@test size(df) == (7,)
df = Repo.get(Employee, (Name="Tim",))
@test size(df) == (1,)
@test df[1].salary == 15000.50

changes = (ID=2, Name="Chloe", Salary=15000.50)
Repo.update!(Employee, changes)
df = Repo.get(Employee, 2)
@test df[1].name == "Chloe"

changes = (ID=2, Name="Chloe")
Repo.delete!(Employee, changes)
df = Repo.get(Employee, 2)
@test size(df) == (0,)

em = from(Employee)
df = Repo.query([SELECT * FROM em WHERE em.Name == "Tim"])
@test size(df) == (1,)
@test df[1].name == "Tim"

# coverage up
Schema.tables[Base.typename(Employee)] = Dict(:table_name => "Employee")
@test_throws Schema.PrimaryKeyError Repo.get(Employee, 2)
@test_throws Schema.PrimaryKeyError Repo.update!(Employee, (ID=2,))
Repo.insert!(Employee, Vector{NamedTuple}())

Repo.disconnect()

end # module adapters_postgresql_repo_test

# https://github.com/wookay/Octo.jl/issues/7
module adapters_postgresql_repo_insert_test

using Test # @test
using Octo.Adapters.PostgreSQL # Repo Schema Raw

struct Role
end
Schema.model(Role, table_name="roles")

Repo.debug_sql()

Repo.connect(
    adapter = Octo.Adapters.PostgreSQL,
    dbname = "postgresqltest",
    user = "postgres",
)

Repo.execute([DROP TABLE IF EXISTS Role])
Repo.execute(Raw("""
    CREATE TABLE roles(
      id SERIAL PRIMARY KEY,
      name VARCHAR(255)
    );
    """))
Repo.insert!(Role, (name="tom",))

df = Repo.query(Role)
@test size(df,) == (1,)

Repo.disconnect()

end # module adapters_postgresql_repo_insert_test