text:
@doc raw"""
    HessianProblem <: Problem

specify a problem for hessian based algorithms.

# Fields
* `M`            : a manifold $\mathcal M$
* `cost` : a function $F\colon\mathcal M\to\mathbb R$ to minimize
* `gradient`     : the gradient $\nabla F\colon\mathcal M
  \to \mathcal T\mathcal M$ of the cost function $F$
* `hessian`      : the hessian $\operatorname{Hess}[F] (\cdot)_ {x} \colon \mathcal T_{x} \mathcal M
  \to \mathcal T_{x} \mathcal M$ of the cost function $F$
* `precon`       : the symmetric, positive deﬁnite
    preconditioner (approximation of the inverse of the Hessian of $F$)

# See also
[`truncated_conjugate_gradient_descent`](@ref), [`trust_regions`](@ref)
"""
struct HessianProblem{mT <: Manifold} <: Problem
    M::mT
    cost::Function
    gradient::Function
    hessian::Union{Function,Missing}
    precon::Function
    HessianProblem(M::mT,cost::Function,grad::Function,hess::Union{Function,Missing},pre::Function) where {mT <: Manifold} = new{mT}(M,cost,grad,hess,pre)
end

abstract type HessianOptions <: Options end
#
# Options
#
@doc raw"""
    TruncatedConjugateGradientOptions <: HessianOptions

describe the Steihaug-Toint truncated conjugate-gradient method, with

# Fields
a default value is given in brackets if a parameter can be left out in initialization.

* `x` : a point, where the trust-region subproblem needs
    to be solved
* `stop` : a function s,r = @(o,iter,ξ,x,xnew) returning a stop
    indicator and a reason based on an iteration number, the gradient and the
    last and current iterates
* `η` : a tangent vector (called update vector), which solves the
    trust-region subproblem after successful calculation by the algorithm
* `δ` : search direction
* `Δ` : the trust-region radius
* `residual` : the gradient
* `useRand` : indicates if the trust-region solve and so the algorithm is to be
        initiated with a random tangent vector. If set to true, no
        preconditioner will be used. This option is set to true in some
        scenarios to escape saddle points, but is otherwise seldom activated.

# Constructor

    TruncatedConjugateGradientOptions(x, stop, eta, delta, Delta, res, uR)

construct a truncated conjugate-gradient Option with the fields as above.

# See also
[`truncated_conjugate_gradient_descent`](@ref), [`trust_regions`](@ref)
"""
mutable struct TruncatedConjugateGradientOptions{P,T} <: HessianOptions
    x::P
    stop::StoppingCriterion
    η::T
    δ::T
    Δ
    residual::T
    useRand::Bool
    function TruncatedConjugateGradientOptions(
        x::P,
        stop::StoppingCriterion,
        η::T,
        δ::T,
        Δ,
        residual::T,
        uR::Bool
        ) where {P, T}
        return new{typeof(x),typeof(η)}(x,stop,η,δ,Δ,residual,uR)
    end
end

@doc raw"""
    TrustRegionsOptions <: HessianOptions

describe the trust-regions solver, with

# Fields
a default value is given in brackets if a parameter can be left out in initialization.

* `x` : a point as starting point
* `stop` : a function s,r = @(o,iter) returning a stop
    indicator and a reason based on an iteration number and the gradient
* `Δ` : the (initial) trust-region radius
* `Δ_bar` : the maximum trust-region radius
* `useRand` : indicates if the trust-region solve is to be initiated with a
        random tangent vector. If set to true, no preconditioner will be
        used. This option is set to true in some scenarios to escape saddle
        points, but is otherwise seldom activated.
* `ρ_prime` : a lower bound of the performance ratio for the iterate that
        decides if the iteration will be accepted or not. If not, the
        trust-region radius will have been decreased. To ensure this,
        ρ'>= 0 must be strictly smaller than 1/4. If ρ' is negative,
        the algorithm is not guaranteed to produce monotonically decreasing
        cost values. It is strongly recommended to set ρ' > 0, to aid
        convergence.
* `ρ_regularization` : Close to convergence, evaluating the performance ratio ρ
        is numerically challenging. Meanwhile, close to convergence, the
        quadratic model should be a good fit and the steps should be
        accepted. Regularization lets ρ go to 1 as the model decrease and
        the actual decrease go to zero. Set this option to zero to disable
        regularization (not recommended). When this is not zero, it may happen
        that the iterates produced are not monotonically improving the cost
        when very close to convergence. This is because the corrected cost
        improvement could change sign if it is negative but very small.

# Constructor

    TrustRegionsOptions(x, stop, delta, delta_bar, uR, rho_prime, rho_reg)

construct a trust-regions Option with the fields as above.

# See also
[`trust_regions`](@ref)
"""
mutable struct TrustRegionsOptions <: HessianOptions
    x
    stop::StoppingCriterion
    Δ
    Δ_bar
    retraction::Function
    useRand::Bool
    ρ_prime
    ρ_regularization
    function TrustRegionsOptions(
        x,
        stop::StoppingCriterion,
        Δ,
        Δ_bar,
        retr::Function,
        useRand::Bool,
        ρ_prime,
        ρ_regularization
        )
        return new(x, stop, Δ, Δ_bar, retr, useRand, ρ_prime, ρ_regularization)
    end
end

@doc raw"""
    getHessian(p,x,ξ)

evaluate the Hessian of a [`HessianProblem`](@ref) `p` at the point `x`
applied to a tangent vector `ξ`.
"""
function getHessian(p::HessianProblem, x, ξ; stepsize=2*10^(-14))
    if ismissing(p.hessian)
        return approxHessianFD(p.M, x -> get_gradient(p.M,x) ,x,ξ; stepsize=stepsize)
    else
        return p.hessian(p.M,x,ξ)
    end
end

@doc raw"""
    get_gradient(p,x)

evaluate the gradient of a [`HessianProblem`](@ref)`p` at the
point `x`.
"""
get_gradient(p::HessianProblem,x) = p.gradient(p.M,x)
@doc raw"""
    get_preconditioner(p,x,ξ)

evaluate the symmetric, positive deﬁnite preconditioner (approximation of the
inverse of the Hessian of the cost function `F`) of a
[`HessianProblem`](@ref) `p` at the point `x`applied to a
tangent vector `ξ`.
"""
get_preconditioner(p::Pr, x, ξ) where {Pr <: HessianProblem} = p.precon(p.M, x, ξ)

@doc raw"""
    approxHessianFD(p,x,ξ,[stepsize=2.0^(-14)])

return an approximated solution of the Hessian of the cost function applied to
a tangent vector `ξ` by using a generic finite difference approximation
based on computations of the gradient.

Input
* `p` – a Manopt problem structure (already containing the manifold and enough
        information to compute the cost gradient)
* `x` – a point where the Hessian is to be approximated
* `ξ` – a tangent vector on which the approximated Hessian is to be applied

# Optional
* `stepsize` – the length of the step with which the method should work

# Output
* a tangent vector generated by applying the approximated Hessian to the
    tangent vector ξ
"""
function approxHessianFD(M::MT, x, gradFct::Function, ξ; stepsize=2.0^(-14), transport=ParallelTransport()) where {MT <: Manifold}
    norm_xi = norm(M,x,ξ)
    if norm_xi < eps(Float64)
        return zero_tangent_vector(M, x)
    end
    c = stepsize / norm_xi
    grad = gradFct(x)
    x1 = exp(M, x, ξ, c)
    grad1 = gradFct(x1)
    grad1 = vector_transport_to(M, x1, grad1, x, transport)
    return (1/c)*(grad1 - grad)
end

@doc raw"""
    stopIfResidualIsReducedByFactor <: StoppingCriterion

A functor for testing if the norm of residual at the current iterate is reduced
by a factor compared to the norm of the initial residual, i.e.
$\Vert r_k \Vert_x \leqq \kappa \Vert r_0 \Vert_x$.
In this case the algorithm reached linear convergence.

# Fields
* `κ` – the reduction factor
* `initialResidualNorm` - stores the norm of the residual at the initial vector
    $\eta$ of the Steihaug-Toint tcg mehtod [`truncated_conjugate_gradient_descent`](@ref)
* `reason` – stores a reason of stopping if the stopping criterion has one be
  reached, see [`get_reason`](@ref).

# Constructor

    stopIfResidualIsReducedByFactor(iRN, κ)

initialize the stopIfResidualIsReducedByFactor functor to indicate to stop after
the norm of the current residual is lesser than the norm of the initial residual
iRN times κ.

# See also
[`truncated_conjugate_gradient_descent`](@ref), [`trust_regions`](@ref)
"""
mutable struct stopIfResidualIsReducedByFactor <: StoppingCriterion
    κ::Float64
    initialResidualNorm::Float64
    reason::String
    stopIfResidualIsReducedByFactor(iRN::Float64,κ::Float64) = new(κ,iRN,"")
end
function (c::stopIfResidualIsReducedByFactor)(p::P,o::O,i::Int) where {P <: HessianProblem, O <: TruncatedConjugateGradientOptions}
    if norm(p.M, o.x, o.residual) <= c.initialResidualNorm*c.κ && i > 0
        c.reason = "The algorithm reached linear convergence (residual at least reduced by κ=$(c.κ)).\n"
        return true
    end
    return false
end

@doc raw"""
    stopIfResidualIsReducedByPower <: StoppingCriterion

A functor for testing if the norm of residual at the current iterate is reduced
by a power of 1+θ compared to the norm of the initial residual, i.e.
$\Vert r_k \Vert_x \leqq  \Vert r_0 \Vert_{x}^{1+\theta}$. In this case the
algorithm reached superlinear convergence.

# Fields
* `θ` – part of the reduction power
* `initialResidualNorm` - stores the norm of the residual at the initial vector
    $\eta$ of the Steihaug-Toint tcg mehtod [`truncated_conjugate_gradient_descent`](@ref)
* `reason` – stores a reason of stopping if the stopping criterion has one be
    reached, see [`get_reason`](@ref).

# Constructor

    stopIfResidualIsReducedByPower(iRN, θ)

initialize the stopIfResidualIsReducedByFactor functor to indicate to stop after
the norm of the current residual is lesser than the norm of the initial residual
iRN to the power of 1+θ.

# See also
[`truncated_conjugate_gradient_descent`](@ref), [`trust_regions`](@ref)
"""
mutable struct stopIfResidualIsReducedByPower <: StoppingCriterion
    θ::Float64
    initialResidualNorm::Float64
    reason::String
    stopIfResidualIsReducedByPower(iRN::Float64,θ::Float64) = new(θ,iRN,"")
end
function (c::stopIfResidualIsReducedByPower)(p::P,o::O,i::Int) where {P <: HessianProblem, O <: TruncatedConjugateGradientOptions}
    if norm(p.M, o.x, o.residual) <= c.initialResidualNorm^(1+c.θ) && i > 0
        c.reason = "The algorithm reached superlinear convergence (residual at least reduced by power 1 + θ=$(1+(c.θ))).\n"
        return true
    end
    return false
end

@doc raw"""
    StopWhenTrustRegionIsExceeded <: StoppingCriterion

A functor for testing if the norm of the next iterate in the  Steihaug-Toint tcg
mehtod is larger than the trust-region radius, i.e. $\Vert η_{k}^{*} \Vert_x
≧ Δ$. terminate the algorithm when the trust region has been left.

# Fields
* `reason` – stores a reason of stopping if the stopping criterion has one be
    reached, see [`get_reason`](@ref).
* `storage` – stores the necessary parameters `η, δ, residual` to check the
    criterion.

# Constructor

    StopWhenTrustRegionIsExceeded([a])

initialize the StopWhenTrustRegionIsExceeded functor to indicate to stop after
the norm of the next iterate is greater than the trust-region radius using the
[`StoreOptionsAction`](@ref) `a`, which is initialized to store
`:η, :δ, :residual` by default.

# See also
[`truncated_conjugate_gradient_descent`](@ref), [`trust_regions`](@ref)
"""
mutable struct StopWhenTrustRegionIsExceeded <: StoppingCriterion
    reason::String
    storage::StoreOptionsAction
    StopWhenTrustRegionIsExceeded(a::StoreOptionsAction=StoreOptionsAction( (:η, :δ, :residual) )) = new("", a)
end
function (c::StopWhenTrustRegionIsExceeded)(p::P,o::O,i::Int) where {P <: HessianProblem, O <: TruncatedConjugateGradientOptions}
    if has_storage(c.storage,:δ) && has_storage(c.storage,:η) && has_storage(c.storage,:residual)
        η = get_storage(c.storage,:η)
        δ = get_storage(c.storage,:δ)
        residual = get_storage(c.storage,:residual)
        a1 = inner(p.M, o.x, o.useRand ? get_preconditioner(p, o.x, residual) : residual, residual)
        a2 = inner(p.M, o.x, δ, getHessian(p, o.x, δ))
        a3 = inner(p.M, o.x, η, get_preconditioner(p, o.x, δ))
        a4 = inner(p.M, o.x, δ, get_preconditioner(p, o.x, δ))
        norm = inner(p.M, o.x, η, η) - 2*( a1 / a2 ) * a3 + (a1 / a2)^2 * a4
        if norm >= o.Δ^2 && i >= 0
            c.reason = "Trust-region radius violation (‖η‖² = $norm >= $(o.Δ^2) = Δ²). \n"
            c.storage(p,o,i)
            return true
        end
    end
    c.storage(p,o,i)
    return false
end

@doc raw"""
    StopWhenCurvatureIsNegative <: StoppingCriterion

A functor for testing if the curvature of the model is negative, i.e.
$\langle \delta_k, \operatorname{Hess}[F](\delta_k)\rangle_x \leqq 0$.
In this case, the model is not strictly convex, and the stepsize as computed
does not give a reduction of the model.

# Fields
* `reason` – stores a reason of stopping if the stopping criterion has one be
    reached, see [`get_reason`](@ref).
* `storage` – stores the necessary parameter `δ` to check the
    criterion.

# Constructor

    StopWhenCurvatureIsNegative([a])

initialize the StopWhenCurvatureIsNegative functor to indicate to stop after
the inner product of the search direction and the hessian applied on the search
dircetion is less than zero using the [`StoreOptionsAction`](@ref) `a`, which
is initialized to just store `:δ` by default.

# See also
[`truncated_conjugate_gradient_descent`](@ref), [`trust_regions`](@ref)
"""
mutable struct StopWhenCurvatureIsNegative <: StoppingCriterion
    reason::String
    storage::StoreOptionsAction
    StopWhenCurvatureIsNegative(a::StoreOptionsAction=StoreOptionsAction( (:δ, ) )) = new("", a)
end
function (c::StopWhenCurvatureIsNegative)(p::P,o::O,i::Int) where {P <: HessianProblem, O <: TruncatedConjugateGradientOptions}
    if has_storage(c.storage,:δ)
        δ = get_storage(c.storage,:δ)
        if inner(p.M, o.x, δ, getHessian(p, o.x, δ)) <= 0 && i > 0
            c.reason = "Negative curvature. The model is not strictly convex (⟨δ,Hδ⟩_x = $(inner(p.M, o.x, δ, getHessian(p, o.x, δ))) <= 0).\n"
            c.storage(p,o,i)
            return true
        end
    end
    c.storage(p,o,i)
    return false
end


text:
using ConstrainedLeastSquares
using Random
using Test

const CLSQ = ConstrainedLeastSquares
const Z = [
    (:a, [1.0, 1.9], [0.1, 0.1]),
    (:b, 1.0, 0.1),
    (:c, [2.9, 5.0], [0.1, 0.05])
]

@testset "creation of parameter index" begin
    target = Dict([:a => 1:2, :b => 3, :c => 4:5, :a_1 => 1, :a_2 => 2, :c_1 => 4, :c_2 => 5])
    @test CLSQ._build_index(Z) == target
    β = [
        (:a, [1.0, 1.9]),
        (:b, 1.0),
        (:c, [2.9, 5.0])
    ]
    @test CLSQ._build_index(β) == target
end

@testset "creation of parameter array" begin
    target = [1.0, 1.9, 1.0, 2.9, 5.0] # values defined from Z
    @test CLSQ._build_var_array(Z, 2) == target
    target = [0.1, 0.1, 0.1, 0.1, 0.05]  # uncertainties defined from Z
    @test CLSQ._build_var_array(Z, 3) == target
end

@testset "set covariance" begin
    z = [
        (:a, 1.5, 0.1),
        (:b, [2., 3.], [0.1, 0.14]),
        (:c, 4.0, 0.2)
    ]
    β = [(:A, 1.5)] # not needed here
    inp = LSQInput(β, z)

    @test_throws ArgumentError set_covariance!(inp, :a, :b, 10.0)
    set_covariance!(inp, :a, :c, 10.0)
    @test inp.Σ[1, 4] == inp.Σ[4, 1] == 10.0
    set_covariance!(inp, :b_1, :b_2, 20.0)
    @test inp.Σ[2, 3] == inp.Σ[3, 2] == 20.0
end

@testset "regression test with linear model" begin
    Random.seed!(42)
    # toy data
    N = 4
    xs = collect(Float64, 1:N) .+ randn(N)/10
    ys = xs * 2.2 .+ 3.1 .+ randn(N)/10

    # measured parameters
    z = [
        (:x, xs, 0.05xs),
        (:y, ys, 0.05ys)
    ]

    # unknown parameters
    β₀ = [
        (:a,  1.0),
        (:b,  1.0)
    ]

    linear_input = LSQInput(β₀, z)
    linear_model = @withinput linear_input begin
        return @. a*x + b - y
    end

    output = solve(linear_model, linear_input)

    @test output.χ²   ≈ 0.20962691792604748
    @test output.β[1] ≈ 2.113191779601563
    @test output.β[2] ≈ 3.3110566163534476
    @test uncertainty_β(output)[1] ≈ 0.21165344125510738
    @test uncertainty_β(output)[2] ≈ 0.419366917354832
end

@testset "regression test with example from Lars Nielsen 2001" begin
    # see Lars Nielsen, 2001: Evaluation of Measurements by the Method of Least Squares
    # measured parameters
    z = [
        (:ms, 199.988816, 0.000010), # known sum of weights in g
        (:mr, 199.999043, 0.000008), # reference weight in g
        (:ρr, 7833.01, 0.29), # densities in kg/m³
        (:ρ,  7965.76, 0.71),
        (:a, 1.1950, 0.0035), # air density
        (:I, [199.988617 # scale indication in "div"
            199.988608
            174.992133
            175.009992
            150.013558
            149.980675
            125.002083
            124.984217
            100.005650
            99.982925
            74.986433
            75.004325
            50.007892
            49.974992
            24.978533
            24.996417],
        ones(16)*2.3e-5),
        (:Ir, [199.998867, 199.998875], ones(2)*2.3e-5)
    ]

    # unknown parameters
    β₀ = [
        (:f,  1.0), # g per div
        (:A,  1.0), # non-linearity
        (:m1, 1.0), # mass 1 to 4
        (:m2, 1.0),
        (:m3, 1.0),
        (:m4, 1.0)
    ]

    mass_input = LSQInput(β₀, z);
    mass_model = @withinput mass_input begin
        mass_combinations = [
            m1 + m2 + m3 + m4 # I1
            m1 + m2 + m3 + m4 # I2
            m1 + m2 + m3      # I3
            m1 + m2 + m4      # I4
            m1 + m2           # I5
            m1 + m3 + m4      # I6
            m1 + m4           # I7
            m1 + m3           # I8
            m1                # I9
            m2 + m3 + m4      # I10
            m2 + m3           # I11
            m2 + m4           # I12
            m2                # I13
            m3 + m4           # I14
            m3                # I15
            m4                # I16
        ]
        return [
            @. mass_combinations*(1 - (a - 1.2)*(1/ρ - 1/8000)) - f*(I + A*I^2);
            @. mr*(1 - (a - 1.2)*(1/ρr - 1/8000)) - f*(Ir + A*Ir^2);
            ms - (m1 + m2 + m3 + m4)
        ]
    end
    output = solve(mass_model, mass_input; tol=1e-9);

    @test output.χ²   ≈ 8.070939437514037
    @test output.β[1] ≈ 1.0000018199321477 # estimated f
    @test output.β[3] ≈ 100.00577273693919 # estimated m1
    @test uncertainty_β(output)[1] ≈ 1.9030092538139585e-7 # estimated std. uncertainty f
    @test uncertainty_β(output)[3] ≈ 1.0989125630912822e-5 # estimated std. uncertainty m1
end

ext: jl


text:
#functions to generate a distance matrix from fasta
#using packages
using CSV
using BioSequences
using BioAlignments
using DataFrames
using FASTX

#create the substitution matrix, derived from Ali et al.
function sub_mat_ali(;submat_csv::String=joinpath(dirname(@__FILE__), "data_files", "ali_submat.csv"))
    ali_df = CSV.read(submat_csv)
    n = nrow(ali_df)

    #copy dataframe scale up and round so the values can be converted to integers
    ali_df_100 = copy(ali_df)
    for i in 1:n
        for j in 1:n
            ali_df_100[i,j] =  round(ali_df[i,j]*100, digits = 0)
        end
    end

    #copy PAM70 substitution matrix to new variable to use as a template for Ali matrix
    ALI_SUBMAT = copy(PAM70)

    #fill new submat based on df of Ali matrix, needs to use integers
    for i in 1:n
        for j in 1:n
            ALI_SUBMAT[i-1, j-1] = ali_df_100[i,j]
        end
    end
    return ALI_SUBMAT
end

#generate a distance matrix from an input fasta file
#uses substitution matrix from Ali et al, based on chemical differences and similiarities in amino acids
#fasta_file = file of fasta sequences to be compared
#output_file = location to store distance matrix as csv
#insert = penalty for insertion (default is 150, for reference substitutions range from 0-100)
#delete = penalty for deletion (default is 150, for reference, substitutions range from 0-100)
#describer = whether to have "identifer" from fasta file or "describer" from fasta file as the name of each sequence in the dataframe (default is identifer)
function dist_mat_gen(fasta_file::String, output_file::String="distance_matrix.csv";
    insert::Int64=150, delete::Int64=150, describer::String="identifier")
    #create empty matrices for the sequences, indentifies and descriptions
    repeat_matrix = LongSequence{AminoAcidAlphabet}[]
    identifier_matrix = String[]
    description_matrix = String[]

    #write sequence, description and identifier to respective arrays if necessary
    if describer == "identifier"
      open(FASTA.Reader, fasta_file) do reader
        for record in reader
            push!(repeat_matrix, sequence(record))
            push!(identifier_matrix, identifier(record))
        end
       end
    else
       open(FASTA.Reader, fasta_file) do reader
         for record in reader
            push!(repeat_matrix, sequence(record))
            push!(description_matrix, description(record))
        end
       end
    end

    #=
    open(FASTA.Reader, fasta_file) do reader
        for record in reader
            push!(repeat_matrix, sequence(record))
            push!(description_matrix, description(record))
            push!(identifier_matrix, identifier(record))
        end
    end
    =#

    #import distance matrix:
    ALI_SUBMAT = sub_mat_ali()

    #create cost model
    costmodel = CostModel(ALI_SUBMAT, insertion = insert, deletion = delete)

    #count number of repeats
    n = length(repeat_matrix)

    #create DataFrame to hold distances
    distance_array = fill(0.0, (n, n))
    distance_matrix = convert(DataFrame, distance_array)

    #name the columns in the data frame as either the identifier or the descritpion from fasta
    if describer == "identifier"
        rename!(distance_matrix, identifier_matrix)
    else
        rename!(distance_matrix, description_matrix)
    end

    for i in 1:n
        for j in 1:n
            alignment = distance(pairalign(EditDistance(), repeat_matrix[i], repeat_matrix[j], costmodel))
            distance_matrix[i,j] = alignment
        end
    end

    #write distance matrix to csv
    CSV.write(output_file, distance_matrix)
    println(string("output file is ", output_file))

    #return distance matrix
    return distance_matrix
end


text:
module PulseShapes
# provides unscaled pulse shapes for waveforms

import Base.tanh

"""
	constant(;pulse_length=0.0, sampling_rate=1.2e9)

Constant pulse shape for delays or square pulses.
"""
function constant(;pulse_length=0.0, sampling_rate=1.2e9)
	num_pts = round(UInt, pulse_length*sampling_rate)
	ones(Complex128, num_pts)
end

"""
	gaussian(;pulse_length=0.0, sampling_rate=1.2e9, cutoff=2.0)::Vector{Complex128}

Gaussian shaped pulse of a given pulse_length and sampling_rate going between -cutoff and cutoff σ wide.
Shape is shifted down to avoid finite cutoff step and start and end of pulse.
"""
function gaussian(;pulse_length=0.0, sampling_rate=1.2e9, cutoff=2.0)::Vector{Complex128}
	num_pts = round(UInt, pulse_length*sampling_rate)
	x_pts = linspace(-cutoff, cutoff, num_pts)
	# pull the pulse down so there is no bit step and the start/end of the pulse
	# i.e. find the shift such that the next point in the pulse would be zero
	x_step = x_pts[2] - x_pts[1]
	next_val = exp(-0.5 * (x_pts[1] - x_step)^2)
	shape = 1/(1-next_val) .* (exp.(-0.5 * (x_pts.^2)) - next_val)
	complex(shape)
end

@enum HALF_GAUSSIAN_DIRECTION HALF_GAUSSIAN_RISE HALF_GAUSSIAN_FALL

"""
	half_gaussian(;pulse_length=0.0, sampling_rate=1.2e9, cutoff=2.0, direction=HALF_GAUSSIAN_RISE)

A half gaussian pulse. Can be used as an excitation pulse but also used to round a square pulse.
"""

function half_gaussian(;pulse_length=0.0, sampling_rate=1.2e9, cutoff=2.0, direction::HALF_GAUSSIAN_DIRECTION=HALF_GAUSSIAN_RISE)
	num_pts = round(UInt, pulse_length*sampling_rate)
	x_pts = linspace(-cutoff, 0, num_pts)
	# pull the pulse down so there is no bit step and the start/end of the pulse
	# i.e. find the shift such that the next point in the pulse would be zero
	x_step = x_pts[2] - x_pts[1]
	next_val = exp(-0.5 * (x_pts[1] - x_step)^2)
	shape = 1/(1-next_val) .* (exp.(-0.5 * (x_pts.^2)) - next_val)
	if direction == HALF_GAUSSIAN_FALL
		reverse!(shape)
	end
	complex(shape)
end

"""
	drag(;pulse_length=0.0, sampling_rate=1.2e9, drag_scaling=1.0)::Vector{Complex128}

DRAG gaussian shape with -0.5 * (time derivative of gaussian) on the quadrature. The
derivative is scaled by `drag_scaling`.
"""
function drag(;pulse_length=0.0, sampling_rate=1.2e9, cutoff=2.0, drag_scaling=1.0)::Vector{Complex128}
	inphase = gaussian(;pulse_length=pulse_length, sampling_rate=sampling_rate, cutoff=cutoff)

	# d/dx of exp(-0.5 * x_pts.^2) = - x_pts * exp(-0.5 * x_pts.^2)
	# the time derivative needs a substitution rule from x -> t
	# where t is in units of sampling_rate
	# the pulse pulse_length in σ or x units is 2*cutoff so t = (num_points/(2*cutoff)) x
	num_pts = round(UInt, pulse_length*sampling_rate)
	x_pts = linspace(-cutoff, cutoff, num_pts)
	deriv_scale = 2*cutoff / num_pts
	quadrature = deriv_scale * drag_scaling * x_pts .* inphase
	complex(inphase + 1im*quadrature)
end

"""
	tanh(;pulse_length=0.0, sampling_rate=1.2e9, sigma=0.0, cutoff=2)::Vector{Complex128}

Square pulse with tanh rounded edges.
"""
function tanh(;pulse_length=0.0, sampling_rate=1.2e9, sigma=1e-9, cutoff=2)::Vector{Complex128}
	num_pts = round(UInt, pulse_length*sampling_rate)
	t = linspace(-pulse_length/2, pulse_length/2, num_pts)
	t₁ = -pulse_length/2 + cutoff*sigma
	t₂ = pulse_length/2 - cutoff*sigma
	shape = 0.5 * ( tanh.((t-t₁)/sigma) + tanh.((t₂-t)/sigma) )
	complex(shape)
end

"""
	exp_decay(;pulse_length=0.0, sampling_rate=1.2e9, sigma=1e-9, steady_state=0.5)::Vector{Complex128}

An exponentially decaying pulse to try and populate the cavity as quickly as possible.
But then don't overdrive it.
"""
function exp_decay(;pulse_length=0.0, sampling_rate=1.2e9, sigma=1e-9, steady_state=0.5)::Vector{Complex128}
	num_pts = round(UInt, pulse_length*sampling_rate)
	time_pts = (1.0/sampling_rate) * (0:num_pts-1)
	shape = steady_state + (1-steady_state)*exp(-time_pts / sigma)
	complex(shape)
end

"""
	CLEAR(;pulse_length=0.0, sampling_rate=1.2e9, sigma=0.0, steady_state=0.5, step_length=0.0, amp1=0.0, amp2=0.0)::Vector{Complex128}

Shape to quickly deplete the cavity at the end of a measurement.
Exponentially decaying measurement pulse followed by 2 steps of pulse_length `step_length` and amplitudes `amp1`, `amp2`.

Reference:

Rapid Driven Reset of a Qubit Readout Resonator

D. T. McClure, Hanhee Paik, L. S. Bishop, M. Steffen, Jerry M. Chow, and Jay M. Gambetta
Phys. Rev. Applied 5, 011001 – Published 27 January 2016 https://doi.org/10.1103/PhysRevApplied.5.011001
"""
function CLEAR(;pulse_length=0.0, sampling_rate=1.2e9, sigma=0.0, steady_state=0.5, step_length=0.0, amp1=0.0, amp2=0.0)::Vector{Complex128}
	meas_pulse = exp_decay(;pulse_length=pulse_length-2*step_length, sampling_rate=sampling_rate, sigma=sigma, steady_state=steady_state)
	num_pts_step = round(UInt, step_length*sampling_rate)
	clear_pulse1 = amp1 * ones(Complex128, num_pts_step)
	clear_pulse2 = amp2 * ones(Complex128, num_pts_step)
	[meas_pulse; clear_pulse1; clear_pulse2]
end

"""
	arb_axis_drag(;pulse_length=0.0, sampling_rate=1.2e9, nut_freq=10e6, rot_angle=0.0, polar_angle=0.0, drag_scaling=0.0)

Single-qubit arbitrary axis pulse implemented with phase ramping and frame change.
Parameters
    nutFreq: effective nutation frequency per unit of drive amplitude (Hz)
    rotAngle : effective rotation rotAngle (radians)
    polarAngle : polar angle of rotation axis (radians)
    aziAngle : azimuthal (radians)
"""
function arb_axis_drag(;pulse_length=0.0, sampling_rate=1.2e9, nut_freq=10e6, rot_angle=0.0, Θ=0.0, drag_scaling=0.0)::Vector{Complex128}
	if pulse_length > 0
		# start from a gaussian shaped pulse
		gauss_pulse = gaussian(pulse_length=pulse_length, sampling_rate=sampling_rate)
		# scale to achieve to the desired rotation
		cal_scale = (rot_angle/2/pi)*sampling_rate/sum(gauss_pulse)
		# calculate the phase ramp steps to achieve the desired Z component to the rotation axis
		phase_steps = -2π*cos(Θ)*cal_scale*gauss_pulse/sampling_rate
		# Calculate Z DRAG correction to phase steps
		# β is a conversion between XY drag scaling and Z drag scaling
		β = drag_scaling/sampling_rate
		instantaneous_detuning = β * (2π*cal_scale*sin(Θ)*gauss_pulse).^2
		phase_steps += instantaneous_detuning*(1/sampling_rate)
		#center phase ramp around the middle of the pulse time steps
		phase_ramp = cumsum(phase_steps) - phase_steps/2
		shape = (1/nut_freq)*sin(Θ)*cal_scale*gauss_pulse.*exp(1im*phase_ramp)
	elseif abs(Θ) <1e-10
		#Otherwise assume we have a zero-length Z rotation
		shape = Vector{Complex128}()
	else
		error("Non-zero transverse rotation with zero-length pulse.")
	end
	complex(shape)
end
end


text:
# This file was generated, do not modify it. # hide
knn = machine(KnnPipe, Xtrain, ytrain)
multi = machine(MnPipe, Xtrain, ytrain)


text:
convert{T<:AbstractString}(::Type{JString}, str::T) = JString(str)
convert{T<:AbstractString}(::Type{JObject}, str::T) = convert(JObject, JString(str))

#Cast java object from S to T . Needed for polymorphic calls
function convert{T,S}(::Type{JavaObject{T}}, obj::JavaObject{S})
    if isConvertible(T, S)   #Safe static cast
        ptr = ccall(jnifunc.NewLocalRef, Ptr{Void}, (Ptr{JNIEnv}, Ptr{Void}), penv, obj.ptr)
        if ptr === C_NULL geterror() end
        return JavaObject{T}(ptr)
    end
    if isnull(obj) ; error("Cannot convert NULL"); end
    realClass = ccall(jnifunc.GetObjectClass, Ptr{Void}, (Ptr{JNIEnv}, Ptr{Void} ), penv, obj.ptr)
    if isConvertible(T, realClass)  #dynamic cast
        ptr = ccall(jnifunc.NewLocalRef, Ptr{Void}, (Ptr{JNIEnv}, Ptr{Void}), penv, obj.ptr)
        if ptr === C_NULL geterror() end
        return JavaObject{T}(ptr)
    end
    error("Cannot cast java object from $S to $T")
end

#Is java type convertible from S to T.
isConvertible(T, S) = (ccall(jnifunc.IsAssignableFrom, jboolean, (Ptr{JNIEnv}, Ptr{Void}, Ptr{Void}), penv, metaclass(S), metaclass(T) ) == JNI_TRUE)
isConvertible(T, S::Ptr{Void} ) = (ccall(jnifunc.IsAssignableFrom, jboolean, (Ptr{JNIEnv}, Ptr{Void}, Ptr{Void}), penv, S, metaclass(T) ) == JNI_TRUE)

unsafe_convert(::Type{Ptr{Void}}, cls::JavaMetaClass) = cls.ptr

# Get the JNI/C type for a particular Java type
function real_jtype(rettype)
    if issubtype(rettype, JavaObject) || issubtype(rettype, Array) || issubtype(rettype, JavaMetaClass)
        jnitype = Ptr{Void}
    else
        jnitype = rettype
    end
    return jnitype
end

function convert_args(argtypes::Tuple, args...)
    convertedArgs = Array(Int64, length(args))
    savedArgs = Array(Any, length(args))
    for i in 1:length(args)
        r = convert_arg(argtypes[i], args[i])
        savedArgs[i] = r[1]
        convertedArgs[i] = jvalue(r[2])
    end
    return savedArgs, convertedArgs
end

function convert_arg(argtype::Type{JString}, arg)
    x = convert(JString, arg)
    return x, x.ptr
end

function convert_arg(argtype::Type, arg)
    x = convert(argtype, arg)
    return x,x
end
function convert_arg{T<:JavaObject}(argtype::Type{T}, arg)
    x = convert(T, arg)::T
    return x, x.ptr
end

for (x, y, z) in [ (:jboolean, :(jnifunc.NewBooleanArray), :(jnifunc.SetBooleanArrayRegion)),
                  (:jchar, :(jnifunc.NewCharArray), :(jnifunc.SetCharArrayRegion)),
                  (:jbyte, :(jnifunc.NewByteArray), :(jnifunc.SetByteArrayRegion)),
                  (:jshort, :(jnifunc.NewShortArray), :(jnifunc.SetShortArrayRegion)),
                  (:jint, :(jnifunc.NewIntArray), :(jnifunc.SetShortArrayRegion)),
                  (:jlong, :(jnifunc.NewLongArray), :(jnifunc.SetLongArrayRegion)),
                  (:jfloat, :(jnifunc.NewFloatArray), :(jnifunc.SetFloatArrayRegion)),
                  (:jdouble, :(jnifunc.NewDoubleArray), :(jnifunc.SetDoubleArrayRegion)) ]
    m = quote
        function convert_arg(argtype::Type{Array{$x,1}}, arg)
            carg = convert(argtype, arg)
            sz=length(carg)
            arrayptr = ccall($y, Ptr{Void}, (Ptr{JNIEnv}, jint), penv, sz)
            ccall($z, Void, (Ptr{JNIEnv}, Ptr{Void}, jint, jint, Ptr{$x}), penv, arrayptr, 0, sz, carg)
            return carg, arrayptr
        end
    end
    eval( m)
end

function convert_arg{T<:JavaObject}(argtype::Type{Array{T,1}}, arg)
    carg = convert(argtype, arg)
    sz=length(carg)
    init=carg[1]
    arrayptr = ccall(jnifunc.NewObjectArray, Ptr{Void}, (Ptr{JNIEnv}, jint, Ptr{Void}, Ptr{Void}), penv, sz, metaclass(T), init.ptr)
    for i=2:sz
        ccall(jnifunc.SetObjectArrayElement, Void, (Ptr{JNIEnv}, Ptr{Void}, jint, Ptr{Void}), penv, arrayptr, i-1, carg[i].ptr)
    end
    return carg, arrayptr
end

convert_result{T<:JString}(rettype::Type{T}, result) = unsafe_string(JString(result))
convert_result{T<:JavaObject}(rettype::Type{T}, result) = T(result)
convert_result(rettype, result) = result

for (x, y, z) in [ (:jboolean, :(jnifunc.GetBooleanArrayElements), :(jnifunc.ReleaseBooleanArrayElements)),
                  (:jchar, :(jnifunc.GetCharArrayElements), :(jnifunc.ReleaseCharArrayElements)),
                  (:jbyte, :(jnifunc.GetByteArrayElements), :(jnifunc.ReleaseByteArrayElements)),
                  (:jshort, :(jnifunc.GetShortArrayElements), :(jnifunc.ReleaseShortArrayElements)),
                  (:jint, :(jnifunc.GetIntArrayElements), :(jnifunc.ReleaseIntArrayElements)),
                  (:jlong, :(jnifunc.GetLongArrayElements), :(jnifunc.ReleaseLongArrayElements)),
                  (:jfloat, :(jnifunc.GetFloatArrayElements), :(jnifunc.ReleaseFloatArrayElements)),
                  (:jdouble, :(jnifunc.GetDoubleArrayElements), :(jnifunc.ReleaseDoubleArrayElements)) ]
    m=quote
        function convert_result(rettype::Type{Array{$(x),1}}, result)
            sz = ccall(jnifunc.GetArrayLength, jint, (Ptr{JNIEnv}, Ptr{Void}), penv, result)
            arr = ccall($(y), Ptr{$(x)}, (Ptr{JNIEnv}, Ptr{Void}, Ptr{jboolean} ), penv, result, C_NULL )
            jl_arr::Array = unsafe_wrap(Array, arr, (@compat Int(sz)), false)
            jl_arr = deepcopy(jl_arr)
            ccall($(z), Void, (Ptr{JNIEnv},Ptr{Void}, Ptr{$(x)}, jint), penv, result, arr, 0)
            return jl_arr
        end
    end
    eval(m)
end

function convert_result{T}(rettype::Type{Array{JavaObject{T},1}}, result)
    sz = ccall(jnifunc.GetArrayLength, jint, (Ptr{JNIEnv}, Ptr{Void}), penv, result)

    ret = Array(JavaObject{T}, sz)

    for i=1:sz
        a=ccall(jnifunc.GetObjectArrayElement, Ptr{Void}, (Ptr{JNIEnv},Ptr{Void}, jint), penv, result, i-1)
        ret[i] = JavaObject{T}(a)
    end
    return ret
end

#The second term in this addition is due to the fact that Java converts all times to local time
convert(::Type{DateTime}, x::@jimport(java.util.Date)) = isnull(x)?Dates.DateTime(1970,1,1,0,0,0):
            (Dates.unix2datetime(jcall(x, "getTime", jlong, ())/1000) +
                    Second(round(div(Dates.value(now() - now(Dates.UTC)),1000)/900)*(900)))

function convert(::Type{DateTime}, x::JavaObject)
    if isnull(x); return Dates.DateTime(1970,1,1,0,0,0); end
    JDate = @jimport(java.util.Date)
    if isConvertible(JDate, x)
        return convert(DateTime, convert(JDate, x))
    elseif isConvertible(@jimport(java.util.Calendar), x)
        return convert(DateTime, jcall(x, "getTime", JDate, ()))
    end
end

function convert(::Type{@jimport(java.util.Properties)}, x::Dict)
    Properties = @jimport(java.util.Properties)
    p = Properties(())
    for (n,v) in x
        jcall(p, "setProperty", @jimport(java.lang.Object), (JString, JString), n, v)
    end
    return p
end

function convert{X,Y}(::Type{@jimport(java.util.HashMap)}, K::Type{JavaObject{X}}, V::Type{JavaObject{Y}}, x::Dict)
    Hashmap = @jimport(java.util.HashMap)
    p = Hashmap(())
    for (n,v) in x
        jcall(p, "put", @jimport(java.lang.Object), (JObject, JObject), n, v)
    end
    return p
end

convert{X,Y}(::Type{@jimport(java.util.Map)}, K::Type{JavaObject{X}}, V::Type{JavaObject{Y}}, x::Dict) = convert(@jimport(java.util.Map), convert(@jimport(java.util.HashMap), K, V, x))

# Convert a reference to a java.lang.String into a Julia string. Copies the underlying byte buffer
function unsafe_string(jstr::JString)  #jstr must be a jstring obtained via a JNI call
    if isnull(jstr); return ""; end #Return empty string to keep type stability. But this is questionable
    pIsCopy = Array(jboolean, 1)
    buf::Ptr{UInt8} = ccall(jnifunc.GetStringUTFChars, Ptr{UInt8}, (Ptr{JNIEnv}, Ptr{Void}, Ptr{jboolean}), penv, jstr.ptr, pIsCopy)
    s=unsafe_string(buf)
    ccall(jnifunc.ReleaseStringUTFChars, Void, (Ptr{JNIEnv}, Ptr{Void}, Ptr{UInt8}), penv, jstr.ptr, buf)
    return s
end

#This is necessary to properly deprecate bytestring in 0.5, while ensuring
# callers don't need to change for 0.4.
function Base.bytestring(jstr::JString)  #jstr must be a jstring obtained via a JNI call
    if VERSION >= v"0.5.0-dev+4612"
        Base.depwarn("bytestring(jstr::JString) is deprecated. Use unsafe_string(jstr) instead", :bytestring )
    end
    return JavaCall.unsafe_string(jstr)
end

for (x, y, z) in [ (:jboolean, :(jnifunc.GetBooleanArrayElements), :(jnifunc.ReleaseBooleanArrayElements)),
                  (:jchar, :(jnifunc.GetCharArrayElements), :(jnifunc.ReleaseCharArrayElements)),
                  (:jbyte, :(jnifunc.GetByteArrayElements), :(jnifunc.ReleaseByteArrayElements)),
                  (:jshort, :(jnifunc.GetShortArrayElements), :(jnifunc.ReleaseShortArrayElements)),
                  (:jint, :(jnifunc.GetIntArrayElements), :(jnifunc.ReleaseIntArrayElements)),
                  (:jlong, :(jnifunc.GetLongArrayElements), :(jnifunc.ReleaseLongArrayElements)),
                  (:jfloat, :(jnifunc.GetFloatArrayElements), :(jnifunc.ReleaseFloatArrayElements)),
                  (:jdouble, :(jnifunc.GetDoubleArrayElements), :(jnifunc.ReleaseDoubleArrayElements)) ]
    m=quote
        function convert(::Type{Array{$(x),1}}, obj::JObject)
            sz = ccall(jnifunc.GetArrayLength, jint, (Ptr{JNIEnv}, Ptr{Void}), penv, obj.ptr)
            arr = ccall($(y), Ptr{$(x)}, (Ptr{JNIEnv}, Ptr{Void}, Ptr{jboolean} ), penv, obj.ptr, C_NULL )
            jl_arr::Array = unsafe_wrap(Array, arr, (@compat Int(sz)), false)
            jl_arr = deepcopy(jl_arr)
            ccall($(z), Void, (Ptr{JNIEnv},Ptr{Void}, Ptr{$(x)}, jint), penv, obj.ptr, arr, 0)
            return jl_arr
        end
    end
    eval(m)
end

function convert{T}(::Type{Array{T, 1}}, obj::JObject)
    sz = ccall(jnifunc.GetArrayLength, jint,
               (Ptr{JNIEnv}, Ptr{Void}), penv, obj.ptr)
    ret = Array(T, sz)
    for i=1:sz
        ptr = ccall(jnifunc.GetObjectArrayElement, Ptr{Void},
                  (Ptr{JNIEnv}, Ptr{Void}, jint), penv, obj.ptr, i-1)
        ret[i] = convert(T, JObject(ptr))
    end
    return ret
end


text:
abstract type AbstractBoundaryScalingFunction <: AbstractScalingFunction end

struct LeftScalingFunction <: AbstractBoundaryScalingFunction
    values::OffsetArrays.OffsetVector{Float64, Vector{Float64}}
    support::Vector{DyadicRational}
    vanishing_moments::Int64
    index::Int64
    resolution::Int64

    function LeftScalingFunction(values, p, index, scale)
        if p < 0
			throw(DomainError(p, "Vanishing moments must be positive"))
        end

        if scale < 0
			throw(DomainError(scale, "Resolution must be positive"))
        end

        if !(0 <= index < p)
			throw(DomainError(index, "Index should be between 0 and " * p - 1))
        end

        support = DyadicRational.(0:length(values) - 1, scale)
        new(values, support, p, index, scale)
    end
end

function Base.show(io::IO, L::LeftScalingFunction)
    print(io, "Left scaling function number $(index(L)) with $(vanishing_moments(L)) vanishing moments at resolution $(resolution(L))")
end

struct RightScalingFunction <: AbstractBoundaryScalingFunction
    values::OffsetArrays.OffsetVector{Float64, Vector{Float64}}
    support::Vector{DyadicRational}
    vanishing_moments::Int64
    index::Int64
    resolution::Int64

    function RightScalingFunction(values, p, index, scale)
        if p < 0
			throw(DomainError(p, "Vanishing moments must be positive"))
        end

        if scale < 0
			throw(DomainError(scale, "Resolution must be positive"))
        end

        if !(0 <= index < p)
			throw(DomainError(index, "Index should be between 0 and " * p - 1))
        end

        support = DyadicRational.(-length(values) + 1:0, scale)
        new(values, support, p, index, scale)
    end
end

function Base.show(io::IO, R::RightScalingFunction)
    print(io, "Right scaling function number $(index(L)) with $(vanishing_moments(L)) vanishing moments at resolution $(resolution(L))")
end

index(phi::AbstractBoundaryScalingFunction) = phi.index
vanishing_moments(phi::AbstractBoundaryScalingFunction) = phi.vanishing_moments
support_boundaries(phi::LeftScalingFunction) = 0, vanishing_moments(phi) + index(phi)
support_boundaries(phi::RightScalingFunction) = -(vanishing_moments(phi) + index(phi)), 0

# It is not possible to have a functor for an abstract type
(phi::LeftScalingFunction)(x::DyadicRational) = get_value(phi, x)
(phi::RightScalingFunction)(x::DyadicRational) = get_value(phi, x)

struct BoundaryScalingFunctions{T <: AbstractBoundaryScalingFunction}
    functions::Vector{T}
    filters::BoundaryFilters
    phi::InteriorScalingFunction
    scale::Int64
    side::Sides

    function BoundaryScalingFunctions(functions, filter, phi, scale, side)
        p = length(functions)

        if length(functions) != vanishing_moments(filter)
			throw(DomainError(p, "The number of vanishing moments of the filter should equal the number of functions"))
        end

        if vanishing_moments(filter) != vanishing_moments(phi)
            throw(DomainError(p, "The filter and the Interior scaling function should have the same number of vanishing moments"))
        end

        if scale < 0
			throw(DomainError(scale, "Scale must be positive"))
        end

        if support_boundaries(phi) != (-p + 1, p)
            ErrorException("Interior scaling function has wrong domain")
        end

        new{eltype(functions)}(functions, filter, phi, scale, side)
    end
end

function Base.show(io::IO, B::BoundaryScalingFunctions)
    print(io, "$(side(B)) scaling functions with $(vanishing_moments(B)) vanishing moments at resolution $(resolution(B))")
end

functions(Phi::BoundaryScalingFunctions) = Phi.functions
filters(Phi::BoundaryScalingFunctions) = Phi.filters
vanishing_moments(Phi::BoundaryScalingFunctions) = Phi |> functions |> length
interior(Phi::BoundaryScalingFunctions) = Phi.phi
side(Phi::BoundaryScalingFunctions) = Phi.side
resolution(Phi::BoundaryScalingFunctions) = Phi.scale
Base.getindex(Phi::BoundaryScalingFunctions, idx::Integer) = functions(Phi)[idx + 1]

Base.iterate(Phi::BoundaryScalingFunctions) = Phi[0], 1
Base.iterate(Phi::BoundaryScalingFunctions, state) = state > length(Phi) ? nothing : (Phi[state], state + 1)
Base.length(Phi::BoundaryScalingFunctions) = length(functions(Phi)) - 1

function initialize_boundary_scaling_functions(b::BoundaryFilters, phi::InteriorScalingFunction, R::Integer)
    p = vanishing_moments(b)

    if side(b) == LEFT
        Y = [LeftScalingFunction(
                OffsetArrays.OffsetVector{Float64}(undef, 0:2^R*(p + k)), p, k, R
            ) for k = 0:p - 1]
    elseif side(b) == RIGHT
        Y = [RightScalingFunction(
                OffsetArrays.OffsetVector{Float64}(undef, -2^R*(p + k):0), p, k, R
            ) for k = 0:p - 1]
    end

    BoundaryScalingFunctions(Y, b, phi, R, side(b))
end

function support_union(Phi::BoundaryScalingFunctions)
    p = vanishing_moments(Phi)
    support(Phi[p - 1])
end

function sorted_support_union(Phi::BoundaryScalingFunctions{LeftScalingFunction})
    support_union(Phi) |> reverse
end

function sorted_support_union(Phi::BoundaryScalingFunctions{RightScalingFunction})
    support_union(Phi)
end

function supports(Phi::BoundaryScalingFunctions)
    p = vanishing_moments(Phi)
    [support(Phi[k]) for k = 0:p - 1]
end

function boundary_scaling_functions(b::BoundaryFilters, phi::InteriorScalingFunction)
    Phi = initialize_boundary_scaling_functions(b, phi, 0)

    p = vanishing_moments(Phi)

    support_values = sorted_support_union(Phi)

    for x in support_values
        for k in p-1:-1:0
            if x ∉ support(Phi[k])
                continue
            end

            phi_val = 0.0

            # Boundary contribution
            for l in 0:p - 1
                phi_val += filters(Phi)[k][l] * Phi[l](2*x)
            end

            # Interior contribution
            for m in p:p + 2k
                phi_val += filters(Phi)[k][m] * phi(2*x - interior_translation(m, side(b)))
            end

            set_value!(Phi[k], x, sqrt2 * phi_val)
        end
    end

    for k in 0:p - 1
        set_value!(Phi[k], 0, 0.0)
    end

    return Phi
end

@inline function interior_translation(m::Integer, side::Sides)
    side == LEFT ? m : -m - 1
end

function boundary_scaling_functions(side::Sides, p::Integer, R::Integer)
    h = interior_filter(p)
    phi = interior_scaling_function(h, R)

    b = boundary_filters(p, side)

    boundary_scaling_functions(b, phi, R)
end

function boundary_scaling_functions(b::BoundaryFilters, phi::InteriorScalingFunction, R::Integer)
    if R < 0
        throw(DomainError(R, "Resolution must be non-negative"))
    end

    Phi = boundary_scaling_functions(b::BoundaryFilters, phi::InteriorScalingFunction)

    for _ = 1:R
        Phi = increase_resolution(Phi)
    end

    compute_edge_value!(Phi)

    return Phi
end

function increase_resolution(Phi::BoundaryScalingFunctions)
    phi = interior(Phi)
    Phi2 = initialize_boundary_scaling_functions(filters(Phi), phi, resolution(Phi) + 1)

    p = vanishing_moments(Phi)

    for k in 0:p - 1
        for (index, x) in enumerate(support(Phi2[k]))
            if isodd(index)
                set_value!(Phi2[k], x, Phi[k](x))
                continue
            end

            phi_val = 0.0
            # Boundary contribution
            for l in 0:p - 1
                phi_val += filters(Phi)[k][l] * Phi[l](2*x)
            end

            # Interior contribution
            for m in p:p + 2k
                phi_val += filters(Phi)[k][m] * phi(2*x - interior_translation(m, side(Phi)))
            end

            set_value!(Phi2[k], x, sqrt2 * phi_val)
        end
    end

    return Phi2
end

function compute_edge_value!(Phi)
    p = vanishing_moments(Phi)
    R = resolution(Phi)
    if R <= ceil(log2(p))
        return Phi
    end

    x = sign(side(Phi)) * DyadicRational.(1:p, R)
    representation_matrix = [Phi[j](x[i]) for i = 1:p, j = 0:p - 1]
    basis_coeff = representation_matrix \ ones(p)

    filter_matrix = [sqrt2 * filters(Phi)[i][j] for i = 0:p - 1, j = 0:p - 1]
    scaled_function_values = eigval1(filter_matrix)

    scaling_factor = LinearAlgebra.dot(basis_coeff, scaled_function_values)

    function_values = scaled_function_values ./ scaling_factor

    for index in 1:p
        set_value!(Phi.functions[index], DyadicRational(0,0), function_values[index])
    end

    return Phi
end

@recipe function plot(phi::BoundaryScalingFunctions)
    for y in phi
        @series begin
            collect(y)
        end
    end
end


text:
# Parts of this code were taken / derived from Graphs.jl. See LICENSE for
# licensing details.

type FloydWarshallState{T}<:AbstractPathState
    dists::Matrix{T}
    parents::Matrix{Int}
end

doc"""Uses the [Floyd-Warshall algorithm](http://en.wikipedia.org/wiki/Floyd–Warshall_algorithm)
to compute shortest paths between all pairs of vertices in graph `g`. Returns a
`FloydWarshallState` with relevant traversal information, each is a
vertex-indexed vector of vectors containing the metric for each vertex in the
graph.

Note that this algorithm may return a large amount of data (it will allocate
on the order of $\mathcal{O}(nv^2)$).
"""
function floyd_warshall_shortest_paths{T}(
    g::SimpleGraph,
    distmx::AbstractArray{T, 2} = DefaultDistance()
)

    n_v = nv(g)
    dists = fill(typemax(T), (n_v,n_v))
    parents = zeros(Int, (n_v,n_v))

    # fws = FloydWarshallState(Matrix{T}(), Matrix{Int}())
    for v in 1:n_v
        dists[v,v] = zero(T)
    end
    undirected = !is_directed(g)
    for e in edges(g)
        u = src(e)
        v = dst(e)

        d = distmx[u,v]

        dists[u,v] = min(d, dists[u,v])
        parents[u,v] = u
        if undirected
            dists[v,u] = min(d, dists[v,u])
            parents[v,u] = v
        end
    end
    for w in vertices(g), u in vertices(g), v in vertices(g)
        if dists[u,w] == typemax(T) || dists[w,v] == typemax(T)
            ans = typemax(T)
        else
            ans = dists[u,w] + dists[w,v]
        end
        if dists[u,v] > ans
            dists[u,v] = dists[u,w] + dists[w,v]
            parents[u,v] = parents[w,v]
        end
    end
    fws = FloydWarshallState(dists, parents)
    # for r in 1:size(parents,1)    # row by row
    #     push!(fws.parents, vec(parents[r,:]))
    # end
    # for r in 1:size(dists,1)
    #     push!(fws.dists, vec(dists[r,:]))
    # end

    return fws
end

function enumerate_paths(s::FloydWarshallState, v::Integer)
    pathinfo = s.parents[v,:]
    paths = Vector{Int}[]
    for i in 1:length(pathinfo)
        if i == v
            push!(paths, Vector{Int}())
        else
            path = Vector{Int}()
            currpathindex = i
            while currpathindex != 0
                push!(path,currpathindex)
                currpathindex = pathinfo[currpathindex]
            end
            push!(paths, reverse(path))
        end
    end
    return paths
end

enumerate_paths(s::FloydWarshallState) = [enumerate_paths(s, v) for v in 1:size(s.parents,1)]
enumerate_paths(st::FloydWarshallState, s::Integer, d::Integer) = enumerate_paths(st, s)[d]


text:
# Automatically generated using Clang.jl wrap_c

# Skipping MacroDefinition: RCUTILS_CHECK_ALLOCATOR ( allocator , fail_statement ) if ( ! rcutils_allocator_is_valid ( allocator ) ) { fail_statement ; }
# Skipping MacroDefinition: RCUTILS_CHECK_ALLOCATOR_WITH_MSG ( allocator , msg , fail_statement ) if ( ! rcutils_allocator_is_valid ( allocator ) ) { RCUTILS_SET_ERROR_MSG ( msg ) ; fail_statement ; }

struct rcutils_allocator_t
    allocate::Ptr{Cvoid}
    deallocate::Ptr{Cvoid}
    reallocate::Ptr{Cvoid}
    zero_allocate::Ptr{Cvoid}
    state::Ptr{Cvoid}
end

# Skipping MacroDefinition: RCUTILS_SAFE_FWRITE_TO_STDERR ( msg ) do { fwrite ( msg , sizeof ( char ) , strlen ( msg ) , stderr ) ; } while ( 0 )

const RCUTILS_ERROR_STATE_LINE_NUMBER_STR_MAX_LENGTH = 20
const RCUTILS_ERROR_FORMATTING_CHARACTERS = 6
const RCUTILS_ERROR_MESSAGE_MAX_LENGTH = 1024
const RCUTILS_ERROR_STATE_MESSAGE_MAX_LENGTH = 768
const RCUTILS_ERROR_STATE_FILE_MAX_LENGTH = (((RCUTILS_ERROR_MESSAGE_MAX_LENGTH - RCUTILS_ERROR_STATE_MESSAGE_MAX_LENGTH) - RCUTILS_ERROR_STATE_LINE_NUMBER_STR_MAX_LENGTH) - RCUTILS_ERROR_FORMATTING_CHARACTERS) - 1

# Skipping MacroDefinition: RCUTILS_CHECK_ARGUMENT_FOR_NULL ( argument , error_return_type ) RCUTILS_CHECK_FOR_NULL_WITH_MSG ( argument , # argument " argument is null" , return error_return_type )
# Skipping MacroDefinition: RCUTILS_CHECK_FOR_NULL_WITH_MSG ( value , msg , error_statement ) do { if ( NULL == value ) { RCUTILS_SET_ERROR_MSG ( msg ) ; error_statement ; } } while ( 0 )
# Skipping MacroDefinition: RCUTILS_SET_ERROR_MSG ( msg ) do { rcutils_set_error_state ( msg , __FILE__ , __LINE__ ) ; } while ( 0 )
# Skipping MacroDefinition: RCUTILS_SET_ERROR_MSG_WITH_FORMAT_STRING ( format_string , ... ) do { char output_msg [ RCUTILS_ERROR_MESSAGE_MAX_LENGTH ] ; int ret = rcutils_snprintf ( output_msg , sizeof ( output_msg ) , format_string , __VA_ARGS__ ) ; if ( ret < 0 ) { RCUTILS_SAFE_FWRITE_TO_STDERR ( "Failed to call snprintf for error message formatting\n" ) ; } else { RCUTILS_SET_ERROR_MSG ( output_msg ) ; } } while ( 0 )

# This is a big structure, so ensure it gets heap allocated
# Also, it helps to have a stable address for the `str` field
mutable struct rcutils_error_string_t
    str::NTuple{RCUTILS_ERROR_MESSAGE_MAX_LENGTH, Cchar}
end

# This is a big structure, so ensure it gets heap allocated
# Also, it helps to have a stable address for the `message` and `file` fields.
mutable struct rcutils_error_state_t
    message::NTuple{RCUTILS_ERROR_STATE_MESSAGE_MAX_LENGTH, Cchar}
    file::NTuple{RCUTILS_ERROR_STATE_FILE_MAX_LENGTH, Cchar}
    line_number::UInt64
end

# Skipping MacroDefinition: rcutils_format_string ( allocator , format_string , ... ) rcutils_format_string_limit ( allocator , 2048 , format_string , __VA_ARGS__ )

const RCUTILS_LOGGING_SEPARATOR_CHAR = '.'
const RCUTILS_LOGGING_SEPARATOR_STRING = "."

@cenum(RCUTILS_LOG_SEVERITY,
    RCUTILS_LOG_SEVERITY_UNSET = 0,
    RCUTILS_LOG_SEVERITY_DEBUG = 10,
    RCUTILS_LOG_SEVERITY_INFO = 20,
    RCUTILS_LOG_SEVERITY_WARN = 30,
    RCUTILS_LOG_SEVERITY_ERROR = 40,
    RCUTILS_LOG_SEVERITY_FATAL = 50,
)

const RCUTILS_DEFAULT_LOGGER_DEFAULT_LEVEL = RCUTILS_LOG_SEVERITY_INFO

# Skipping MacroDefinition: RCUTILS_LIKELY ( x ) __builtin_expect ( ( x ) , 1 )
# Skipping MacroDefinition: RCUTILS_UNLIKELY ( x ) __builtin_expect ( ( x ) , 0 )
# Skipping MacroDefinition: RCUTILS_LOGGING_AUTOINIT if ( RCUTILS_UNLIKELY ( ! g_rcutils_logging_initialized ) ) { rcutils_ret_t ret = rcutils_logging_initialize ( ) ; if ( ret != RCUTILS_RET_OK ) { RCUTILS_SAFE_FWRITE_TO_STDERR ( "[rcutils|" __FILE__ ":" RCUTILS_STRINGIFY ( __LINE__ ) "] error initializing logging: " ) ; RCUTILS_SAFE_FWRITE_TO_STDERR ( rcutils_get_error_string ( ) . str ) ; RCUTILS_SAFE_FWRITE_TO_STDERR ( "\n" ) ; rcutils_reset_error ( ) ; } }

struct rcutils_log_location_t
    function_name::Cstring
    file_name::Cstring
    line_number::Csize_t
end

const rcutils_logging_output_handler_t = Ptr{Cvoid}
const RCUTILS_LOG_MIN_SEVERITY_DEBUG = 0
const RCUTILS_LOG_MIN_SEVERITY_INFO = 1
const RCUTILS_LOG_MIN_SEVERITY_WARN = 2
const RCUTILS_LOG_MIN_SEVERITY_ERROR = 3
const RCUTILS_LOG_MIN_SEVERITY_FATAL = 4
const RCUTILS_LOG_MIN_SEVERITY_NONE = 5
const RCUTILS_LOG_MIN_SEVERITY = RCUTILS_LOG_MIN_SEVERITY_DEBUG

# Skipping MacroDefinition: RCUTILS_LOG_COND_NAMED ( severity , condition_before , condition_after , name , ... ) do { RCUTILS_LOGGING_AUTOINIT static rcutils_log_location_t __rcutils_logging_location = { __func__ , __FILE__ , __LINE__ } ; if ( rcutils_logging_logger_is_enabled_for ( name , severity ) ) { condition_before rcutils_log ( & __rcutils_logging_location , severity , name , __VA_ARGS__ ) ; condition_after } } while ( 0 )
# Skipping MacroDefinition: RCUTILS_LOG_CONDITION_ONCE_BEFORE { static int __rcutils_logging_once = 0 ; if ( RCUTILS_UNLIKELY ( 0 == __rcutils_logging_once ) ) { __rcutils_logging_once = 1 ;
# Skipping MacroDefinition: RCUTILS_LOG_CONDITION_ONCE_AFTER } }
# Skipping MacroDefinition: RCUTILS_LOG_CONDITION_EXPRESSION_BEFORE ( expression ) if ( expression ) {
# Skipping MacroDefinition: RCUTILS_LOG_CONDITION_FUNCTION_BEFORE ( function ) if ( ( * function ) ( ) ) {
# Skipping MacroDefinition: RCUTILS_LOG_CONDITION_SKIPFIRST_BEFORE { static bool __rcutils_logging_first = true ; if ( RCUTILS_UNLIKELY ( true == __rcutils_logging_first ) ) { __rcutils_logging_first = false ; } else {
# Skipping MacroDefinition: RCUTILS_LOG_CONDITION_SKIPFIRST_AFTER } }
# Skipping MacroDefinition: RCUTILS_LOG_CONDITION_THROTTLE_BEFORE ( time_source_type , duration ) { static rcutils_duration_value_t __rcutils_logging_duration = RCUTILS_MS_TO_NS ( ( rcutils_duration_value_t ) duration ) ; static rcutils_time_point_value_t __rcutils_logging_last_logged = 0 ; rcutils_time_point_value_t __rcutils_logging_now = 0 ; bool __rcutils_logging_condition = true ; if ( rcutils_steady_time_now ( & __rcutils_logging_now ) != RCUTILS_RET_OK ) { rcutils_log ( & __rcutils_logging_location , RCUTILS_LOG_SEVERITY_ERROR , "" , "%s() at %s:%d getting current steady time failed\n" , __func__ , __FILE__ , __LINE__ ) ; } else { __rcutils_logging_condition = __rcutils_logging_now >= __rcutils_logging_last_logged + __rcutils_logging_duration ; } if ( RCUTILS_LIKELY ( __rcutils_logging_condition ) ) { __rcutils_logging_last_logged = __rcutils_logging_now ;
# Skipping MacroDefinition: RCUTILS_LOG_CONDITION_THROTTLE_AFTER } }
# Skipping MacroDefinition: RCUTILS_LOG_DEBUG ( ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_DEBUG , RCUTILS_LOG_CONDITION_EMPTY , RCUTILS_LOG_CONDITION_EMPTY , NULL , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_DEBUG_NAMED ( name , ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_DEBUG , RCUTILS_LOG_CONDITION_EMPTY , RCUTILS_LOG_CONDITION_EMPTY , name , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_DEBUG_ONCE ( ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_DEBUG , RCUTILS_LOG_CONDITION_ONCE_BEFORE , RCUTILS_LOG_CONDITION_ONCE_AFTER , NULL , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_DEBUG_ONCE_NAMED ( name , ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_DEBUG , RCUTILS_LOG_CONDITION_ONCE_BEFORE , RCUTILS_LOG_CONDITION_ONCE_AFTER , name , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_DEBUG_EXPRESSION ( expression , ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_DEBUG , RCUTILS_LOG_CONDITION_EXPRESSION_BEFORE ( expression ) , RCUTILS_LOG_CONDITION_EXPRESSION_AFTER , NULL , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_DEBUG_EXPRESSION_NAMED ( expression , name , ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_DEBUG , RCUTILS_LOG_CONDITION_EXPRESSION_BEFORE ( expression ) , RCUTILS_LOG_CONDITION_EXPRESSION_AFTER , name , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_DEBUG_FUNCTION ( function , ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_DEBUG , RCUTILS_LOG_CONDITION_FUNCTION_BEFORE ( function ) , RCUTILS_LOG_CONDITION_FUNCTION_AFTER , NULL , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_DEBUG_FUNCTION_NAMED ( function , name , ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_DEBUG , RCUTILS_LOG_CONDITION_FUNCTION_BEFORE ( function ) , RCUTILS_LOG_CONDITION_FUNCTION_AFTER , name , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_DEBUG_SKIPFIRST ( ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_DEBUG , RCUTILS_LOG_CONDITION_SKIPFIRST_BEFORE , RCUTILS_LOG_CONDITION_SKIPFIRST_AFTER , NULL , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_DEBUG_SKIPFIRST_NAMED ( name , ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_DEBUG , RCUTILS_LOG_CONDITION_SKIPFIRST_BEFORE , RCUTILS_LOG_CONDITION_SKIPFIRST_AFTER , name , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_DEBUG_THROTTLE ( time_source_type , duration , ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_DEBUG , RCUTILS_LOG_CONDITION_THROTTLE_BEFORE ( time_source_type , duration ) , RCUTILS_LOG_CONDITION_THROTTLE_AFTER , NULL , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_DEBUG_SKIPFIRST_THROTTLE ( time_source_type , duration , ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_DEBUG , RCUTILS_LOG_CONDITION_THROTTLE_BEFORE ( time_source_type , duration ) RCUTILS_LOG_CONDITION_SKIPFIRST_BEFORE , RCUTILS_LOG_CONDITION_THROTTLE_AFTER RCUTILS_LOG_CONDITION_SKIPFIRST_AFTER , NULL , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_DEBUG_THROTTLE_NAMED ( time_source_type , duration , name , ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_DEBUG , RCUTILS_LOG_CONDITION_THROTTLE_BEFORE ( time_source_type , duration ) , RCUTILS_LOG_CONDITION_THROTTLE_AFTER , name , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_DEBUG_SKIPFIRST_THROTTLE_NAMED ( time_source_type , duration , name , ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_DEBUG , RCUTILS_LOG_CONDITION_THROTTLE_BEFORE ( time_source_type , duration ) RCUTILS_LOG_CONDITION_SKIPFIRST_BEFORE , RCUTILS_LOG_CONDITION_THROTTLE_AFTER RCUTILS_LOG_CONDITION_SKIPFIRST_AFTER , name , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_INFO ( ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_INFO , RCUTILS_LOG_CONDITION_EMPTY , RCUTILS_LOG_CONDITION_EMPTY , NULL , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_INFO_NAMED ( name , ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_INFO , RCUTILS_LOG_CONDITION_EMPTY , RCUTILS_LOG_CONDITION_EMPTY , name , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_INFO_ONCE ( ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_INFO , RCUTILS_LOG_CONDITION_ONCE_BEFORE , RCUTILS_LOG_CONDITION_ONCE_AFTER , NULL , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_INFO_ONCE_NAMED ( name , ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_INFO , RCUTILS_LOG_CONDITION_ONCE_BEFORE , RCUTILS_LOG_CONDITION_ONCE_AFTER , name , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_INFO_EXPRESSION ( expression , ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_INFO , RCUTILS_LOG_CONDITION_EXPRESSION_BEFORE ( expression ) , RCUTILS_LOG_CONDITION_EXPRESSION_AFTER , NULL , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_INFO_EXPRESSION_NAMED ( expression , name , ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_INFO , RCUTILS_LOG_CONDITION_EXPRESSION_BEFORE ( expression ) , RCUTILS_LOG_CONDITION_EXPRESSION_AFTER , name , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_INFO_FUNCTION ( function , ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_INFO , RCUTILS_LOG_CONDITION_FUNCTION_BEFORE ( function ) , RCUTILS_LOG_CONDITION_FUNCTION_AFTER , NULL , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_INFO_FUNCTION_NAMED ( function , name , ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_INFO , RCUTILS_LOG_CONDITION_FUNCTION_BEFORE ( function ) , RCUTILS_LOG_CONDITION_FUNCTION_AFTER , name , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_INFO_SKIPFIRST ( ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_INFO , RCUTILS_LOG_CONDITION_SKIPFIRST_BEFORE , RCUTILS_LOG_CONDITION_SKIPFIRST_AFTER , NULL , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_INFO_SKIPFIRST_NAMED ( name , ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_INFO , RCUTILS_LOG_CONDITION_SKIPFIRST_BEFORE , RCUTILS_LOG_CONDITION_SKIPFIRST_AFTER , name , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_INFO_THROTTLE ( time_source_type , duration , ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_INFO , RCUTILS_LOG_CONDITION_THROTTLE_BEFORE ( time_source_type , duration ) , RCUTILS_LOG_CONDITION_THROTTLE_AFTER , NULL , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_INFO_SKIPFIRST_THROTTLE ( time_source_type , duration , ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_INFO , RCUTILS_LOG_CONDITION_THROTTLE_BEFORE ( time_source_type , duration ) RCUTILS_LOG_CONDITION_SKIPFIRST_BEFORE , RCUTILS_LOG_CONDITION_THROTTLE_AFTER RCUTILS_LOG_CONDITION_SKIPFIRST_AFTER , NULL , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_INFO_THROTTLE_NAMED ( time_source_type , duration , name , ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_INFO , RCUTILS_LOG_CONDITION_THROTTLE_BEFORE ( time_source_type , duration ) , RCUTILS_LOG_CONDITION_THROTTLE_AFTER , name , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_INFO_SKIPFIRST_THROTTLE_NAMED ( time_source_type , duration , name , ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_INFO , RCUTILS_LOG_CONDITION_THROTTLE_BEFORE ( time_source_type , duration ) RCUTILS_LOG_CONDITION_SKIPFIRST_BEFORE , RCUTILS_LOG_CONDITION_THROTTLE_AFTER RCUTILS_LOG_CONDITION_SKIPFIRST_AFTER , name , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_WARN ( ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_WARN , RCUTILS_LOG_CONDITION_EMPTY , RCUTILS_LOG_CONDITION_EMPTY , NULL , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_WARN_NAMED ( name , ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_WARN , RCUTILS_LOG_CONDITION_EMPTY , RCUTILS_LOG_CONDITION_EMPTY , name , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_WARN_ONCE ( ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_WARN , RCUTILS_LOG_CONDITION_ONCE_BEFORE , RCUTILS_LOG_CONDITION_ONCE_AFTER , NULL , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_WARN_ONCE_NAMED ( name , ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_WARN , RCUTILS_LOG_CONDITION_ONCE_BEFORE , RCUTILS_LOG_CONDITION_ONCE_AFTER , name , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_WARN_EXPRESSION ( expression , ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_WARN , RCUTILS_LOG_CONDITION_EXPRESSION_BEFORE ( expression ) , RCUTILS_LOG_CONDITION_EXPRESSION_AFTER , NULL , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_WARN_EXPRESSION_NAMED ( expression , name , ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_WARN , RCUTILS_LOG_CONDITION_EXPRESSION_BEFORE ( expression ) , RCUTILS_LOG_CONDITION_EXPRESSION_AFTER , name , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_WARN_FUNCTION ( function , ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_WARN , RCUTILS_LOG_CONDITION_FUNCTION_BEFORE ( function ) , RCUTILS_LOG_CONDITION_FUNCTION_AFTER , NULL , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_WARN_FUNCTION_NAMED ( function , name , ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_WARN , RCUTILS_LOG_CONDITION_FUNCTION_BEFORE ( function ) , RCUTILS_LOG_CONDITION_FUNCTION_AFTER , name , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_WARN_SKIPFIRST ( ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_WARN , RCUTILS_LOG_CONDITION_SKIPFIRST_BEFORE , RCUTILS_LOG_CONDITION_SKIPFIRST_AFTER , NULL , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_WARN_SKIPFIRST_NAMED ( name , ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_WARN , RCUTILS_LOG_CONDITION_SKIPFIRST_BEFORE , RCUTILS_LOG_CONDITION_SKIPFIRST_AFTER , name , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_WARN_THROTTLE ( time_source_type , duration , ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_WARN , RCUTILS_LOG_CONDITION_THROTTLE_BEFORE ( time_source_type , duration ) , RCUTILS_LOG_CONDITION_THROTTLE_AFTER , NULL , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_WARN_SKIPFIRST_THROTTLE ( time_source_type , duration , ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_WARN , RCUTILS_LOG_CONDITION_THROTTLE_BEFORE ( time_source_type , duration ) RCUTILS_LOG_CONDITION_SKIPFIRST_BEFORE , RCUTILS_LOG_CONDITION_THROTTLE_AFTER RCUTILS_LOG_CONDITION_SKIPFIRST_AFTER , NULL , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_WARN_THROTTLE_NAMED ( time_source_type , duration , name , ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_WARN , RCUTILS_LOG_CONDITION_THROTTLE_BEFORE ( time_source_type , duration ) , RCUTILS_LOG_CONDITION_THROTTLE_AFTER , name , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_WARN_SKIPFIRST_THROTTLE_NAMED ( time_source_type , duration , name , ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_WARN , RCUTILS_LOG_CONDITION_THROTTLE_BEFORE ( time_source_type , duration ) RCUTILS_LOG_CONDITION_SKIPFIRST_BEFORE , RCUTILS_LOG_CONDITION_THROTTLE_AFTER RCUTILS_LOG_CONDITION_SKIPFIRST_AFTER , name , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_ERROR ( ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_ERROR , RCUTILS_LOG_CONDITION_EMPTY , RCUTILS_LOG_CONDITION_EMPTY , NULL , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_ERROR_NAMED ( name , ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_ERROR , RCUTILS_LOG_CONDITION_EMPTY , RCUTILS_LOG_CONDITION_EMPTY , name , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_ERROR_ONCE ( ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_ERROR , RCUTILS_LOG_CONDITION_ONCE_BEFORE , RCUTILS_LOG_CONDITION_ONCE_AFTER , NULL , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_ERROR_ONCE_NAMED ( name , ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_ERROR , RCUTILS_LOG_CONDITION_ONCE_BEFORE , RCUTILS_LOG_CONDITION_ONCE_AFTER , name , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_ERROR_EXPRESSION ( expression , ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_ERROR , RCUTILS_LOG_CONDITION_EXPRESSION_BEFORE ( expression ) , RCUTILS_LOG_CONDITION_EXPRESSION_AFTER , NULL , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_ERROR_EXPRESSION_NAMED ( expression , name , ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_ERROR , RCUTILS_LOG_CONDITION_EXPRESSION_BEFORE ( expression ) , RCUTILS_LOG_CONDITION_EXPRESSION_AFTER , name , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_ERROR_FUNCTION ( function , ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_ERROR , RCUTILS_LOG_CONDITION_FUNCTION_BEFORE ( function ) , RCUTILS_LOG_CONDITION_FUNCTION_AFTER , NULL , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_ERROR_FUNCTION_NAMED ( function , name , ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_ERROR , RCUTILS_LOG_CONDITION_FUNCTION_BEFORE ( function ) , RCUTILS_LOG_CONDITION_FUNCTION_AFTER , name , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_ERROR_SKIPFIRST ( ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_ERROR , RCUTILS_LOG_CONDITION_SKIPFIRST_BEFORE , RCUTILS_LOG_CONDITION_SKIPFIRST_AFTER , NULL , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_ERROR_SKIPFIRST_NAMED ( name , ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_ERROR , RCUTILS_LOG_CONDITION_SKIPFIRST_BEFORE , RCUTILS_LOG_CONDITION_SKIPFIRST_AFTER , name , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_ERROR_THROTTLE ( time_source_type , duration , ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_ERROR , RCUTILS_LOG_CONDITION_THROTTLE_BEFORE ( time_source_type , duration ) , RCUTILS_LOG_CONDITION_THROTTLE_AFTER , NULL , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_ERROR_SKIPFIRST_THROTTLE ( time_source_type , duration , ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_ERROR , RCUTILS_LOG_CONDITION_THROTTLE_BEFORE ( time_source_type , duration ) RCUTILS_LOG_CONDITION_SKIPFIRST_BEFORE , RCUTILS_LOG_CONDITION_THROTTLE_AFTER RCUTILS_LOG_CONDITION_SKIPFIRST_AFTER , NULL , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_ERROR_THROTTLE_NAMED ( time_source_type , duration , name , ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_ERROR , RCUTILS_LOG_CONDITION_THROTTLE_BEFORE ( time_source_type , duration ) , RCUTILS_LOG_CONDITION_THROTTLE_AFTER , name , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_ERROR_SKIPFIRST_THROTTLE_NAMED ( time_source_type , duration , name , ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_ERROR , RCUTILS_LOG_CONDITION_THROTTLE_BEFORE ( time_source_type , duration ) RCUTILS_LOG_CONDITION_SKIPFIRST_BEFORE , RCUTILS_LOG_CONDITION_THROTTLE_AFTER RCUTILS_LOG_CONDITION_SKIPFIRST_AFTER , name , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_FATAL ( ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_FATAL , RCUTILS_LOG_CONDITION_EMPTY , RCUTILS_LOG_CONDITION_EMPTY , NULL , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_FATAL_NAMED ( name , ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_FATAL , RCUTILS_LOG_CONDITION_EMPTY , RCUTILS_LOG_CONDITION_EMPTY , name , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_FATAL_ONCE ( ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_FATAL , RCUTILS_LOG_CONDITION_ONCE_BEFORE , RCUTILS_LOG_CONDITION_ONCE_AFTER , NULL , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_FATAL_ONCE_NAMED ( name , ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_FATAL , RCUTILS_LOG_CONDITION_ONCE_BEFORE , RCUTILS_LOG_CONDITION_ONCE_AFTER , name , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_FATAL_EXPRESSION ( expression , ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_FATAL , RCUTILS_LOG_CONDITION_EXPRESSION_BEFORE ( expression ) , RCUTILS_LOG_CONDITION_EXPRESSION_AFTER , NULL , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_FATAL_EXPRESSION_NAMED ( expression , name , ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_FATAL , RCUTILS_LOG_CONDITION_EXPRESSION_BEFORE ( expression ) , RCUTILS_LOG_CONDITION_EXPRESSION_AFTER , name , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_FATAL_FUNCTION ( function , ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_FATAL , RCUTILS_LOG_CONDITION_FUNCTION_BEFORE ( function ) , RCUTILS_LOG_CONDITION_FUNCTION_AFTER , NULL , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_FATAL_FUNCTION_NAMED ( function , name , ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_FATAL , RCUTILS_LOG_CONDITION_FUNCTION_BEFORE ( function ) , RCUTILS_LOG_CONDITION_FUNCTION_AFTER , name , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_FATAL_SKIPFIRST ( ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_FATAL , RCUTILS_LOG_CONDITION_SKIPFIRST_BEFORE , RCUTILS_LOG_CONDITION_SKIPFIRST_AFTER , NULL , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_FATAL_SKIPFIRST_NAMED ( name , ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_FATAL , RCUTILS_LOG_CONDITION_SKIPFIRST_BEFORE , RCUTILS_LOG_CONDITION_SKIPFIRST_AFTER , name , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_FATAL_THROTTLE ( time_source_type , duration , ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_FATAL , RCUTILS_LOG_CONDITION_THROTTLE_BEFORE ( time_source_type , duration ) , RCUTILS_LOG_CONDITION_THROTTLE_AFTER , NULL , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_FATAL_SKIPFIRST_THROTTLE ( time_source_type , duration , ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_FATAL , RCUTILS_LOG_CONDITION_THROTTLE_BEFORE ( time_source_type , duration ) RCUTILS_LOG_CONDITION_SKIPFIRST_BEFORE , RCUTILS_LOG_CONDITION_THROTTLE_AFTER RCUTILS_LOG_CONDITION_SKIPFIRST_AFTER , NULL , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_FATAL_THROTTLE_NAMED ( time_source_type , duration , name , ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_FATAL , RCUTILS_LOG_CONDITION_THROTTLE_BEFORE ( time_source_type , duration ) , RCUTILS_LOG_CONDITION_THROTTLE_AFTER , name , __VA_ARGS__ )
# Skipping MacroDefinition: RCUTILS_LOG_FATAL_SKIPFIRST_THROTTLE_NAMED ( time_source_type , duration , name , ... ) RCUTILS_LOG_COND_NAMED ( RCUTILS_LOG_SEVERITY_FATAL , RCUTILS_LOG_CONDITION_THROTTLE_BEFORE ( time_source_type , duration ) RCUTILS_LOG_CONDITION_SKIPFIRST_BEFORE , RCUTILS_LOG_CONDITION_THROTTLE_AFTER RCUTILS_LOG_CONDITION_SKIPFIRST_AFTER , name , __VA_ARGS__ )

const RclLogFilter = Ptr{Cvoid}

# Skipping MacroDefinition: RCUTILS_WARN_UNUSED __attribute__ ( ( warn_unused_result ) )
# Skipping MacroDefinition: RCUTILS_STRINGIFY_IMPL ( x ) # x
# Skipping MacroDefinition: RCUTILS_STRINGIFY ( x ) RCUTILS_STRINGIFY_IMPL ( x )
# Skipping MacroDefinition: RCUTILS_UNUSED ( x ) ( void ) ( x )
# Skipping MacroDefinition: my__has_feature ( ... ) __has_feature ( __VAR_ARGS__ )
# Skipping MacroDefinition: rcutils_atomic_load ( object , out ) ( out ) = atomic_load ( object )
# Skipping MacroDefinition: rcutils_atomic_compare_exchange_strong ( object , out , expected , desired ) ( out ) = atomic_compare_exchange_strong ( object , expected , desired )
# Skipping MacroDefinition: rcutils_atomic_exchange ( object , out , desired ) ( out ) = atomic_exchange ( object , desired )
# Skipping MacroDefinition: rcutils_atomic_store ( object , desired ) atomic_store ( object , desired )
# Skipping MacroDefinition: rcutils_atomic_fetch_add ( object , out , arg ) ( out ) = atomic_fetch_add ( object , arg )
RCUTILS_S_TO_NS(seconds) = 1_000_000_000seconds
RCUTILS_MS_TO_NS(milliseconds) = 1_000_000milliseconds
RCUTILS_US_TO_NS(microseconds) = 1000microseconds
RCUTILS_NS_TO_S(nanoseconds) = nanoseconds ÷ 1_000_000_000
RCUTILS_NS_TO_MS(nanoseconds) = nanoseconds ÷ 1_000_000
RCUTILS_NS_TO_US(nanoseconds) = nanoseconds ÷ 1_000

const rcutils_time_point_value_t = Int64
const rcutils_duration_value_t = Int64

# Skipping MacroDefinition: RCUTILS_EXPORT __attribute__ ( ( visibility ( "default" ) ) )
# Skipping MacroDefinition: RCUTILS_PUBLIC __attribute__ ( ( visibility ( "default" ) ) )
# Skipping MacroDefinition: RCUTILS_LOCAL __attribute__ ( ( visibility ( "hidden" ) ) )
# Skipping MacroDefinition: ATOMIC_VAR_INIT ( value ) ( value )
# Skipping MacroDefinition: atomic_init ( obj , value ) __c11_atomic_init ( obj , value )
# Skipping MacroDefinition: atomic_thread_fence ( order ) __c11_atomic_thread_fence ( order )
# Skipping MacroDefinition: atomic_signal_fence ( order ) __c11_atomic_signal_fence ( order )
# Skipping MacroDefinition: atomic_is_lock_free ( obj ) __c11_atomic_is_lock_free ( sizeof ( obj ) )
# Skipping MacroDefinition: atomic_compare_exchange_strong_explicit ( object , expected , desired , success , failure ) __c11_atomic_compare_exchange_strong ( object , expected , desired , success , failure )
# Skipping MacroDefinition: atomic_compare_exchange_weak_explicit ( object , expected , desired , success , failure ) __c11_atomic_compare_exchange_weak ( object , expected , desired , success , failure )
# Skipping MacroDefinition: atomic_exchange_explicit ( object , desired , order ) __c11_atomic_exchange ( object , desired , order )
# Skipping MacroDefinition: atomic_fetch_add_explicit ( object , operand , order ) __c11_atomic_fetch_add ( object , operand , order )
# Skipping MacroDefinition: atomic_fetch_and_explicit ( object , operand , order ) __c11_atomic_fetch_and ( object , operand , order )
# Skipping MacroDefinition: atomic_fetch_or_explicit ( object , operand , order ) __c11_atomic_fetch_or ( object , operand , order )
# Skipping MacroDefinition: atomic_fetch_sub_explicit ( object , operand , order ) __c11_atomic_fetch_sub ( object , operand , order )
# Skipping MacroDefinition: atomic_fetch_xor_explicit ( object , operand , order ) __c11_atomic_fetch_xor ( object , operand , order )
# Skipping MacroDefinition: atomic_load_explicit ( object , order ) __c11_atomic_load ( object , order )
# Skipping MacroDefinition: atomic_store_explicit ( object , desired , order ) __c11_atomic_store ( object , desired , order )
# Skipping MacroDefinition: atomic_compare_exchange_strong ( object , expected , desired ) atomic_compare_exchange_strong_explicit ( object , expected , desired , memory_order_seq_cst , memory_order_seq_cst )
# Skipping MacroDefinition: atomic_compare_exchange_weak ( object , expected , desired ) atomic_compare_exchange_weak_explicit ( object , expected , desired , memory_order_seq_cst , memory_order_seq_cst )
# Skipping MacroDefinition: atomic_exchange ( object , desired ) atomic_exchange_explicit ( object , desired , memory_order_seq_cst )
# Skipping MacroDefinition: atomic_fetch_add ( object , operand ) atomic_fetch_add_explicit ( object , operand , memory_order_seq_cst )
# Skipping MacroDefinition: atomic_fetch_and ( object , operand ) atomic_fetch_and_explicit ( object , operand , memory_order_seq_cst )
# Skipping MacroDefinition: atomic_fetch_or ( object , operand ) atomic_fetch_or_explicit ( object , operand , memory_order_seq_cst )
# Skipping MacroDefinition: atomic_fetch_sub ( object , operand ) atomic_fetch_sub_explicit ( object , operand , memory_order_seq_cst )
# Skipping MacroDefinition: atomic_fetch_xor ( object , operand ) atomic_fetch_xor_explicit ( object , operand , memory_order_seq_cst )
# Skipping MacroDefinition: atomic_load ( object ) atomic_load_explicit ( object , memory_order_seq_cst )
# Skipping MacroDefinition: atomic_store ( object , desired ) atomic_store_explicit ( object , desired , memory_order_seq_cst )
# Skipping MacroDefinition: ATOMIC_FLAG_INIT ATOMIC_VAR_INIT ( 0 )
# Skipping MacroDefinition: atomic_flag_clear_explicit ( object , order ) atomic_store_explicit ( object , 0 , order )
# Skipping MacroDefinition: atomic_flag_test_and_set_explicit ( object , order ) atomic_compare_exchange_strong_explicit ( object , 0 , 1 , order , order )
# Skipping MacroDefinition: atomic_flag_clear ( object ) atomic_flag_clear_explicit ( object , memory_order_seq_cst )
# Skipping MacroDefinition: atomic_flag_test_and_set ( object ) atomic_flag_test_and_set_explicit ( object , memory_order_seq_cst )

@cenum(memory_order,
    memory_order_relaxed = 0,
    memory_order_consume = 1,
    memory_order_acquire = 2,
    memory_order_release = 3,
    memory_order_acq_rel = 4,
    memory_order_seq_cst = 5,
)

const atomic_bool = Cvoid
const atomic_char = Cvoid
const atomic_schar = Cvoid
const atomic_uchar = Cvoid
const atomic_short = Cvoid
const atomic_ushort = Cvoid
const atomic_int = Cvoid
const atomic_uint = Cvoid
const atomic_long = Cvoid
const atomic_ulong = Cvoid
const atomic_llong = Cvoid
const atomic_ullong = Cvoid
const atomic_wchar_t = Cvoid
const atomic_int_least8_t = Cvoid
const atomic_uint_least8_t = Cvoid
const atomic_int_least16_t = Cvoid
const atomic_uint_least16_t = Cvoid
const atomic_int_least32_t = Cvoid
const atomic_uint_least32_t = Cvoid
const atomic_int_least64_t = Cvoid
const atomic_uint_least64_t = Cvoid
const atomic_int_fast8_t = Cvoid
const atomic_uint_fast8_t = Cvoid
const atomic_int_fast16_t = Cvoid
const atomic_uint_fast16_t = Cvoid
const atomic_int_fast32_t = Cvoid
const atomic_uint_fast32_t = Cvoid
const atomic_int_fast64_t = Cvoid
const atomic_uint_fast64_t = Cvoid
const atomic_intptr_t = Cvoid
const atomic_uintptr_t = Cvoid
const atomic_size_t = Cvoid
const atomic_ptrdiff_t = Cvoid
const atomic_intmax_t = Cvoid
const atomic_uintmax_t = Cvoid
const atomic_flag = atomic_bool

# Skipping MacroDefinition: ATOMIC_VAR_INIT ( value ) { . __val = ( value ) }
# Skipping MacroDefinition: atomic_init ( obj , value ) do { ( obj ) -> __val = ( value ) ; \
#} while ( 0 )
# Skipping MacroDefinition: atomic_thread_fence ( order ) MemoryBarrier ( )
# Skipping MacroDefinition: atomic_signal_fence ( order ) _ReadWriteBarrier ( )
# Skipping MacroDefinition: atomic_is_lock_free ( obj ) ( sizeof ( ( obj ) -> __val ) <= sizeof ( void * ) )
# Skipping MacroDefinition: rcutils_win32_atomic_compare_exchange_strong ( object , out , expected , desired ) __pragma ( warning ( push ) ) __pragma ( warning ( disable : 4244 ) ) do { switch ( sizeof ( out ) ) { case sizeof ( uint64_t ) : out = _InterlockedCompareExchange64 ( ( LONGLONG * ) object , desired , * expected ) ; break ; case sizeof ( uint32_t ) : out = _InterlockedCompareExchange ( ( LONG * ) object , desired , * expected ) ; break ; case sizeof ( uint16_t ) : out = _InterlockedCompareExchange16 ( ( SHORT * ) object , desired , * expected ) ; break ; case sizeof ( uint8_t ) : out = _InterlockedCompareExchange8 ( ( char * ) object , desired , * expected ) ; break ; default : RCUTILS_LOG_ERROR_NAMED ( ROS_PACKAGE_NAME , "Unsupported integer type in atomic_compare_exchange_strong" ) ; exit ( - 1 ) ; break ; } } while ( 0 ) ; __pragma ( warning ( pop ) )
# Skipping MacroDefinition: rcutils_win32_atomic_compare_exchange_weak ( object , out , expected , desired ) rcutils_win32_atomic_compare_exchange_strong ( object , out , expected , desired )
# Skipping MacroDefinition: rcutils_win32_atomic_exchange ( object , out , desired ) __pragma ( warning ( push ) ) __pragma ( warning ( disable : 4244 ) ) do { switch ( sizeof ( out ) ) { case sizeof ( uint64_t ) : out = _InterlockedExchange64 ( ( LONGLONG * ) object , desired ) ; break ; case sizeof ( uint32_t ) : out = _InterlockedExchange ( ( LONG * ) object , desired ) ; break ; case sizeof ( uint16_t ) : out = _InterlockedExchange16 ( ( SHORT * ) object , desired ) ; break ; case sizeof ( uint8_t ) : out = _InterlockedExchange8 ( ( char * ) object , desired ) ; break ; default : RCUTILS_LOG_ERROR_NAMED ( ROS_PACKAGE_NAME , "Unsupported integer type in atomic_exchange_strong" ) ; exit ( - 1 ) ; break ; } } while ( 0 ) ; __pragma ( warning ( pop ) )
# Skipping MacroDefinition: rcutils_win32_atomic_fetch_add ( object , out , operand ) __pragma ( warning ( push ) ) __pragma ( warning ( disable : 4244 ) ) do { switch ( sizeof ( out ) ) { case sizeof ( uint64_t ) : out = _InterlockedExchangeAdd64 ( ( LONGLONG * ) object , operand ) ; break ; case sizeof ( uint32_t ) : out = _InterlockedExchangeAdd ( ( LONG * ) object , operand ) ; break ; case sizeof ( uint16_t ) : out = _InterlockedExchangeAdd16 ( ( SHORT * ) object , operand ) ; break ; case sizeof ( uint8_t ) : out = _InterlockedExchangeAdd8 ( ( char * ) object , operand ) ; break ; default : RCUTILS_LOG_ERROR_NAMED ( ROS_PACKAGE_NAME , "Unsupported integer type in atomic_fetch_add" ) ; exit ( - 1 ) ; break ; } } while ( 0 ) ; __pragma ( warning ( pop ) )
# Skipping MacroDefinition: rcutils_win32_atomic_fetch_and ( object , out , operand ) __pragma ( warning ( push ) ) __pragma ( warning ( disable : 4244 ) ) do { switch ( sizeof ( out ) ) { case sizeof ( uint64_t ) : out = _InterlockedAnd64 ( ( LONGLONG * ) object , operand ) ; break ; case sizeof ( uint32_t ) : out = _InterlockedAnd ( ( LONG * ) object , operand ) ; break ; case sizeof ( uint16_t ) : out = _InterlockedAnd16 ( ( SHORT * ) object , operand ) ; break ; case sizeof ( uint8_t ) : out = _InterlockedAnd8 ( ( char * ) object , operand ) ; break ; default : RCUTILS_LOG_ERROR_NAMED ( ROS_PACKAGE_NAME , "Unsupported integer type in atomic_fetch_and" ) ; exit ( - 1 ) ; break ; } } while ( 0 ) ; __pragma ( warning ( pop ) )
# Skipping MacroDefinition: rcutils_win32_atomic_fetch_or ( object , out , operand ) __pragma ( warning ( push ) ) __pragma ( warning ( disable : 4244 ) ) do { switch ( sizeof ( out ) ) { case sizeof ( uint64_t ) : out = _InterlockedOr64 ( ( LONGLONG * ) object , operand ) ; break ; case sizeof ( uint32_t ) : out = _InterlockedOr ( ( LONG * ) object , operand ) ; break ; case sizeof ( uint16_t ) : out = _InterlockedOr16 ( ( SHORT * ) object , operand ) ; break ; case sizeof ( uint8_t ) : out = _InterlockedOr8 ( ( char * ) object , operand ) ; break ; default : RCUTILS_LOG_ERROR_NAMED ( ROS_PACKAGE_NAME , "Unsupported integer type in atomic_fetch_or" ) ; exit ( - 1 ) ; break ; } } while ( 0 ) ; __pragma ( warning ( pop ) )
# Skipping MacroDefinition: rcutils_win32_atomic_fetch_sub ( object , out , operand ) rcutils_win32_atomic_fetch_add ( object , out , - ( operand ) )
# Skipping MacroDefinition: rcutils_win32_atomic_fetch_xor ( object , out , operand ) __pragma ( warning ( push ) ) __pragma ( warning ( disable : 4244 ) ) do { switch ( sizeof ( out ) ) { case sizeof ( uint64_t ) : out = _InterlockedXor64 ( ( LONGLONG * ) object , operand ) ; break ; case sizeof ( uint32_t ) : out = _InterlockedXor ( ( LONG * ) object , operand ) ; break ; case sizeof ( uint16_t ) : out = _InterlockedXor16 ( ( SHORT * ) object , operand ) ; break ; case sizeof ( uint8_t ) : out = _InterlockedXor8 ( ( char * ) object , operand ) ; break ; default : RCUTILS_LOG_ERROR_NAMED ( ROS_PACKAGE_NAME , "Unsupported integer type in atomic_fetch_xor" ) ; exit ( - 1 ) ; break ; } } while ( 0 ) ; __pragma ( warning ( pop ) )
# Skipping MacroDefinition: rcutils_win32_atomic_load ( object , out ) __pragma ( warning ( push ) ) __pragma ( warning ( disable : 4244 ) ) do { switch ( sizeof ( out ) ) { case sizeof ( uint64_t ) : out = _InterlockedExchangeAdd64 ( ( LONGLONG * ) object , 0 ) ; break ; case sizeof ( uint32_t ) : out = _InterlockedExchangeAdd ( ( LONG * ) object , 0 ) ; break ; case sizeof ( uint16_t ) : out = _InterlockedExchangeAdd16 ( ( SHORT * ) object , 0 ) ; break ; case sizeof ( uint8_t ) : out = _InterlockedExchangeAdd8 ( ( char * ) object , 0 ) ; break ; default : RCUTILS_LOG_ERROR_NAMED ( ROS_PACKAGE_NAME , "Unsupported integer type in atomic_load" ) ; exit ( - 1 ) ; break ; } } while ( 0 ) ; __pragma ( warning ( pop ) )
# Skipping MacroDefinition: rcutils_win32_atomic_store ( object , desired ) do { MemoryBarrier ( ) ; ( object ) -> __val = ( desired ) ; MemoryBarrier ( ) ; } while ( 0 )
# Skipping MacroDefinition: ARRAY_LIST_VALIDATE_ARRAY_LIST ( array_list ) RCUTILS_CHECK_ARGUMENT_FOR_NULL ( array_list , RCUTILS_RET_INVALID_ARGUMENT ) ; if ( NULL == array_list -> impl ) { RCUTILS_SET_ERROR_MSG ( "array_list is not initialized" ) ; return RCUTILS_RET_NOT_INITIALIZED ; }

const rcutils_array_list_impl_t = Cvoid

struct rcutils_array_list_t
    impl::Ptr{rcutils_array_list_impl_t}
end

struct rcutils_char_array_t
    buffer::Cstring
    owns_buffer::Bool
    buffer_length::Csize_t
    buffer_capacity::Csize_t
    allocator::rcutils_allocator_t
end

# Skipping MacroDefinition: HASH_MAP_VALIDATE_HASH_MAP ( map ) RCUTILS_CHECK_ARGUMENT_FOR_NULL ( map , RCUTILS_RET_INVALID_ARGUMENT ) ; if ( NULL == map -> impl ) { RCUTILS_SET_ERROR_MSG ( "map is not initialized" ) ; return RCUTILS_RET_NOT_INITIALIZED ; }

const rcutils_hash_map_impl_t = Cvoid

struct rcutils_hash_map_t
    impl::Ptr{rcutils_hash_map_impl_t}
end

const rcutils_hash_map_key_hasher_t = Ptr{Cvoid}
const rcutils_hash_map_key_cmp_t = Ptr{Cvoid}
const RCUTILS_RET_OK = 0
const RCUTILS_RET_WARN = 1
const RCUTILS_RET_ERROR = 2
const RCUTILS_RET_BAD_ALLOC = 10
const RCUTILS_RET_INVALID_ARGUMENT = 11
const RCUTILS_RET_NOT_ENOUGH_SPACE = 12
const RCUTILS_RET_NOT_INITIALIZED = 13
const RCUTILS_RET_NOT_FOUND = 14
const RCUTILS_RET_STRING_MAP_ALREADY_INIT = 30
const RCUTILS_RET_STRING_MAP_INVALID = 31
const RCUTILS_RET_STRING_KEY_NOT_FOUND = 32
const RCUTILS_RET_LOGGING_SEVERITY_MAP_INVALID = 40
const RCUTILS_RET_LOGGING_SEVERITY_STRING_INVALID = 41
const RCUTILS_RET_HASH_MAP_NO_MORE_ENTRIES = 50
const rcutils_ret_t = Cint

struct rcutils_string_array_t
    size::Csize_t
    data::Ptr{Cstring}
    allocator::rcutils_allocator_t
end

const rcutils_string_map_impl_t = Cvoid

struct rcutils_string_map_t
    impl::Ptr{rcutils_string_map_impl_t}
end

struct rcutils_uint8_array_t
    buffer::Ptr{UInt8}
    buffer_length::Csize_t
    buffer_capacity::Csize_t
    allocator::rcutils_allocator_t
end


text:
#=
Challenge #259 [Easy] Clarence the Slow Typist

Description

Clarence is a data entry clerk who works at an internet service provider. His
job is to manually enter the IP addresses of all of the ISP's customers into the
database. He does this using a keypad which has the following layout:

1	2	3
4	5	6
7	8	9
.	0

The distance between the centre of horizontally or vertically adjacent keys is
exactly one centimetre. For instance, the distance between the centres of 3 and
9 would be two centimetres. The distance between the centres of 3 and 5 would be
sqrt 2cm. The Pythagoras theorem is sufficient to calculate the distance between
any two keys.
Clarence, as you might expect from one who works in an ISP, uses a very slow and
inefficient system of typing. He uses a single finger and searches for the key,
and then moves his finger to the key, then presses it, and repeats for all of the
digits in the number. You might know of this style as the "eagle search system"
since the finger searches above the keyboard for the correct key before plunging
down for the keypress, like an eagle plunging down for a kill.
For example, here is how Clarence would type out the number 7851:
    * He starts his finger at 7 and pushes the key.
    * He moves his finger to the right 1cm to 8 and pushes the key.
    * He moves his finger upwards 1cm to 5 and pushes the key.
    * He moves his finger diagonally upwards and left sqrt 2cm to 1 and pushes
      the key.
Therefore the total distance that Clarence moved his finger to type in 7851 is 1
+ 1 + sqrt 2 which is about 3.41cm.
Your task is to write a program that calculates the distance Clarence must move
his finger to type in arbitrary IP addresses.

Formal Inputs and Outputs

Input Description

Input is a string that will be in the form
().().().()
where each () is an integer in the range 0 - 999. This represents the IP address
that Clarence must type in. An example input might be:
219.45.143.143
I would also like to point out that inputs such as 0.42.42.42 or 999.999.999.999
are still valid inputs, despite the fact that they are invalid IP addresses.
So you don't need to include any IP address verification code in your program.

Output Description

Output the distance that Clarence must move his finger in order to type in the
specified IP address. Round answers to two decimal places where needed, and use
the cm unit in your output. The output for the example input is 27.38cm (1 + sqrt
8 + sqrt 5 + 2 + 1 + sqrt 5 + 3 + 1 + sqrt 5 + sqrt 13 + 3 + 1 + sqrt 5).

Credit

This challenge was suggested by /u/katyai. If you have any challenge ideas please
share them on /r/dailyprogrammer_ideas and there's a good chance we'll use them!

( source: https://redd.it/4bc3el )

The version of the user Gobbedyret was so simple -- and good -- that inspired me
=#

function keyboard_distance( key_1::Char, key_2::Char )
    sequence::AbstractString = "123456789.0"

    first::Tuple = divrem( search( sequence, key_1 ) - 1, 3 )
    second::Tuple = divrem( search( sequence, key_2 ) - 1, 3 )

    dx::Integer = second[ 2 ] - first[ 2 ]
    dy::Integer = second[ 1 ] - first[ 1 ]

    return ( dx^2 + dy^2 )^0.5
end

function main( )
    input::AbstractString = chomp( readline( STDIN ) )
    @printf( "%.2fcm\n", sum( [ keyboard_distance( i, j ) for ( i, j ) in zip( input[1:end-1], input[2:end] ) ] ) )
end

main( )

max_stars_repo_name: farmfirst/dailyprogrammer

max_issues_repo_name: farmfirst/dailyprogrammer

max_forks_repo_name: farmfirst/dailyprogrammer


text:
@testset "Util" begin

    # Test `get_window_bounds()`.
    let A = Gray.(zeros(5,5))
        for index in CartesianIndices(A)
            bounds = ImageBinarization.get_window_bounds(A, index, 1)
            for bound = bounds
                @test 1 <= bound <= 5
            end
        end
    end

    # Test `μ_in_window()`.
    let A = [(x-1) * 5 + y for x = 1:5, y = 1:5]
        I = ImageBinarization.integral_image(A)
        for r₀ in 1:5, c₀ in 1:5
            for r₁ in r₀:5, c₁ in c₀:5
                @test ImageBinarization.μ_in_window(I, r₀, c₀, r₁, c₁) == mean(vec(A[r₀:r₁,c₀:c₁]))
            end
        end
    end

    # Test `σ²_in_window()`.
    let A = [(x-1) * 5 + y for x = 1:5, y = 1:5]
        I² = ImageBinarization.integral_image(A.^2)
        for r₀ in 1:5, c₀ in 1:5
            for r₁ in r₀:5, c₁ in c₀:5
                μ = mean(vec(A[r₀:r₁,c₀:c₁]))
                δ = ImageBinarization.σ²_in_window(I², μ, r₀, c₀, r₁, c₁) - var(vec(A[r₀:r₁,c₀:c₁]), corrected=false)
                @test δ == NaN || δ < 1e-10
            end
        end
    end

    # Test `σ_in_window()`.
    let A = [(x-1) * 5 + y for x = 1:5, y = 1:5]
        I² = ImageBinarization.integral_image(A.^2)
        for r₀ in 1:5, c₀ in 1:5
            for r₁ in r₀:5, c₁ in c₀:5
                μ = mean(vec(A[r₀:r₁,c₀:c₁]))
                δ = ImageBinarization.σ_in_window(I², μ, r₀, c₀, r₁, c₁) - std(vec(A[r₀:r₁,c₀:c₁]), corrected=false)
                @test δ == NaN || δ < 1e-10
            end
        end
    end
end


text:
using Lumira
using Gadfly

plot = plot([x -> 2*sqrt(x),x -> -2*sqrt(x)],0,25)

exportToSVG(plot)

setId("comsapsbcd90helloworld")
setName("HelloWorld")
createLumiraExtension()