text:
# include("Configuration.jl")
# include("delegate.jl")
import Base: getindex, findfirst, length, size, start, done, next, isempty

abstract ParticleMove

immutable LatticeParticleMove <: ParticleMove
    particle::Particle
    destination::Int
end

# see Base.Cartesian for better multidimensional capabilities..
immutable Continuum1DParticleMove <: ParticleMove
    particle::Particle
    destination::Float64
end

# immutable Continuum2DParticleMove <: ParticleMove
#     particle::Particle
#     @compat destination::Tuple{Float64, Float64}
# end

abstract SystemMove

immutable ParticlesMove{T<:ParticleMove} <: SystemMove
    nontrivial_move::Bool
    move_vec::Vector{T}
    ParticlesMove(move_vec::Vector{T}) = new(true, move_vec)
    ParticlesMove() = new(false) # need to specify T via ParticlesMove{T}() when called
end

# which form is most appropriate?  (issue shows up in other places too)
ParticlesMove{T<:ParticleMove}(move_vec::Vector{T}) = ParticlesMove{eltype(move_vec)}(move_vec)
# ParticlesMove(move_vec) = ParticlesMove{eltype(move_vec)}(move_vec)
# ParticlesMove(move_vec::Vector) = ParticlesMove{eltype(move_vec)}(move_vec)
# ParticlesMove(move_vec::Vector{ParticleMove}) = ParticlesMove{eltype(move_vec)}(move_vec)

is_nontrivial(move::SystemMove) = move.nontrivial_move

# to make ParticlesMove objects effectively behave like Vector{T<:ParticleMove} objects
# (without explictly accessing the move_vec field)
@delegate ParticlesMove.move_vec [ getindex, length, size, start, done, next, isempty ]
export getindex, length, size, start, done, next, isempty

function update_configuration!(config::LatticeParticlesConfiguration, move::ParticlesMove{LatticeParticleMove})
    # if the move is trivial (not actually a change to the configuration space) then we don't do anything to config
    if is_nontrivial(move)
        for sp_move in move
            config.particle_positions[sp_move.particle.species][sp_move.particle.index] = sp_move.destination
        end
        config.lattice_status = LatticeParticlesConfiguration(config.particle_positions, get_Nsites(config)).lattice_status
    end
    return config
end

function update_configuration(config::LatticeParticlesConfiguration, move::ParticlesMove{LatticeParticleMove})
    new_config = deepcopy(config)
    if is_nontrivial(move)
        for sp_move in move
            new_config.particle_positions[sp_move.particle.species][sp_move.particle.index] = sp_move.destination
        end
        new_config.lattice_status = LatticeParticlesConfiguration(new_config.particle_positions, get_Nsites(new_config)).lattice_status
    end
    return new_config
end


text:
"""

    logp(x; dims=:)

Treat entries in `x` as as unnormalized log probabilities and return
normalized log probabilities.

`dims` is an optional argument, if not specified the normalization is
over the whole `x`, otherwise the normalization is performed over the
given dimensions.  In particular, if `x` is a matrix, `dims=1`
normalizes columns of `x` and `dims=2` normalizes rows of `x`.

"""
logp(x; dims=:) = generic_softmax(x,2,_logp; dims=dims)

# Math for the cross-entropy loss: x is unnormalized input, p is
# target probabilities, q is estimated probabilities. Read left column
# down, right column (loss gradients) back up.

# x			dx = -p + qz/z = -p + exp(logq)
# xmax  = max(x,1)	-sum(db)=0
# logqz = x .- xmax	-p + qz/z
# qz    = exp(logqz)	rep(1/z)
# z     = sum(qz,1)	1/z
# logz  = log(z)	sum(p)=1
# logq  = logqz.-logz	-p
# plogq = p .* logq	-1
# loss  = -sum(plogq)	1

# We keep the old implementation _logp for CPU arrays, slow cases and
# cases of d not handled by cudnn.
function _logp(x;dims=:,algo=2)
    xval = value(x)
    if isa(xval,Number)
        return zero(xval)
    elseif isempty(xval)
        return xval
    else
        x = x .- maximum(x,dims=dims)
        return (x .- log.(sum(exp.(x),dims=dims)))
        # Expanding for profiling:
        # x1 = maximum(x,d...)
        # x2 = x .- x1
        # x3 = exp.(x2)
        # x4 = sum(x3,d...)
        # x5 = log.(x4)
        # x6 = x2 .- x5
        # return x6
    end
end

function _logpback(x,y,dy;dims)
    xval = value(x)
    if isa(xval,Number)
        return zero(xval)
    elseif isempty(xval)
        return xval
    else
        return (dy - exp.(y).*sum(dy;dims=dims))
        # Expanding for profiling:
        # dx1 = sum(dy,d...)
        # dx2 = exp.(y)
        # dx3 = dx2 .* dx1
        # dx4 = dy - dx3
        # return dx4
    end
end

# dy should be -p and y=logq so this should give us -p+q
@primitive  _logp(x;dims=:,algo=2),dy,y  _logpback(x,y,dy,dims=dims)

#=
mutable structdef enum
{
    CUDNN_SOFTMAX_FAST     = 0,         /* straightforward implementation */
    CUDNN_SOFTMAX_ACCURATE = 1,         /* subtract max from every point to avoid overflow */
    CUDNN_SOFTMAX_LOG      = 2
} cudnnSoftmaxAlgorithm_t;

mutable structdef enum
{
    CUDNN_SOFTMAX_MODE_INSTANCE = 0,   /* compute the softmax over all C, H, W for each N */
    CUDNN_SOFTMAX_MODE_CHANNEL = 1     /* compute the softmax over all C for each H, W, N */
} cudnnSoftmaxMode_t;

=#

"""

    softmax(x; dims=1, algo=1)

The softmax function typically used in classification.
Gives the same results as to `exp.(logp(x, dims))`.

If `algo=1` computation is more accurate, if `algo=0` it is
faster.

See also `logsoftmax`.

"""
function softmax(x; dims=:, algo=1)
    generic_softmax(x, algo, _softmax; dims=dims)
end

function _softmax(x; dims=:, algo=1)
    @assert algo ∈ [0, 1]
    if algo == 1
        x = x .- maximum(x, dims=dims)
    end
    x = exp.(x)
    return x ./ sum(x;dims=dims)
end

function _softback(x,y,dy;dims=:)
    return y .* dy .- y .* sum(y .* dy; dims=dims)
end

@primitive  _softmax(x;dims=:,algo=1),dy,y  _softback(x,y,dy,dims=dims)

"""
     logsoftmax(x; dims=:)

 Equivalent to `logp(x; dims=:)`. See also `sotfmax`.
"""
const logsoftmax = logp

function dimvec(x, dims)
     sz = size(x)
     dims = dims == Colon() ? sz : dims
     sort(union(dims)),sz  # handles duplicate dimensions and integer/vector/tuple dims
end

generic_softmax(x,algo::Int,fallback;dims=:) = fallback(x;dims=dims,algo=algo)
function generic_softmax(x::T,algo::Int,fallback;dims=:) where T<:Union{<:KnetArray, AutoGrad.Value{<:KnetArray}}
    d,sz = dimvec(x,dims)
    if d==[1]
        x = cudnnSoftmaxForward(reshape(x, (1,1,sz[1],:)), algo=algo)
        reshape(x, sz)
    elseif d==[2] && ndims(x)==2
        generic_softmax(x',algo,fallback;dims=1)'
    elseif length(d)==ndims(x);
        n = length(x)
        (n > 20000 ? fallback(x) : # see Knet/prof/softmax.jl for timing info
        reshape(cudnnSoftmaxForward(reshape(x,(1,1,n,1)),algo=algo),size(x)))
    else
        fallback(x;dims=dims)
    end
end

function cudnnSoftmaxForward(x::KnetArray{T}; algo=0, mode=0, alpha=1, handle=cudnnhandle()) where {T}
    beta = 0 # nonzero beta does not make sense when we create y
    y = similar(x)
    @cudnn(cudnnSoftmaxForward,
          (Cptr, Cint, Cint, Ptr{T}, Cptr, Ptr{T}, Ptr{T}, Cptr, Ptr{T}),
          handle, algo, mode, Ref(T(alpha)), TD4(x), x, Ref(T(beta)), TD4(y), y)
    return y
end

function cudnnSoftmaxBackward(y::KnetArray{T}, dy::KnetArray{T}; algo=0, mode=0, alpha=1, handle=cudnnhandle()) where {T}
    beta = 0
    dx = similar(dy)
    @cudnn(cudnnSoftmaxBackward,
          (Cptr, Cint, Cint, Ptr{T}, Cptr, Ptr{T}, Cptr, Ptr{T}, Ptr{T}, Cptr, Ptr{T}),
          handle, algo, mode, Ref(T(alpha)), TD4(y), y, TD4(dy), dy, Ref(T(beta)), TD4(dx), dx)
    return dx
end

@primitive cudnnSoftmaxForward(x;o...),dy,y cudnnSoftmaxBackward(y,dy;o...)
@zerograd cudnnSoftmaxBackward(y,dy;o...)

function TD4(x::KnetArray)
    d = ndims(x)
    if d == 4 || d == 5
        TD(x)
    else
        n = size(x,d)
        m = div(length(x),n)
        TD(reshape(x,(1,1,m,n)))
    end
end

"""

    logsumexp(x;dims=:)

Compute `log(sum(exp(x);dims))` in a numerically stable manner.

`dims` is an optional argument, if not specified the summation is over
the whole `x`, otherwise the summation is performed over the given
dimensions.  In particular if `x` is a matrix, `dims=1` sums columns
of `x` and `dims=2` sums rows of `x`.

"""
function logsumexp(x;dims=:)
    xmax = maximum(x,dims=dims)
    xmax + log.(sum(exp.(x .- xmax),dims=dims))
end

@primitive logsumexp(x;dims=:),dy,y  (dy .* exp.(x .- y))

"""

    nll(scores, answers; dims=1, average=true)

Given an unnormalized `scores` matrix and an `Integer` array of
correct `answers`, return the per-instance negative log
likelihood. `dims=1` means instances are in columns, `dims=2` means
instances are in rows.  Use `average=false` to return the sum instead
of per-instance average.

"""
function nll(y,a::AbstractArray{<:Integer}; dims=1, average=true)
    indices = findindices(y,a,dims=dims)
    lp = logp(y,dims=dims)[indices]
    average ? -mean(lp) : -sum(lp)
end

"""
    logistic(scores, answers; average=true)
Computes logistic loss given scores(predicted values) and answer labels.
answer values should be {-1,1}, then it returns `mean|sum(log(1 + exp(-answers*scores)))`. See also `bce`.
"""
function logistic(x̂,x;average=true)
    ε = eltype(x̂)(1e-12)
    l = log.((1-ε) .+ exp.(-x .* x̂))
    average ? mean(l) : sum(l)
end

"""

    bce(scores,answers;average=true)

Computes binary cross entropy given scores(predicted values) and answer labels.
answer values should be {0,1}, then it returns negative of `mean|sum(answers * log(p) + (1-answers)*log(1-p))`
where `p` is equal to `1/(1 + exp.(scores))`. See also `logistic`.
"""
function bce(x̂,x;average=true)
    ε = eltype(x̂)(1e-12)
    p = 1 ./ (1 .+ exp.(-x̂))
    l = x .* log.(p .+ ε) .+ (1 .- x).*log.((1-ε) .- p)
    average ? -mean(l) : -sum(l)
end

"""

    accuracy(scores, answers; dims=1, average=true)

Given an unnormalized `scores` matrix and an `Integer` array of
correct `answers`, return the ratio of instances where the correct
answer has the maximum score. `dims=1` means instances are in columns,
`dims=2` means instances are in rows. Use `average=false` to return
the number of correct answers instead of the ratio.

"""
function accuracy(y,a::AbstractArray{<:Integer}; dims=1, average=true)
    indices = findindices(y,a,dims=dims)
    ycpu = convert(Array,y)
    (maxval,maxind) = findmax(ycpu,dims=dims)
    maxind = LinearIndices(ycpu)[maxind]
    correct = (vec(maxind) .== indices)
    average ? mean(correct) : sum(correct)
end

function findindices(y,a::AbstractArray{<:Integer}; dims=1)
    n = length(a)
    indices = Vector{Int}(undef,n)
    if dims == 1                   # instances in first dimension
        y1 = size(y,1)
        y2 = div(length(y),y1)
        if n != y2; throw(DimensionMismatch()); end
        @inbounds for j=1:n
            indices[j] = (j-1)*y1 + a[j]
        end
    elseif dims == 2               # instances in last dimension
        y2 = size(y,ndims(y))
        y1 = div(length(y),y2)
        if n != y1; throw(DimensionMismatch()); end
        @inbounds for j=1:n
            indices[j] = (a[j]-1)*y1 + j
        end
    else
        error("findindices only supports dims = 1 or 2")
    end
    return indices
end

"""
    nll(model, data; dims=1, average=true, o...)

Compute `nll(model(x; o...), y; dims)` for `(x,y)` in `data` and return the per-instance
average (if average=true) or total (if average=false) negative log likelihood.
"""
function nll(model, data; dims=1, average=true, o...)
    sum = cnt = 0
    for (x,y) in data
        sum += nll(model(x; o...), y; dims=dims, average=false)
        cnt += length(y)
    end
    average ? sum / cnt : sum
end

"""
    accuracy(model, data; dims=1, average=true, o...)

Compute `accuracy(model(x; o...), y; dims)` for `(x,y)` in `data` and return the ratio (if
average=true) or the count (if average=false) of correct answers.
"""
function accuracy(model, data; dims=1, average=true, o...)
    sum = cnt = 0
    for (x,y) in data
        sum += accuracy(model(x; o...), y; dims=dims, average=false)
        cnt += length(y)
    end
    average ? sum / cnt : sum
end

"zeroone loss is equal to 1 - accuracy"
zeroone(x...; o...) = 1 - accuracy(x...; o...)

# We need the (model,x,y) interface to implement regularization:
nll(f, x, y; dims=1, average=true, o...)=nll(f(x; o...), y; dims=dims, average=average)
accuracy(f, x, y; dims=1, average=true, o...)=accuracy(f(x; o...), y; dims=dims, average=average)

# We need the (weights,data,predict) interface to support the old interface:
nll(w, data, f::Function; dims=1, average=true, o...)=nll(x->f(w,x;o...), data; dims=dims, average=average)
accuracy(w, data, f::Function; dims=1, average=true, o...)=accuracy(x->f(w,x;o...), data; dims=dims, average=average)

ext: jl


text:
# sample model as in BayesExamples1 and 2, but using
# a specialized package and more sophisticated sampling
using Distributions, Turing, StatsPlots
function main()
# sample is from exponential, prior is lognormal
y = rand(Exponential(3.0), 300)
# the model: prior and likelihood
@model function ExpModel(y)
    θ ~ LogNormal(1.,1.)
    y ~ Exponential(θ)
end
# get the chain
chain = sample(ExpModel(y), NUTS(200, 0.65), 10000)
end
## run it
chain = main()
# examine and plot chain
display(chain)
plot(chain[end-1000:end])

max_stars_repo_name: mcreel/EconometricsNotes

max_issues_repo_name: mcreel/EconometricsNotes

max_forks_repo_name: mcreel/EconometricsNotes


text:
function value_of(::Type{TiesStrategy}, arg0::JString)
    return jcall(TiesStrategy, "valueOf", TiesStrategy, (JString,), arg0)
end

function values(::Type{TiesStrategy})
    return jcall(TiesStrategy, "values", Vector{TiesStrategy}, ())
end


text:
v1=SharedArray(collect(0.01:0.01:10.0))

v2=SharedArray(collect(20.0:5:60))

p0max=400.0
p0min=0.01

psmax=300.0
psmin=0.01

v1=SharedArray(exp.(collect(log(p0min):(log(p0max)-log(p0min))/100:log(p0max))))
v2=SharedArray(exp.(collect(log(psmin):(log(psmax)-log(psmin))/75:log(psmax))))

Imv1=[(i,j) for j in v2 for i in v1]

outvIm3 = pmap(
    p0 -> FRGRealTime.fastpropImintqs_All(
        pv,
        0.000001,
        30.0,
        1.0,
        800.0,
        4.0,
        m2fun,
        lamfun,
        rtol=1e-2,atol=1e-2,maxevals=80,initdiv=8,
    ),
    v1,
)

temp_T

outvIm4 = pmap(
    pv -> FRGRealTime.fastpropImintqs_All(
        pv[1],
        pv[2],
        temp_T,
        1.0,
        800.0,
        4.0,
        m2fun,
        lamfun,
        rtol=1e-10,atol=1e-10,maxevals=10000000,initdiv=40,
    ),
    Imv1,
)

plot(v1,outvIm4)

plot(v1[120:140],(outvIm4./(outvIm4.^2+outvRe.^2))[120:140],yaxis=:log)

outvIm4=pmap(p0->FRGRealTime.propImintqs_F4simple(p0, 0.0001, 40.0, 1.0, 800.0, 4.0, m2fun, lamfun),v1)

using Plots

plot(v1,outvIm3)
dir="/home/wjfu1/tyy/FRG-RealTime-data/Gamma2Im"
writedlm("$dir/propImI2p0+q0.dat",outvIm3)
writedlm("/home/tyy/Documents/CTP-fRG-Test/Real-Time-data/Im/ImI2p0+q0.dat",outvIm3)

vI1pmq=readdlm("/home/tyy/Documents/CTP-fRG-Test/Real-Time-data/Im/ImI1p0-q0.dat")
vI1ppq=readdlm("/home/tyy/Documents/CTP-fRG-Test/Real-Time-data/Im/ImI1p0+q0.dat")
vI2pmq=readdlm("/home/tyy/Documents/CTP-fRG-Test/Real-Time-data/Im/ImI2p0-q0.dat")
vI2ppq=readdlm("/home/tyy/Documents/CTP-fRG-Test/Real-Time-data/Im/ImI2p0+q0.dat")

plot(v1,vI1pmq,label="I1 p-q",legend=:topleft)
plot!(v1,vI1ppq,label="I1 p+q",legend=:topleft)
plot!(v1,vI2pmq,label="I2 p-q",legend=:topleft)
plot!(v1,vI2ppq,label="I2 p+q",legend=:topleft)

plot!(v1,vI1pmq+vI1ppq+vI2pmq+vI2ppq,label="Total",legend=:topleft)

FRGRealTime.fastpropImintqs_F4(
    10.00,
    0.000001,
    145.0,
    1.0,
    800.0,
    4.0,
    m2fun,
    lamfun,
    rtol=1e-2,atol=1e-2,maxevals=10,initdiv=200,
)

outvIm4=pmap(
    p0 -> FRGRealTime.fastpropImintqs_All(
        p0,
        0.000001,
        100.0,
        20.0,
        100.0,
        4.0,
        m2fun,
        lamfun,rtol=1e-3,atol=1e-3
    ),
    v2,
)-pmap(
    p0 -> FRGRealTime.fastpropImintqs_F4(
        p0,
        0.000001,
        100.0,
        20.0,
        100.0,
        4.0,
        m2fun,
        lamfun,rtol=1e-3,atol=1e-3
    ),
    v2
)

outvIm5=pmap(
    p0 -> FRGRealTime.propImSimple_dq0(
        p0,
        0.000001,
        100.0,
        20.0,
        100.0,
        4.0,
        m2fun(200.0),
        -10.0
    ),
    v2,
)
FRGRealTime.

outvIm6=pmap(
    p0 -> FRGRealTime.fastpropImintqs_All_dVdq0(
        p0,
        0.000001,
        100.0,
        20.0,
        100.0,
        4.0,
        m2fun,
        lamfun,rtol=1e-3,atol=1e-3
    ),
    v2,
)

FRGRealTime.propImSimple_dq0(
    40.0,
    0.000001,
    100.0,
    40.0,
    100.0,
    4.0,
    m2fun(200.0),
    -10.0
)

plot(k->3 * Epi(k, m2fun(k)),20,100)

using Plots

plot(v2,outvIm4)
plot(v2,outvIm5)
plot!(v2,outvIm6)

FRGRealTime.deltasumkfix(100.0, 0.0001, 100.0, 100.0, 4.0,1.0, 800.0, m2fun, lamfun)

FRGRealTime.propImSimple_dq0(
    10.0,
    0.000001,
    100.0,
    10.0,
    200.0,
    4.0,
    10.0^2,
    -10.0
)

FRGRealTime.VImintqsSimple_dq0(10.0, 0.0001, 10.0, 100.0, 4.0, 100.0, -10.0,200.0)

FRGRealTime.VImSimple(10.0, 0.0001, 20.0, 10.0, 100.0, 100.0, 4.0, -10.0, 200.0)

FRGRealTime.loopfunppSmooth(10.0, 0.0001, 20.0, 100.0, 100.0)

plot(v1,outvIm3)
plot!(v1,outvIm3+outvIm4)
plot!(v1,outvIm4)

pmap(
    p0 -> FRGRealTime.propImintqs(
        p0,
        0.000001,
        100.0,
        1.0,
        400.0,
        4.0,
        m2fun,
        lamfun,
    ),
    v1,
)

using Plots

outvIm3=map(
    p0 -> FRGRealTime.propImintqs_F4simple(
        p0,
        0.000001,
        100.0,
        1.0,
        400.0,
        4.0,
        m2fun,
        lamfun,
    ),
    v1,
)

outvIm4=map(
    p0 -> FRGRealTime.fastpropImintqs_F4(
        p0,
        0.000001,
        100.0,
        1.0,
        400.0,
        4.0,
        m2fun,
        lamfun,rtol=1e-3,atol=1e-3
    ),
    v1,
)

FRGRealTime.fastpropImintqs_F4(
    15.0,
    0.000001,
    100.0,
    1.0,
    50.0,
    4.0,
    m2fun,
    lamfun,rtol=1e-4,atol=1e-4,initdiv=200,maxevals=100000000
)

FRGRealTime.propImintqs_F4simple(
    15.0,
    0.000001,
    100.0,
    1.0,
    50.0,
    4.0,
    m2fun,
    lamfun,
)

using Plots

plot(x->sin(x),1.0,10.0)

plot(v1, outvIm3, xaxis = "p0", label = "T=145,Λ=400")
plot!(v1, outvIm4, xaxis = "p0", label = "T=145,Λ=400")

plot(v1, outvIm2+outvIm, xaxis = "p0", label = "T=145,Λ=400")

FRGRealTime.fastpropImintqs_All(
    600.0,
    0.000001,
    100.0,
    1.0,
    1600.0,
    4.0,
    m2fun,
    lamfun,atol=1e-3,rtol=1e-3
)

plot(k->FRGRealTime.VImintqs(
    20.0,
    0.0001,
    k,
    100.0,
    4.0,
    1.0,
    1600.0,
    m2fun,
    lamfun,
),1.0,1600.0)

FRGRealTime.VImintqsSimple(
    335.0,
    0.0001,
    10.0,
    100.0,
    4.0,
    m2fun,
    lamfun,
    1600.0,
)


text:
abstract type AbstractStrideArray{S,D,T,N,C,B,R,X,O} <: DenseArray{T,N} end
abstract type AbstractPtrStrideArray{S,D,T,N,C,B,R,X,O} <: AbstractStrideArray{S,D,T,N,C,B,R,X,O} end
const AbstractStrideVector{S,D,T,C,B,R,X,O} = AbstractStrideArray{S,D,T,1,C,B,R,X,O}
const AbstractStrideMatrix{S,D,T,C,B,R,X,O} = AbstractStrideArray{S,D,T,2,C,B,R,X,O}

struct PtrArray{S,D,T,N,C,B,R,X,O} <: AbstractPtrStrideArray{S,D,T,N,C,B,R,X,O}
    ptr::StridedPointer{T,N,C,B,R,X,O}
    size::S
end
@inline function PtrArray(ptr::StridedPointer{T,N,C,B,R,X,O}, size::S, ::Val{D}) where {S,D,T,N,C,B,R,X,O}
    PtrArray{S,D,T,N,C,B,R,X,O}(ptr, size)
end

const PtrVector{S,D,T,C,B,R,X,O} = PtrArray{S,D,T,1,C,B,R,X,O}
const PtrMatrix{S,D,T,C,B,R,X,O} = PtrArray{S,D,T,2,C,B,R,X,O}

@inline PtrArray(A::AbstractArray) = PtrArray(stridedpointer(A), size(A), val_dense_dims(A))

@inline VectorizationBase.stridedpointer(A::PtrArray) = getfield(A, :ptr)
@inline Base.pointer(A::AbstractStrideArray) = pointer(stridedpointer(A))
@inline Base.unsafe_convert(::Type{Ptr{T}}, A::AbstractStrideArray) where {T} = Base.unsafe_convert(Ptr{T}, pointer(A))
@inline Base.elsize(::AbstractStrideArray{<:Any,<:Any,T}) where {T} = sizeof(T)

@inline ArrayInterface.size(A::PtrArray) = getfield(A, :size)
@inline VectorizationBase.bytestrides(A::PtrArray) = getfield(getfield(A, :ptr), :strd)
ArrayInterface.device(::AbstractStrideArray) = ArrayInterface.CPUPointer()

ArrayInterface.contiguous_axis(::Type{<:AbstractStrideArray{S,D,T,N,C}}) where {S,D,T,N,C} = StaticInt{C}()
ArrayInterface.contiguous_batch_size(::Type{<:AbstractStrideArray{S,D,T,N,C,B}}) where {S,D,T,N,C,B} = ArrayInterface.StaticInt{B}()

static_expr(N::Int) = Expr(:call, Expr(:curly, :StaticInt, N))
static_expr(b::Bool) = Expr(:call, b ? :True : :False)
@generated function ArrayInterface.stride_rank(::Type{<:AbstractStrideArray{S,D,T,N,C,B,R}}) where {S,D,T,N,C,B,R}
    t = Expr(:tuple)
    for r ∈ R
        push!(t.args, static_expr(r::Int))
    end
    t
end
@generated function ArrayInterface.dense_dims(::Type{<:AbstractStrideArray{S,D}}) where {S,D}
    t = Expr(:tuple)
    for d ∈ D
        push!(t.args, static_expr(d::Bool))
    end
    t
end

@inline bytestride(A, n) = VectorizationBase.bytestrides(A)[n]
function default_stridedpointer_quote(::Type{T}, N, Ot) where {T}
    C = 1
    B = 0
    R = Expr(:tuple)
    o = Expr(:tuple)
    for n ∈ 1:N
        push!(R.args, n)
        push!(o.args, Expr(:call, Ot))
    end
    quote
        $(Expr(:meta,:inline))
        StridedPointer{$T,$N,$C,$B,$R}(ptr, x, $o)
    end
end

@generated function default_stridedpointer(ptr::Ptr{T}, x::X) where {T, N, X <: Tuple{Vararg{Integer,N}}}
    default_stridedpointer_quote(T, N, :One)
end
@generated function default_zerobased_stridedpointer(ptr::Ptr{T}, x::X) where {T, N, X <: Tuple{Vararg{Integer,N}}}
    default_stridedpointer_quote(T, N, :Zero)
end
@inline function ptrarray0(ptr::Ptr{T}, s::Tuple{Vararg{Integer,N}}, x::Tuple{Vararg{Integer,N}}, ::Val{D}) where {T,N,D}
    PtrArray(default_zerobased_stridedpointer(ptr, x), s, Val{D}())
end
@inline function PtrArray(ptr::Ptr{T}, s::Tuple{Vararg{Integer,N}}, x::Tuple{Vararg{Integer,N}}, ::Val{D}) where {T,N,D}
    PtrArray(default_stridedpointer(ptr, x), s, Val{D}())
end

function ptrarray_densestride_quote(::Type{T}, N, stridedpointer_offsets) where {T}
    last_sx = :s_0
    q = Expr(:block, Expr(:meta,:inline), Expr(:(=), last_sx, static_expr(sizeof(T))))
    t = Expr(:tuple); d = Expr(:tuple);
    n = 0
    while true
        n += 1
        push!(t.args, last_sx)
        push!(d.args, true)
        n == N && break
        new_sx = Symbol(:s_,n)
        push!(q.args, Expr(:(=), new_sx, Expr(:call, :vmul_fast, last_sx, Expr(:ref, :s, n))))
        last_sx = new_sx
    end
    push!(q.args, :(PtrArray($stridedpointer_offsets(ptr, $t), s, Val{$d}())))
    q
end
@generated function PtrArray(ptr::Ptr{T}, s::Tuple{Vararg{Integer,N}}) where {T,N}
    ptrarray_densestride_quote(T, N, :default_stridedpointer)
end
@generated function ptrarray0(ptr::Ptr{T}, s::Tuple{Vararg{Integer,N}}) where {T,N}
    ptrarray_densestride_quote(T, N, :default_zerobased_stridedpointer)
end

@generated function ArrayInterface.strides(A::PtrArray{S,D,T,N}) where {S,D,T,N}
    shifter = static_expr(VectorizationBase.intlog2(sizeof(T)))
    x = Expr(:tuple)
    for n in 1:N
        push!(x.args, Expr(:call, :(>>>), Expr(:ref, :x, n), shifter))
    end
    quote
        $(Expr(:meta,:inline))
        x = A.ptr.strd
        $x
    end
end

@inline Base.size(A::AbstractStrideArray) = map(Int, size(A))
@inline Base.strides(A::AbstractStrideArray) = map(Int, strides(A))

@inline create_axis(s, ::Zero) = CloseOpen(s)
@inline create_axis(s, ::One) = One():s
@inline create_axis(s, o) = CloseOpen(s, s+o)

@inline ArrayInterface.axes(A::AbstractStrideArray) = map(create_axis, size(A), offsets(A))
@inline Base.axes(A::AbstractStrideArray) = axes(A)

@inline ArrayInterface.offsets(A::PtrArray) = getfield(getfield(A, :ptr), :offsets)
@inline ArrayInterface.static_length(A::AbstractStrideArray) = prod(size(A))

# type stable, because index known at compile time
@inline type_stable_select(t::NTuple, ::StaticInt{N}) where {N} = t[N]
@inline type_stable_select(t::Tuple, ::StaticInt{N}) where {N} = t[N]
# type stable, because tuple is homogenous
@inline type_stable_select(t::NTuple, i::Integer) = t[i]
# make the tuple homogenous before indexing
@inline type_stable_select(t::Tuple, i::Integer) = map(Int, t)[i]

@inline function ArrayInterface.axes(A::AbstractStrideVector, i::Integer)
    if i == 1
        o = type_stable_select(offsets(A), i)
        s = type_stable_select(size(A), i)
        return create_axis(s, o)
    else
        return One():1
    end
end
@inline function ArrayInterface.axes(A::AbstractStrideArray, i::Integer)
    o = type_stable_select(offsets(A), i)
    s = type_stable_select(size(A), i)
    create_axis(s, o)
end
@inline Base.axes(A::AbstractStrideArray, i::Integer) = axes(A, i)

@inline function ArrayInterface.size(A::AbstractStrideVector, i::Integer)
    d = Int(length(A))
    ifelse(isone(i), d, one(d))
end
@inline ArrayInterface.size(A::AbstractStrideVector, ::StaticInt{N}) where {N} = One()
@inline ArrayInterface.size(A::AbstractStrideVector, ::StaticInt{1}) = length(A)
@inline ArrayInterface.size(A::AbstractStrideArray, ::StaticInt{N}) where {N} = size(A)[N]
@inline ArrayInterface.size(A::AbstractStrideArray, i::Integer) = type_stable_select(size(A), i)
@inline Base.size(A::AbstractStrideArray, i::Integer) = size(A, i)

# Base.IndexStyle(::Type{<:AbstractStrideArray}) = IndexCartesian()
# Base.IndexStyle(::Type{<:AbstractStrideVector{<:Any,<:Any,<:Any,1}}) = IndexLinear()
@generated function Base.IndexStyle(::Type{<:AbstractStrideArray{S,D,T,N,C,B,R}}) where {S,D,T,N,C,B,R}
    # if is column major || is a transposed contiguous vector
    if all(D) && ((isone(C) && R === ntuple(identity, Val(N))) || (C === 2 && R === (2,1) && S <: Tuple{One,Integer}))
        :(IndexLinear())
    else
        :(IndexCartesian())
    end
end

@inline VectorizationBase.preserve_buffer(A::PtrArray) = nothing
Base.@propagate_inbounds Base.getindex(A::AbstractStrideVector, i::Int, j::Int) = A[i]
@inline function Base.getindex(A::PtrArray{S,D,T,K}, i::Vararg{Integer,K}) where {S,D,T,K}
    @boundscheck checkbounds(A, i...)
    vload(stridedpointer(A), i)
end
@inline function Base.getindex(A::AbstractStrideArray{S,D,T,K}, i::Vararg{Integer,K}) where {S,D,T,K}
    b = preserve_buffer(A)
    P = PtrArray(A)
    GC.@preserve b begin
        @boundscheck checkbounds(P, i...)
        vload(stridedpointer(P), i)
    end
end
@inline function Base.setindex!(A::PtrArray{S,D,T,K}, v, i::Vararg{Integer,K}) where {S,D,T,K}
    @boundscheck checkbounds(A, i...)
    vstore!(stridedpointer(A), v, i)
    v
end
@inline function Base.setindex!(A::AbstractStrideArray{S,D,T,K}, v, i::Vararg{Integer,K}) where {S,D,T,K}
    b = preserve_buffer(A)
    P = PtrArray(A)
    GC.@preserve b begin
        @boundscheck checkbounds(P, i...)
        vstore!(stridedpointer(P), v, i)
    end
    v
end
@inline function Base.getindex(A::PtrArray, i::Integer)
    @boundscheck checkbounds(A, i)
    vload(stridedpointer(A), (i - one(i),))
end
@inline function Base.getindex(A::AbstractStrideArray, i::Integer)
    b = preserve_buffer(A)
    P = PtrArray(A)
    GC.@preserve b begin
        @boundscheck checkbounds(P, i)
        vload(stridedpointer(P), (i - one(i),))
    end
end
@inline function Base.setindex!(A::PtrArray, v, i::Integer)
    @boundscheck checkbounds(A, i)
    vstore!(stridedpointer(A), v, (i - one(i),))
    v
end
@inline function Base.setindex!(A::AbstractStrideArray, v, i::Integer)
    b = preserve_buffer(A)
    P = PtrArray(A)
    GC.@preserve b begin
        @boundscheck checkbounds(P, i)
        vstore!(stridedpointer(P), v, (i - one(i),))
    end
    v
end


text:
module Transaction

using HTTP, JSON3, Dates

export getTransactionPages, getTransaction, getTransactions

#------------------------------------------------------------------------------------
#/accounts/{accountID}/transactions Endpoint
#------------------------------------------------------------------------------------
"""
The transaction pages

# Fields
- 'from': where pages start
- 'to': where pages end
- 'pageSize': size of each page
- 'type::Vector{String}': The type of the transaction pages
- 'count': number of pages
- 'pages::Vector{String}': The pages
- 'lastTransactionID': the last transaction id
"""
mutable struct transactionPages
    from
    to
    pageSize
    type::Vector{String}
    count
    pages::Vector{String}
    lastTransactionID

    transactionPages() = new()
end

# Declaring JSON3 struct types
JSON3.StructType(::Type{transactionPages}) = JSON3.Mutable()

# Conversions to proper Julia types
function coerceTransactionPages(tpages::transactionPages)

    RFC = Dates.DateFormat("yyyy-mm-ddTHH:MM:SS.sssssssssZ")

    tpages.from = DateTime(first(tpages.from, 23), RFC) #DateTime has milliseconds precision. Can only use 23 characters...
    tpages.to = DateTime(first(tpages.to, 23), RFC)
    tpages.lastTransactionID = parse(Int, tpages.lastTransactionID)

    return tpages
end

"""
    getTransactionPages(config::config; from::DateTime=nothing, to::DateTime=Dates.now(), pageSize::Int=100, type::String=nothing)

Return a struct. Field ':pages' includes the urls for requesting the transactions data in the given timeframe

# Arguments
- 'config::config': a valid config file
- 'from::Union{DateTime, Nothing}': get transactions from
- 'to::DateTime': get transactions to
- 'pageSize::Int': Size of each page
- 'type::Union{String,Nothing}': type of pages to request

# Example
    getTransactionPages(userdata, from=DateTime(2019,5,31),type="MARKET_ORDER,STOP_LOSS_ORDER")
"""
function getTransactionPages(
    config;
    from::Union{DateTime,Nothing} = nothing,
    to::DateTime = Dates.now(),
    pageSize::Int = 100,
    type::Union{String,Nothing} = nothing,
)

    q = Dict(
        "to" => Dates.format(to, "yyyy-mm-ddTHH:MM:SS.000000000Z"),
        "pageSize" => pageSize,
    )
    !isnothing(from) && push!(
        q,
        "from" => Dates.format(from, "yyyy-mm-ddTHH:MM:SS.000000000Z"),
    )
    !isnothing(type) && push!(q, "type" => type)

    r = HTTP.get(
        string(
            "https://",
            config.hostname,
            "/v3/accounts/",
            config.account,
            "/transactions",
        ),
        [
         "Authorization" => string("Bearer ", config.token),
         "Accept-Datetime-Format" => "RFC3339",
        ];
        query = q,
    )

    return JSON3.read(r.body, transactionPages) |> coerceTransactionPages
end
#------------------------------------------------------------------------------------
#/accounts/{accountID}/transactions/{transactionID} Endpoint
#------------------------------------------------------------------------------------
"""
Transactions

# Fields
- 'transaction::Dict{String,Any}': The transaction data
- 'lastTransactionID': The last transaction
"""
mutable struct transaction
    transaction::Dict{String,Any}
    lastTransactionID

    transaction() = new()
end

# Declaring JSON3 struct types
JSON3.StructType(::Type{transaction}) = JSON3.Mutable()

"Recursive coersion of transaction Dictionaries to proper Julia types"
function coerceTransactionDict(tDict::Dict{String,Any}) #Also used in getTransactions endpoints

    valueFields = [
        "price",
        "priceBound",
        "fullVWAP",
        "distance",
        "closeoutBid",
        "closeoutAsk",
        "marginRate",
        "initialMarginRequired",
        "requestedUnits",
        "liquidity",
        "gainQuoteHomeConversionFactor",
        "lossQuoteHomeConversionFactor",
        "AccountBalance",
        "amount",
        "financing",
        "pl",
        "commission",
        "guaranteedExecutionFee",
        "halfSpreadCost",
        "dividend",
        "realizedPL",
        "bidLiquidityUsed",
        "askLiquidityUsed",
    ]

    timeFields = ["timestamp", "time", "gtdTime"]
    RFC = Dates.DateFormat("yyyy-mm-ddTHH:MM:SS.sssssssssZ")

    for (key, value) in tDict
        if eltype(value) == Pair{String,Any}
            tDict[key] = coerceTransactionDict(tDict[key]) #Recursion for Dictionaries inside a transaction field
        elseif eltype(value) == Any #'asks' & 'bids' in 'fullPrice' have an array of liquidity, prices
            tDict[key] = collect(coerceTransactionDict.(tDict[key]))
        elseif key in valueFields
            tDict[key] = parse(Float32, value)
        elseif key == "units" && value != "ALL"
            tDict[key] = parse(Float32, value)
        elseif key in timeFields
            tDict[key] = DateTime(first(value, 23), RFC)
        end
    end

    return tDict
end

"""
    getTransaction(config::config, tID::Int)

Return a Dictionary with the transaction data

# Arguments
- 'config::config': a valid config object
- 'tID::Int': transaction ID

# Example
    getTransaction(userdata,4)
"""
function getTransaction(config, tID::Int)

    r = HTTP.get(
        string(
            "https://",
            config.hostname,
            "/v3/accounts/",
            config.account,
            "/transactions/",
            string(tID),
        ),
        [
         "Authorization" => string("Bearer ", config.token),
         "Accept-Datetime-Format" => "RFC3339",
        ],
    )

    temp = JSON3.read(r.body, transaction)
    temp.transaction = coerceTransactionDict(temp.transaction)
    return temp
end
#------------------------------------------------------------------------------------
#/accounts/{accountID}/transactions/idrange  Endpoint
#/accounts/{accountID}/transactions/sinceid  Endpoint
#------------------------------------------------------------------------------------

mutable struct transactions
    transactions::Array{Dict{String,Any},1}
    lastTransactionID

    transactions() = new()
end

# Declaring JSON3 struct types
JSON3.StructType(::Type{transactions}) = JSON3.Mutable()

"""
    getTransactions(config::config, fromID::Int, toID::Int, type::Union{String,Nothing}=nothing)
    getTransactions(config::config, sinceID::Int, type::Union{String,Nothing}=nothing)

Return an array of Dictionaries with the transactions data

# Arguments
- 'config::config': a valid config struct
- 'type::Union{String,Nothing}': Specify transaction types

- 'fromID::Int', 'toID::Int': Get all transactions between two ID's

OR

- 'sinceID::Int': Get all transactions since an ID

# Examples
    getTransactions(userdata,3,"MARKET_ORDER,STOP_LOSS_ORDER")
    getTransactions(userdata,2,10)
"""
function getTransactions(
    config,
    fromID::Int,
    toID::Int,
    type::Union{String,Nothing} = nothing,
)

    q = Dict("from" => string(fromID), "to" => string(toID))
    !isnothing(type) && push!(q, "type" => type)

    r = HTTP.get(
        string(
            "https://",
            config.hostname,
            "/v3/accounts/",
            config.account,
            "/transactions/idrange",
        ),
        [
         "Authorization" => string("Bearer ", config.token),
         "Accept-Datetime-Format" => "RFC3339",
        ];
        query = q,
    )

    temp = JSON3.read(r.body, transactions)

    for dict in temp.transactions
        dict = coerceTransactionDict(dict)
    end

    return temp
end

function getTransactions(
    config,
    sinceID::Int,
    type::Union{String,Nothing} = nothing,
)

    q = Dict("id" => string(sinceID))
    !isnothing(type) && push!(q, "type" => type)

    r = HTTP.get(
        string(
            "https://",
            config.hostname,
            "/v3/accounts/",
            config.account,
            "/transactions/sinceid",
        ),
        [
         "Authorization" => string("Bearer ", config.token),
         "Accept-Datetime-Format" => "RFC3339",
        ];
        query = q,
    )

    temp = JSON3.read(r.body, transactions)

    for dict in temp.transactions
        dict = coerceTransactionDict(dict)
    end

    return temp
end
#------------------------------------------------------------------------------------
#/accounts/{accountID}/transactions/stream Endpoint
#------------------------------------------------------------------------------------

end #Module

max_stars_repo_name: CalebDepatie/Julianda

max_forks_repo_name: CalebDepatie/Julianda


text:
using CorpusLoaders
using Base.Test
using Base.Iterators
using MultiResolutionIterators

@testset "basic use" for path in [datadep"SemCor 1.6", datadep"SemCor 1.7", datadep"SemCor 1.7.1", datadep"SemCor 2.0", datadep"SemCor 3.0", datadep"SemCor 3.0/brownv"]
    wk_gen = load(SemCor(path))
    docs = collect(take(wk_gen, 10));

    words = consolidate(flatten_levels(docs, (!lvls)(SemCor, :word)))
    @test length(words) > length(docs)
    @test length(words) > sum(length.(docs))
    @test typeof(words) == Vector{CorpusLoaders.TaggedWord}

    plain_words = word.(words)
    @test typeof(plain_words) <: Vector{String}
    @test all(startswith.(title.(docs), "br"))
end

@testset "Index" begin
    corp = load(SemCor())
    index = Dict{String, Vector{Vector{String}}}()
    for sentence in flatten_levels(corp, (!lvls)(SemCor, :sent, :word))
        multisense_words = filter(x->x isa SenseAnnotatedWord,  sentence)
        context_words = word.(sentence)
        for target in multisense_words
            word_sense = sensekey(target)
            uses = get!(Vector{Vector{String}}, index, word_sense)
            push!(uses, context_words)
        end
    end
    index

    index["abandon%1:07:00::"]
    index["abandon%2:38:00::"]
    index["abandon%2:40:00::"]
    index["abandon%2:40:01::"]
end


text:
using PtFEM, Test

data = Dict(
  # Beam(ndim, nst, nxe, nip, direction, finite_element(nod, nodof), axisymmetric)
  :struc_el => Beam(2, 1, 4, 1, :x, Line(2, 1), false),
  :properties => [1.0;],
  :x_coords => [0.0, 0.25, 0.5, 0.75, 1.0],
  :support => [
    (1, [0 1]),
    (5, [0 0])
    ],
  :limit => 100,
  :tol => 0.00001
)

@time m = p46(data)

@test m[4] ≈ [0.0,0.7273399696355276,0.15236981309765138,0.3883541804128791,
  0.1686800077576337,-0.24396646116150877,0.06725268705915496,
  -0.4521565393506495]


text:
# using Cairo

# li = joinpath(dirname(Cairo._jl_libcairo), "libcairo-script-interpreter.so")
# if isfile(li)
#     a = joinpath(dirname(@__FILE__),"deps.jl")
#     display(a)
#     f = open(a,"w")
#     write(f,"_jl_libcairo-script-interpreter = \"" * li * "\";")
#     close(f)
# else
#     error("couldn't find libcairo-script-interpreter.so")
# end

# # check for cairo version
# function validate_cairo_version(name,handle)
#     f = Libdl.dlsym_e(handle, "cairo_version")
#     f == C_NULL && return false
#     v = ccall(f, Int32,())
#     return v > 10800
# end

# group = library_group("cairo")

using BinDeps
using Compat

@BinDeps.setup

csi = library_dependency("csi", aliases = ["libcairo-script-interpreter", "libcairo-script-interpreter-2.2", "libcairo-script-interpreter-2-2", "libcairo-script-interpreter-2.dll", "libcairo-script-interpreter-2.so.2"])

if Sys.islinux() begin
        provides(AptGet, "libcairo-script-interpreter2-2",csi)
    end
end

if Sys.isapple() begin
        using Homebrew
        provides(Homebrew.HB, "cairo", [csi], os=:Darwin)
    end
end

if Sys.iswindows() begin
        using WinRPM
        provides(WinRPM.RPM,"libcairo-script-interpreter2",csi,os = :Windows)
    end
end

@BinDeps.install Dict(:csi => :_jl_libcsi)

# cairoscriptinterpreter = library_dependency("cairoscriptinterpreter", aliases = ["libcairo.so.2"])

# if is_windows()
#     using WinRPM
#     provides(WinRPM.RPM,"libpango-1_0-0",[pango,pangocairo],os = :Windows)
#     provides(WinRPM.RPM,["glib2", "libgobject-2_0-0"],gobject,os = :Windows)
#     provides(WinRPM.RPM,"zlib-devel",zlib,os = :Windows)
#     provides(WinRPM.RPM,["libcairo2","libharfbuzz0"],cairo,os = :Windows)
# end

# if is_apple()
#     if Pkg.installed("Homebrew") === nothing
#         error("Homebrew package not installed, please run Pkg.add(\"Homebrew\")")
#     end
#     using Homebrew
#     provides( Homebrew.HB, "cairo", cairo, os = :Darwin )
#     provides( Homebrew.HB, "pango", [pango, pangocairo], os = :Darwin, onload =
#     """
#     function __init__()
#         ENV["PANGO_SYSCONFDIR"] = joinpath("$(Homebrew.prefix())", "etc")
#     end
#     """ )
#     provides( Homebrew.HB, "fontconfig", fontconfig, os = :Darwin )
#     provides( Homebrew.HB, "glib", gobject, os = :Darwin )
#     provides( Homebrew.HB, "libpng", libpng, os = :Darwin )
#     provides( Homebrew.HB, "gettext", gettext, os = :Darwin )
#     provides( Homebrew.HB, "freetype", freetype, os = :Darwin )
#     provides( Homebrew.HB, "libffi", libffi, os = :Darwin )
#     provides( Homebrew.HB, "pixman", pixman, os = :Darwin )
# end

# # System Package Managers
# provides(AptGet,
#     @compat Dict(
#         "libcairo2" => cairo,
#         "libfontconfig1" => fontconfig,
#         "libpango1.0-0" => [pango,pangocairo],
#         "libglib2.0-0" => gobject,
#         "libpng12-0" => libpng,
#         "libpixman-1-0" => pixman,
#         "gettext" => gettext
#     ))

# # TODO: check whether these are accurate
# provides(Yum,
#     @compat Dict(
#         "cairo" => cairo,
#         "fontconfig" => fontconfig,
#         "pango" => [pango,pangocairo],
#         "glib2" => gobject,
#         "libpng" => libpng,
#         "gettext-libs" => gettext
#     ))

# provides(Zypper,
#     @compat Dict(
#         "libcairo" => cairo,
#         "libfontconfig" => fontconfig,
#         "libpango-1.0" => [pango,pangocairo],
#         "libglib-2.0" => gobject,
#         "libpng12" => libpng,
#         "libpixman-1" => pixman,
#         "gettext" => gettext
#     ))

# const png_version = "1.5.14"

# provides(Sources,
#     @compat Dict(
#         URI("http://www.cairographics.org/releases/pixman-0.28.2.tar.gz") => pixman,
#         URI("http://www.cairographics.org/releases/cairo-1.12.16.tar.xz") => cairo,
#         URI("http://download.savannah.gnu.org/releases/freetype/freetype-2.4.11.tar.gz") => freetype,
#         URI("http://www.freedesktop.org/software/fontconfig/release/fontconfig-2.10.2.tar.gz") => fontconfig,
#         URI("http://ftp.gnu.org/pub/gnu/gettext/gettext-0.18.2.tar.gz") => gettext,
#         URI("ftp://ftp.simplesystems.org/pub/libpng/png/src/history/libpng15/libpng-$(png_version).tar.gz") => libpng,
#         URI("ftp://sourceware.org/pub/libffi/libffi-3.0.11.tar.gz") => libffi,
#         URI("http://ftp.gnome.org/pub/gnome/sources/glib/2.34/glib-2.34.3.tar.xz") => gobject,
#         URI("http://ftp.gnome.org/pub/GNOME/sources/pango/1.32/pango-1.32.6.tar.xz") => [pango,pangocairo],
#         URI("http://zlib.net/zlib-1.2.7.tar.gz") => zlib
#     ))

# xx(t...) = (is_windows() ? t[1] : (is_linux() || length(t) == 2) ? t[2] : t[3])

# provides(BuildProcess,
#     @compat Dict(
#         Autotools(libtarget = "pixman/libpixman-1.la", installed_libname = xx("libpixman-1-0.","libpixman-1.","libpixman-1.0.")*Libdl.dlext) => pixman,
#         Autotools(libtarget = xx("objs/.libs/libfreetype.la","libfreetype.la")) => freetype,
#         Autotools(libtarget = "src/libfontconfig.la") => fontconfig,
#         Autotools(libtarget = "src/libcairo.la", configure_options = append!(append!(
#                 AbstractString[],
#                 !is_linux() ? AbstractString["--without-x","--disable-xlib","--disable-xcb"] : AbstractString[]),
#                 is_apple() ? AbstractString["--enable-quartz","--enable-quartz-font","--enable-quartz-image","--disable-gl"] : AbstractString[])) => cairo,
#         Autotools(libtarget = "gettext-tools/gnulib-lib/.libs/libgettextlib.la") => gettext,
#         Autotools(libtarget = "libffi.la") => libffi,
#         Autotools(libtarget = "gobject/libgobject-2.0.la") => gobject,
#         Autotools(libtarget = "pango/libpango-1.0.la") => [pango,pangocairo]
#     ))

# provides(BuildProcess,Autotools(libtarget = "libpng15.la"),libpng,os = :Unix)

# provides(SimpleBuild,
#     (@build_steps begin
#         GetSources(zlib)
#         @build_steps begin
#             ChangeDirectory(joinpath(BinDeps.depsdir(zlib),"src","zlib-1.2.7"))
#             MakeTargets(["-fwin32/Makefile.gcc"])
#             #MakeTargets(["-fwin32/Makefile.gcc","DESTDIR=../../usr/","INCLUDE_PATH=include","LIBRARY_PATH=lib","SHARED_MODE=1","install"])
#         end
#     end),zlib, os = :Windows)

# prefix=joinpath(BinDeps.depsdir(libpng),"usr")
# uprefix = replace(replace(prefix,"\\","/"),"C:/","/c/")
# pngsrcdir = joinpath(BinDeps.depsdir(libpng),"src","libpng-$png_version")
# pngbuilddir = joinpath(BinDeps.depsdir(libpng),"builds","libpng-$png_version")
# provides(BuildProcess,
#     (@build_steps begin
#         GetSources(libpng)
#         CreateDirectory(pngbuilddir)
#         @build_steps begin
#             ChangeDirectory(pngbuilddir)
#             FileRule(joinpath(prefix,"lib","libpng15.dll"),@build_steps begin
#                 `cmake -DCMAKE_INSTALL_PREFIX="$prefix" -G"MSYS Makefiles" $pngsrcdir`
#                 `make`
#                 `cp 'libpng*.dll' $prefix/lib`
#                 `cp 'libpng*.a' $prefix/lib`
#                 `cp 'libpng*.pc' $prefix/lib/pkgconfig`
#                 `cp pnglibconf.h $prefix/include`
#                 `cp $pngsrcdir/png.h $prefix/include`
#                 `cp $pngsrcdir/pngconf.h $prefix/include`
#             end)
#         end
#     end),libpng, os = :Windows)

# @BinDeps.install Dict([(:cairoscriptinterpreter, :_jl_libcairo-script-interpreter)])


text:
###############################################
#FEniCS tutorial demo program: Diffusion of a Gaussian hill.
#  u'= Laplace(u) + f  in a square domain
#  u = u_D             on the boundary
#  u = u_0             at t = 0
#  u_D = f = 0
#The initial condition u_0 is chosen as a Gaussian hill.
###############################################

module ft04

using FenicsPy

T = 2.0            # final time
num_steps = 50     # number of time steps
Δt = T / num_steps # time step size

# Create mesh and define function space
nx = ny = 30
mesh = RectangleMesh(Point(-2, -2), Point(2, 2), nx, ny)
V = FunctionSpace(mesh, "P", 1)

# Define boundary condition
bc = DirichletBC(V, Constant(0), "on_boundary")

# Define initial value
u_0 = Expression("exp(-a*pow(x[0], 2) - a*pow(x[1], 2))",
                 degree=2, a=5)
u_n = interpolate(u_0, V)

# Define variational problem
u = TrialFunction(V)
v = TestFunction(V)
f = Constant(0)

F = u*v*dx + Δt*dot(grad(u), grad(v))*dx - (u_n + Δt*f)*v*dx
a, L = lhs(F), rhs(F)

# Create VTK file for saving solution
vtkfile = File("heat_gaussian/solution.pvd")

# Time-stepping
u = FeFunction(V)
t = 0
for n = 1:num_steps

    # Update current time
    global t += Δt

    # Compute solution
    solve(a == L, u, bc)

    # Save to file and plot solution
    vtkfile << (u, t)
    #plot(u)

    # Update previous solution
    u_n.assign(u)
end

end # module ft04


text:
using Plots
using LaTeXStrings
using CategoricalArrays
using GLM
using Distributions

using SigmaRidgeRegression
using LinearAlgebra
using StatsBase
using Plots

using Random

tmp_X = whiten_covariates(X, Σ_chol)

cov(tmp_X)
estimate_var(DickerMoments(),X,Y; Σ = Σ_chol)

using ForwardDiff

σ = 5.0
#gr = GroupedFeatures(repeat([200],5))
Random.seed!(1)
σ = 5.0
grp = GroupedFeatures([30;30;30;30;30;30])
n = 400
p = grp.p

ρ = 0.7
Σ = [ρ^(abs(i-j)) for i=1:p,j=1:p]
Σ_chol = cholesky(Σ)
X = randn(n, p) * Σ_chol.UL
Xnew = randn(10000, p) * Σ_chol.UL

using Statistics
cov(X)
#X= randn(n, p) .+ randn(n)
αs = sqrt.(range(4.0,12.0,length=ngroups(grp)))#r#ange(2.0, 2.75, 3.5; length=3)#1.0:5.0
β = random_betas(grp, αs)
group_summary(grp, β, norm)
sum(abs2, β)
Y = X*β .+ σ .* randn(n)

tmp = BasicGroupRidgeWorkspace(X=X, Y=Y, groups=grp)

λωλας_λ(tmp)

λs

σ_squared_max(mom)
using StatsBase

StatsBase.fit!(tmp, λωλας_λ(tmp))
mom = MomentTunerSetup(tmp)

tune_σ(1.0)
SigmaRidgeRegression.

min1 = opt_res.minimizer
lambda_min1 = get_λs(mom, min1)
min_val1 = opt_res.minimum
β1 = copy(tmp.β_curr)

function tune_λ(λ)
    fit!(tmp, λ)
end

lower_box_constraint = fill(0.0, 6)
upper_box_constraint = fill(Inf, 6)

opt_res2 = optimize(tune_λ,
                    lower_box_constraint, upper_box_constraint,
                    lambda_min1)
opt_res2.minimizer
opt_res2.minimizer
opt_res2.minimum
fit!(tmp, opt_res2.minimizer)
β2 = copy(tmp.β_curr)

mean(abs2, X*(β-β1))
mean(abs2, X*(β-β2))

opt_res3 = optimize(tune_λ,
                    lower_box_constraint, upper_box_constraint,
                    fill(1.0,6))
opt_res3.minimizer
opt_res3.minimizer
#opt_res3.minimum

opt_res.minimizer

oracle_λ = σ^2 ./ αs.^2 .* 30 ./ n

using Optim

using Plots
scatter( αs.^2, SigmaRidgeRegression.get_αs_squared(mom,1.0))
plot!(αs.^2,αs.^2)
σs_squared = range(0.01, 3.0; length=100)
mypath1 = sigma_squared_path(tmp, mom, σs_squared)
plot(σs_squared, mypath1.loos)

using Plots
plot(σs_squared, mypath1.λs)

λs = vcat([get_λs(mom, s)' for s in σs_squared]...)
pl = plot(σs_squared, λs)

σs_squared = range(0.01, 50.0; length=100)
mypath = sigma_squared_path(tmp, mom, σs_squared)
plot(σs_squared, mypath.loos)

four_cols_rep = hcat([fill(col, 1, 30) for col in   ["#440154"; "#31688E"; "#35B779"]]...)
linetype_rep = hcat([fill(col, 1, 25) for col in [:dash,:dot,:dashdot, :solid]]...)

[:black,"#9818d6","#ff5151"]
#66c2a5
#fc8d62
#8da0cb
#e78ac3
four_cols_rep = hcat([fill(col, 1, 30) for col in   [:black; :purple; :green]]...)

plot(σs_squared, mypath.βs, alpha=0.8, linewidth=1.0,label="", color=four_cols_rep, ylim=(-2,2))
using Plots
using PlotThemes
theme(:default)
opt_λ_empirical = σ^2/norm(β)^2*γ
opt_λ = σ^2/20.0*p/n

p/n

max_σ_squared(tmp)
fit!(tmp, 0.050)

mom = MomentTunerSetup(tmp)
mom.M_squared

my
find_λs_squared(mom, 0.2)

find_αs_squared(mom, 1.0)

using NonNegLeastSquares

using Plots
using LaTeXStrings
pgfplotsx()
, ylab=L"\hat{\lambda}(\sigmacv)", xlab=L"\sigmacv", size=(300,200));
pl = plot(σs_squared, get_α,  size=(500,400))

savefig(pl, "pl2.tex")

mom.N_norms_squared
find_αs(mom, 2.0)

using NonNegLeastSquares

find_αs(mom, 20.0)

using RandomMatrices

myrot = rand(GaussianHermite{1},n,1)

n_test = 20_000
n = 10_000
p = 1_000
σ = 1.0

γ = p/n
X = randn(n, p) .+ randn(n) #strong positive correlations.

Z = randn(p,p)
Z_qr_Q = Matrix(qr(Z).Q)

my_eigs = [fill(5, 500);fill(1, 500)]
Σ = Z_qr_Q * Diagonal(my_eigs) * Z_qr_Q'

X = real.(Matrix((sqrt(Σ)*randn(p,n))'))

X_qr.Q'*X_qr.Q

Y_test = X_test*β .+ σ .* randn(n_test)

1.41
tmp.XtXpΛ

size(tmp.X)

size(tmp.XtXpΛ_div_Xt)
size(tmp.Y)

StatsBase.fit!(tmp, 2.0)

diag(tmp.X*inv(tmp.XtX + Diagonal(group_expand(tmp.groups, tmp.λs)))tmp.X')

tmp.leverage_store

hat_matrix = tmp.X*inv(tmp.XtX + Diagonal(group_expand(tmp.groups, tmp.λs)))tmp.X'./n
hat_matrix*tmp.Y ≈ tmp.X * tmp.β_curr

diag(hat_matrix) ≈ tmp.leverage_store
mean(diag(hat_matrix))
mean(tmp.leverage_store)

using ForwardDiff
using Zygote

Zygote.gradient(λ->fit!(tmp, λ), fill(1.0,5))

ForwardDiff.gradient(λ->fit!(tmp, λ), fill(1.0,5))

ForwardDiff.Hess

loo_error(tmp)

mse_ridge(tmp, X_test, Y_test)

λs = range(0.00, 3.0; length=50)

mses_hat = zeros(length(λs))
loos_hat = zeros(length(λs))
for (i, λ) in enumerate(λs)
    fit!(tmp, λ)
    mses_hat[i] = mse_ridge(tmp, X_test, Y_test)
    loos_hat[i] = loo_error(tmp)
end

using Plots
using LaTeXStrings

plot(λs, [mses_hat loos_hat], color=["black" "blue"], linestyle=[:solid :dot],
                    label=["MSE" "LOO"], xlabel=L"\lambda")

plot(λs, mses_hat .- loos_hata)

fits = [solve_ridge(XtX, XtY, X, Y, λ) for λ in λs]
mses_hat = [mse_ridge(X_test, Y_test, fit[:β_hat]) for fit in fits]
loos_hat = [fit[:LOO_error] for fit in fits]

using Plots
using LaTeXStrings

vline!([opt_λ_empirical opt_λ], color=[:green :red])

true_error =

tmp2 = fit!(tmp., 1.0:5.0)
tmp2.XtXpΛ_chol\(tmp.XtX + Diagonal(group_expand(tmp.groups, 1.0:5.0))) ≈ I
(tmp.XtX + Diagonal(group_expand(tmp.groups, 1.0:5.0)))\tmp.XtY ≈ tmp.β_curr

function BasicGroupRidgeWorkspace(X, Y, groups)

end
mychol = cholesky(XtX)

vs = XtX
ldiv!(XtX, mychol, I)

cholesky(XtX)
isa(vs, AbstractMatrix)

#function rand()

#n_test = 10_000

β = randn(p) .* sqrt(α^2/p)
norm(β)^2

XtY = X'*Y./n
function solve_ridge(XtX::Symmetric, XtY, X, Y, λ; compute_M_matrix=false)
    n, p = size(X)
    chol_trans_inv = inv(cholesky(XtX + λ*I(p)))

    β_hat = chol_trans_inv*XtY

    hat_matrix = X*chol_trans_inv*X' ./ n

    Y_hat = X*β_hat

    LOO_error = norm( (Y .- Y_hat)./ ( 1.0 .- diag(hat_matrix)))^2 / n

    res= Dict(:β_hat => β_hat, :LOO_error => LOO_error, :λ => λ)

    if compute_M_matrix
        M_matrix = chol_trans_inv * XtX
        N_matrix = chol_trans_inv * X'./n

        res[:M_matrix] = M_matrix
        res[:N_matrix] = N_matrix

    end
    res
end

P_mat = ridge_sol[:N_matrix]

sol_matrix
sol_rhs
β_hat_norms

α_squared_hat = sol_matrix\sol_rhs

matrix_sol =

# want a fun:

# FeatureGroups

# repeat(..., FeatureGroups)

# + iterator protocol for groups.
# groupwise(Groups(), \beta::Vector, )
# groupwise(Groups(), \beta::Matrix, )
# groupwise(Groups(), \beta::Matrix, )

a = reshape(Vector(1:16), (4,4))
@which reduce(max, a, dims=1)

Σ = [ρ^(abs(i-j)) for i=1:p,j=1:p]

myinv = inv(Σ_chol.UL)

myinv*Σ*myinv'

X = randn(n, p) * Σ_chol.L

woodbury_playi

using WoodburyMatrices

A, B, D
bla = copy(tmp.λs)
bla[6] = Inf
A_tmp = Diagonal(group_expand(tmp.groups, bla))
wd = SymWoodbury(A_tmp, X', I(n)/n)
wd.Dp
wd.B

wd.

Dp = inv(n*I + wd.B'*(A_tmp\wd.B))

wd.Dp ≈ Dp

≈ Dp
Dp = safeinv(safeinv(D) .+ B'*(A\B))

?Woodbury

Random.seed!(100)
σ = 4.0
grp = GroupedFeatures([300;3000;5000])
n = 400
p = grp.p

X = randn(n, p)# * Σ_chol.UL

αs = sqrt.([4.0;8.0;12.0])#r#ange(2.0, 2.75, 3.5; length=3)#1.0:5.0
β = random_betas(grp, αs)
group_summary(grp, β, norm)
sum(abs2, β)
Y = X*β .+ σ .* randn(n)

tmp = BasicGroupRidgeWorkspace(X=X, Y=Y, groups=grp,
                              XtXpΛ_chol = WoodburyRidgePredictor(X))
fit!(tmp, λωλας_λ(tmp))

mom = MomentTunerSetup(tmp)
#scatter( αs.^2, SigmaRidgeRegression.get_αs_squared(mom,1.0))
#plot!(αs.^2,αs.^2)
σs_squared1 = range(0.0001, 34; length=30)
mypath1 = sigma_squared_path(tmp, mom, σs_squared1)

#with gr
plot(sqrt.(σs_squared1), mypath1.loos)

get_λs(mom, 4)


text:
# WARNING: This file was generated from bed-parser.rl using ragel. Do not edit!
const bedparser_start  = 41
const bedparser_first_final  = 41
const bedparser_error  = 0
const bedparser_en_main  = 41
const _bedparser_nfa_targs = Int8[ 0, 0 ,  ]
const _bedparser_nfa_offsets = Int8[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,  ]
const _bedparser_nfa_push_actions = Int8[ 0, 0 ,  ]
const _bedparser_nfa_pop_trans = Int8[ 0, 0 ,  ]
Ragel.@generate_read!_function(
"bedparser",
BEDReader,
BEDInterval,
begin
begin
if ( p == pe  )
	@goto _test_eof

end
if ( cs  == 41 )
	@goto st_case_41
elseif ( cs  == 0 )
	@goto st_case_0
elseif ( cs  == 1 )
	@goto st_case_1
elseif ( cs  == 2 )
	@goto st_case_2
elseif ( cs  == 3 )
	@goto st_case_3
elseif ( cs  == 4 )
	@goto st_case_4
elseif ( cs  == 5 )
	@goto st_case_5
elseif ( cs  == 6 )
	@goto st_case_6
elseif ( cs  == 7 )
	@goto st_case_7
elseif ( cs  == 8 )
	@goto st_case_8
elseif ( cs  == 9 )
	@goto st_case_9
elseif ( cs  == 10 )
	@goto st_case_10
elseif ( cs  == 11 )
	@goto st_case_11
elseif ( cs  == 12 )
	@goto st_case_12
elseif ( cs  == 13 )
	@goto st_case_13
elseif ( cs  == 14 )
	@goto st_case_14
elseif ( cs  == 15 )
	@goto st_case_15
elseif ( cs  == 16 )
	@goto st_case_16
elseif ( cs  == 17 )
	@goto st_case_17
elseif ( cs  == 18 )
	@goto st_case_18
elseif ( cs  == 19 )
	@goto st_case_19
elseif ( cs  == 20 )
	@goto st_case_20
elseif ( cs  == 21 )
	@goto st_case_21
elseif ( cs  == 22 )
	@goto st_case_22
elseif ( cs  == 23 )
	@goto st_case_23
elseif ( cs  == 24 )
	@goto st_case_24
elseif ( cs  == 25 )
	@goto st_case_25
elseif ( cs  == 26 )
	@goto st_case_26
elseif ( cs  == 27 )
	@goto st_case_27
elseif ( cs  == 28 )
	@goto st_case_28
elseif ( cs  == 29 )
	@goto st_case_29
elseif ( cs  == 30 )
	@goto st_case_30
elseif ( cs  == 42 )
	@goto st_case_42
elseif ( cs  == 31 )
	@goto st_case_31
elseif ( cs  == 32 )
	@goto st_case_32
elseif ( cs  == 33 )
	@goto st_case_33
elseif ( cs  == 34 )
	@goto st_case_34
elseif ( cs  == 35 )
	@goto st_case_35
elseif ( cs  == 36 )
	@goto st_case_36
elseif ( cs  == 37 )
	@goto st_case_37
elseif ( cs  == 38 )
	@goto st_case_38
elseif ( cs  == 39 )
	@goto st_case_39
elseif ( cs  == 40 )
	@goto st_case_40
end
@goto st_out
@label ctr2
begin
input.state.linenum += 1
end
@goto st41
@label st41
p+= 1;
if 	( p == pe  )
	@goto _test_eof41

end
@label st_case_41
if ( (data[1+(p )]) == 9 )
	begin
	@goto ctr85

end
elseif 	( (data[1+(p )]) == 10 )
	begin
	@goto ctr2

end
elseif 	( (data[1+(p )]) == 11 )
	begin
	@goto st2

end
elseif 	( (data[1+(p )]) == 13 )
	begin
	@goto st3

end
elseif 	( (data[1+(p )]) == 32 )
	begin
	@goto ctr86

end
end
if 	( 33 <= (data[1+(p )])&& (data[1+(p )])<= 126  )
	begin
	@goto ctr87

end

end
begin
	@goto st0

end
@label st_case_0
@label st0
cs = 0;
@goto _out
@label ctr83
begin
output.metadata.used_fields = 0; Ragel.@copy_from_anchor!(output.seqname)
end
@goto st1
@label ctr85
begin
Ragel.@anchor!
end
begin
output.metadata.used_fields = 0; Ragel.@copy_from_anchor!(output.seqname)
end
@goto st1
@label st1
p+= 1;
if ( p == pe  )
@goto _test_eof1

end
@label st_case_1
if ( (data[1+(p )]) == 10 )
begin
@goto ctr2

end
elseif ( (data[1+(p )]) == 13 )
begin
@goto st3

end
elseif ( (data[1+(p )]) == 32 )
begin
@goto st2

end
end
if ( (data[1+(p )])> 11  )
begin
if ( 48 <= (data[1+(p )])&& (data[1+(p )])<= 57  )
begin
@goto ctr4

end

end

end

elseif ( (data[1+(p )])>= 9  )
begin
@goto st2

end

end
begin
@goto st0

end
@label st2
p+= 1;
if ( p == pe  )
@goto _test_eof2

end
@label st_case_2
if ( (data[1+(p )]) == 10 )
begin
@goto ctr2

end
elseif ( (data[1+(p )]) == 13 )
begin
@goto st3

end
elseif ( (data[1+(p )]) == 32 )
begin
@goto st2

end
end
if ( 9 <= (data[1+(p )])&& (data[1+(p )])<= 11  )
begin
@goto st2

end

end
begin
@goto st0

end
@label st3
p+= 1;
if ( p == pe  )
@goto _test_eof3

end
@label st_case_3
if ( (data[1+(p )])== 10  )
begin
@goto ctr2

end

end
begin
@goto st0

end
@label ctr4
begin
Ragel.@anchor!
end
@goto st4
@label st4
p+= 1;
if ( p == pe  )
@goto _test_eof4

end
@label st_case_4
if ( (data[1+(p )])== 9  )
begin
@goto ctr5

end

end
if ( 48 <= (data[1+(p )])&& (data[1+(p )])<= 57  )
begin
@goto st4

end

end
begin
@goto st0

end
@label ctr5
begin
output.first = 1 + Ragel.@int64_from_anchor!
end
@goto st5
@label st5
p+= 1;
if ( p == pe  )
@goto _test_eof5

end
@label st_case_5
if ( 48 <= (data[1+(p )])&& (data[1+(p )])<= 57  )
begin
@goto ctr7

end

end
begin
@goto st0

end
@label ctr7
begin
Ragel.@anchor!
end
@goto st6
@label st6
p+= 1;
if ( p == pe  )
@goto _test_eof6

end
@label st_case_6
if ( (data[1+(p )]) == 9 )
begin
@goto ctr8

end
elseif ( (data[1+(p )]) == 10 )
begin
@goto ctr9

end
elseif ( (data[1+(p )]) == 13 )
begin
@goto ctr10

end
end
if ( 48 <= (data[1+(p )])&& (data[1+(p )])<= 57  )
begin
@goto st6

end

end
begin
@goto st0

end
@label ctr8
begin
output.last = Ragel.@int64_from_anchor!
end
@goto st7
@label st7
p+= 1;
if ( p == pe  )
@goto _test_eof7

end
@label st_case_7
if ( (data[1+(p )]) == 9 )
begin
@goto ctr12

end
elseif ( (data[1+(p )]) == 10 )
begin
@goto ctr13

end
elseif ( (data[1+(p )]) == 13 )
begin
@goto ctr14

end
end
if ( 32 <= (data[1+(p )])&& (data[1+(p )])<= 126  )
begin
@goto ctr15

end

end
begin
@goto st0

end
@label ctr12
begin
Ragel.@anchor!
end
begin
Ragel.@copy_from_anchor!(output.metadata.name)
end
begin
output.metadata.used_fields += 1
end
@goto st8
@label ctr79
begin
Ragel.@copy_from_anchor!(output.metadata.name)
end
begin
output.metadata.used_fields += 1
end
@goto st8
@label st8
p+= 1;
if ( p == pe  )
@goto _test_eof8

end
@label st_case_8
if ( 48 <= (data[1+(p )])&& (data[1+(p )])<= 57  )
begin
@goto ctr16

end

end
begin
@goto st0

end
@label ctr16
begin
Ragel.@anchor!
end
@goto st9
@label st9
p+= 1;
if ( p == pe  )
@goto _test_eof9

end
@label st_case_9
if ( (data[1+(p )]) == 9 )
begin
@goto ctr17

end
elseif ( (data[1+(p )]) == 10 )
begin
@goto ctr18

end
elseif ( (data[1+(p )]) == 13 )
begin
@goto ctr19

end
end
if ( 48 <= (data[1+(p )])&& (data[1+(p )])<= 57  )
begin
@goto st9

end

end
begin
@goto st0

end
@label ctr17
begin
output.metadata.score = Ragel.@int64_from_anchor!
end
begin
output.metadata.used_fields += 1
end
@goto st10
@label st10
p+= 1;
if ( p == pe  )
@goto _test_eof10

end
@label st_case_10
if ( (data[1+(p )]) == 43 )
begin
@goto ctr21

end
elseif ( (data[1+(p )]) == 63 )
begin
@goto ctr21

end
end
if ( 45 <= (data[1+(p )])&& (data[1+(p )])<= 46  )
begin
@goto ctr21

end

end
begin
@goto st0

end
@label ctr21
begin
output.strand = convert(Strand, (Ragel.@char))
end
@goto st11
@label st11
p+= 1;
if ( p == pe  )
@goto _test_eof11

end
@label st_case_11
if ( (data[1+(p )]) == 9 )
begin
@goto ctr22

end
elseif ( (data[1+(p )]) == 10 )
begin
@goto ctr23

end
elseif ( (data[1+(p )]) == 13 )
begin
@goto ctr24

end
end
begin
@goto st0

end
@label ctr22
begin
output.metadata.used_fields += 1
end
@goto st12
@label st12
p+= 1;
if ( p == pe  )
@goto _test_eof12

end
@label st_case_12
if ( 48 <= (data[1+(p )])&& (data[1+(p )])<= 57  )
begin
@goto ctr25

end

end
begin
@goto st0

end
@label ctr25
begin
Ragel.@anchor!
end
@goto st13
@label st13
p+= 1;
if ( p == pe  )
@goto _test_eof13

end
@label st_case_13
if ( (data[1+(p )]) == 9 )
begin
@goto ctr26

end
elseif ( (data[1+(p )]) == 10 )
begin
@goto ctr27

end
elseif ( (data[1+(p )]) == 13 )
begin
@goto ctr28

end
end
if ( 48 <= (data[1+(p )])&& (data[1+(p )])<= 57  )
begin
@goto st13

end

end
begin
@goto st0

end
@label ctr26
begin
output.metadata.thick_first = 1 + Ragel.@int64_from_anchor!
end
begin
output.metadata.used_fields += 1
end
@goto st14
@label st14
p+= 1;
if ( p == pe  )
@goto _test_eof14

end
@label st_case_14
if ( 48 <= (data[1+(p )])&& (data[1+(p )])<= 57  )
begin
@goto ctr30

end

end
begin
@goto st0

end
@label ctr30
begin
Ragel.@anchor!
end
@goto st15
@label st15
p+= 1;
if ( p == pe  )
@goto _test_eof15

end
@label st_case_15
if ( (data[1+(p )]) == 9 )
begin
@goto ctr31

end
elseif ( (data[1+(p )]) == 10 )
begin
@goto ctr32

end
elseif ( (data[1+(p )]) == 13 )
begin
@goto ctr33

end
end
if ( 48 <= (data[1+(p )])&& (data[1+(p )])<= 57  )
begin
@goto st15

end

end
begin
@goto st0

end
@label ctr31
begin
output.metadata.thick_last = Ragel.@int64_from_anchor!
end
begin
output.metadata.used_fields += 1
end
@goto st16
@label st16
p+= 1;
if ( p == pe  )
@goto _test_eof16

end
@label st_case_16
if ( 48 <= (data[1+(p )])&& (data[1+(p )])<= 57  )
begin
@goto ctr35

end

end
begin
@goto st0

end
@label ctr35
begin
Ragel.@anchor!
end
@goto st17
@label st17
p+= 1;
if ( p == pe  )
@goto _test_eof17

end
@label st_case_17
if ( (data[1+(p )]) == 9 )
begin
@goto ctr36

end
elseif ( (data[1+(p )]) == 10 )
begin
@goto ctr37

end
elseif ( (data[1+(p )]) == 11 )
begin
@goto ctr38

end
elseif ( (data[1+(p )]) == 13 )
begin
@goto ctr39

end
elseif ( (data[1+(p )]) == 32 )
begin
@goto ctr38

end
elseif ( (data[1+(p )]) == 44 )
begin
@goto ctr40

end
end
if ( 48 <= (data[1+(p )])&& (data[1+(p )])<= 57  )
begin
@goto st17

end

end
begin
@goto st0

end
@label ctr36
begin
input.red = input.green = input.blue = (Ragel.@int64_from_anchor!) / 255.0
end
begin
output.metadata.item_rgb = RGB{Float32}(input.red, input.green, input.blue)
end
begin
output.metadata.used_fields += 1
end
@goto st18
@label st18
p+= 1;
if ( p == pe  )
@goto _test_eof18

end
@label st_case_18
if ( (data[1+(p )]) == 9 )
begin
@goto st19

end
elseif ( (data[1+(p )]) == 11 )
begin
@goto st19

end
elseif ( (data[1+(p )]) == 32 )
begin
@goto st19

end
elseif ( (data[1+(p )]) == 44 )
begin
@goto st20

end
end
if ( 48 <= (data[1+(p )])&& (data[1+(p )])<= 57  )
begin
@goto ctr44

end

end
begin
@goto st0

end
@label ctr38
begin
input.red = input.green = input.blue = (Ragel.@int64_from_anchor!) / 255.0
end
@goto st19
@label st19
p+= 1;
if ( p == pe  )
@goto _test_eof19

end
@label st_case_19
if ( (data[1+(p )]) == 9 )
begin
@goto st19

end
elseif ( (data[1+(p )]) == 11 )
begin
@goto st19

end
elseif ( (data[1+(p )]) == 32 )
begin
@goto st19

end
elseif ( (data[1+(p )]) == 44 )
begin
@goto st20

end
end
begin
@goto st0

end
@label ctr40
begin
input.red = input.green = input.blue = (Ragel.@int64_from_anchor!) / 255.0
end
@goto st20
@label st20
p+= 1;
if ( p == pe  )
@goto _test_eof20

end
@label st_case_20
if ( (data[1+(p )]) == 9 )
begin
@goto st20

end
elseif ( (data[1+(p )]) == 11 )
begin
@goto st20

end
elseif ( (data[1+(p )]) == 32 )
begin
@goto st20

end
end
if ( 48 <= (data[1+(p )])&& (data[1+(p )])<= 57  )
begin
@goto ctr45

end

end
begin
@goto st0

end
@label ctr45
begin
Ragel.@anchor!
end
@goto st21
@label st21
p+= 1;
if ( p == pe  )
@goto _test_eof21

end
@label st_case_21
if ( (data[1+(p )]) == 9 )
begin
@goto ctr46

end
elseif ( (data[1+(p )]) == 11 )
begin
@goto ctr46

end
elseif ( (data[1+(p )]) == 32 )
begin
@goto ctr46

end
elseif ( (data[1+(p )]) == 44 )
begin
@goto ctr47

end
end
if ( 48 <= (data[1+(p )])&& (data[1+(p )])<= 57  )
begin
@goto st21

end

end
begin
@goto st0

end
@label ctr46
begin
input.green = (Ragel.@int64_from_anchor!) / 255.0
end
@goto st22
@label st22
p+= 1;
if ( p == pe  )
@goto _test_eof22

end
@label st_case_22
if ( (data[1+(p )]) == 9 )
begin
@goto st22

end
elseif ( (data[1+(p )]) == 11 )
begin
@goto st22

end
elseif ( (data[1+(p )]) == 32 )
begin
@goto st22

end
elseif ( (data[1+(p )]) == 44 )
begin
@goto st23

end
end
begin
@goto st0

end
@label ctr47
begin
input.green = (Ragel.@int64_from_anchor!) / 255.0
end
@goto st23
@label st23
p+= 1;
if ( p == pe  )
@goto _test_eof23

end
@label st_case_23
if ( (data[1+(p )]) == 9 )
begin
@goto st23

end
elseif ( (data[1+(p )]) == 11 )
begin
@goto st23

end
elseif ( (data[1+(p )]) == 32 )
begin
@goto st23

end
end
if ( 48 <= (data[1+(p )])&& (data[1+(p )])<= 57  )
begin
@goto ctr51

end

end
begin
@goto st0

end
@label ctr51
begin
Ragel.@anchor!
end
@goto st24
@label st24
p+= 1;
if ( p == pe  )
@goto _test_eof24

end
@label st_case_24
if ( (data[1+(p )]) == 9 )
begin
@goto ctr52

end
elseif ( (data[1+(p )]) == 10 )
begin
@goto ctr53

end
elseif ( (data[1+(p )]) == 13 )
begin
@goto ctr54

end
end
if ( 48 <= (data[1+(p )])&& (data[1+(p )])<= 57  )
begin
@goto st24

end

end
begin
@goto st0

end
@label ctr52
begin
input.blue = (Ragel.@int64_from_anchor!) / 255.0
end
begin
output.metadata.item_rgb = RGB{Float32}(input.red, input.green, input.blue)
end
begin
output.metadata.used_fields += 1
end
@goto st25
@label st25
p+= 1;
if ( p == pe  )
@goto _test_eof25

end
@label st_case_25
if ( 48 <= (data[1+(p )])&& (data[1+(p )])<= 57  )
begin
@goto ctr44

end

end
begin
@goto st0

end
@label ctr44
begin
Ragel.@anchor!
end
@goto st26
@label st26
p+= 1;
if ( p == pe  )
@goto _test_eof26

end
@label st_case_26
if ( (data[1+(p )]) == 9 )
begin
@goto ctr56

end
elseif ( (data[1+(p )]) == 10 )
begin
@goto ctr57

end
elseif ( (data[1+(p )]) == 13 )
begin
@goto ctr58

end
end
if ( 48 <= (data[1+(p )])&& (data[1+(p )])<= 57  )
begin
@goto st26

end

end
begin
@goto st0

end
@label ctr56
begin
output.metadata.block_count = Ragel.@int64_from_anchor!

if (output.metadata.block_count > length(output.metadata.block_sizes))
resize!(output.metadata.block_sizes, output.metadata.block_count)
end

if (output.metadata.block_count > length(output.metadata.block_firsts))
resize!(output.metadata.block_firsts, output.metadata.block_count)
end
end
begin
output.metadata.used_fields += 1
end
@goto st27
@label st27
p+= 1;
if ( p == pe  )
@goto _test_eof27

end
@label st_case_27
if ( 48 <= (data[1+(p )])&& (data[1+(p )])<= 57  )
begin
@goto ctr60

end

end
begin
@goto st0

end
@label ctr60
begin
Ragel.@anchor!
end
@goto st28
@label st28
p+= 1;
if ( p == pe  )
@goto _test_eof28

end
@label st_case_28
if ( (data[1+(p )]) == 9 )
begin
@goto ctr61

end
elseif ( (data[1+(p )]) == 10 )
begin
@goto ctr62

end
elseif ( (data[1+(p )]) == 13 )
begin
@goto ctr63

end
elseif ( (data[1+(p )]) == 44 )
begin
@goto ctr64

end
end
if ( 48 <= (data[1+(p )])&& (data[1+(p )])<= 57  )
begin
@goto st28

end

end
begin
@goto st0

end
@label ctr78
begin
output.metadata.used_fields += 1
end
@goto st29
@label ctr61
begin
if input.block_size_idx > length(output.metadata.block_sizes)
error("More size blocks encountered than BED block count field suggested.")
end
output.metadata.block_sizes[input.block_size_idx] = Ragel.@int64_from_anchor!
input.block_size_idx += 1
end
begin
output.metadata.used_fields += 1
end
@goto st29
@label st29
p+= 1;
if ( p == pe  )
@goto _test_eof29

end
@label st_case_29
if ( 48 <= (data[1+(p )])&& (data[1+(p )])<= 57  )
begin
@goto ctr66

end

end
begin
@goto st0

end
@label ctr66
begin
Ragel.@anchor!
end
@goto st30
@label st30
p+= 1;
if ( p == pe  )
@goto _test_eof30

end
@label st_case_30
if ( (data[1+(p )]) == 10 )
begin
@goto ctr67

end
elseif ( (data[1+(p )]) == 13 )
begin
@goto ctr68

end
elseif ( (data[1+(p )]) == 44 )
begin
@goto ctr69

end
end
if ( 48 <= (data[1+(p )])&& (data[1+(p )])<= 57  )
begin
@goto st30

end

end
begin
@goto st0

end
@label ctr72
begin
input.state.linenum += 1
end
@goto st42
@label ctr9
begin
output.last = Ragel.@int64_from_anchor!
end
begin
input.state.linenum += 1
end
@goto st42
@label ctr13
begin
Ragel.@anchor!
end
begin
Ragel.@copy_from_anchor!(output.metadata.name)
end
begin
output.metadata.used_fields += 1
end
begin
input.state.linenum += 1
end
@goto st42
@label ctr18
begin
output.metadata.score = Ragel.@int64_from_anchor!
end
begin
output.metadata.used_fields += 1
end
begin
input.state.linenum += 1
end
@goto st42
@label ctr23
begin
output.metadata.used_fields += 1
end
begin
input.state.linenum += 1
end
@goto st42
@label ctr27
begin
output.metadata.thick_first = 1 + Ragel.@int64_from_anchor!
end
begin
output.metadata.used_fields += 1
end
begin
input.state.linenum += 1
end
@goto st42
@label ctr32
begin
output.metadata.thick_last = Ragel.@int64_from_anchor!
end
begin
output.metadata.used_fields += 1
end
begin
input.state.linenum += 1
end
@goto st42
@label ctr37
begin
input.red = input.green = input.blue = (Ragel.@int64_from_anchor!) / 255.0
end
begin
output.metadata.item_rgb = RGB{Float32}(input.red, input.green, input.blue)
end
begin
output.metadata.used_fields += 1
end
begin
input.state.linenum += 1
end
@goto st42
@label ctr53
begin
input.blue = (Ragel.@int64_from_anchor!) / 255.0
end
begin
output.metadata.item_rgb = RGB{Float32}(input.red, input.green, input.blue)
end
begin
output.metadata.used_fields += 1
end
begin
input.state.linenum += 1
end
@goto st42
@label ctr57
begin
output.metadata.block_count = Ragel.@int64_from_anchor!

if (output.metadata.block_count > length(output.metadata.block_sizes))
resize!(output.metadata.block_sizes, output.metadata.block_count)
end

if (output.metadata.block_count > length(output.metadata.block_firsts))
resize!(output.metadata.block_firsts, output.metadata.block_count)
end
end
begin
output.metadata.used_fields += 1
end
begin
input.state.linenum += 1
end
@goto st42
@label ctr62
begin
if input.block_size_idx > length(output.metadata.block_sizes)
error("More size blocks encountered than BED block count field suggested.")
end
output.metadata.block_sizes[input.block_size_idx] = Ragel.@int64_from_anchor!
input.block_size_idx += 1
end
begin
output.metadata.used_fields += 1
end
begin
input.state.linenum += 1
end
@goto st42
@label ctr67
begin
if input.block_first_idx > length(output.metadata.block_firsts)
error("More start blocks encountered than BED block count field suggested.")
end
output.metadata.block_firsts[input.block_first_idx] = 1 + Ragel.@int64_from_anchor!
input.block_first_idx += 1
end
begin
output.metadata.used_fields += 1
end
begin
input.state.linenum += 1
end
@goto st42
@label ctr80
begin
Ragel.@copy_from_anchor!(output.metadata.name)
end
begin
output.metadata.used_fields += 1
end
begin
input.state.linenum += 1
end
@goto st42
@label st42
p+= 1;
if ( p == pe  )
@goto _test_eof42

end
@label st_case_42
if ( (data[1+(p )]) == 9 )
begin
@goto ctr88

end
elseif ( (data[1+(p )]) == 10 )
begin
@goto ctr72

end
elseif ( (data[1+(p )]) == 11 )
begin
@goto st32

end
elseif ( (data[1+(p )]) == 13 )
begin
@goto st33

end
elseif ( (data[1+(p )]) == 32 )
begin
@goto ctr89

end
end
if ( 33 <= (data[1+(p )])&& (data[1+(p )])<= 126  )
begin
@goto ctr90

end

end
begin
@goto st0

end
@label ctr74
begin
output.metadata.used_fields = 0; Ragel.@copy_from_anchor!(output.seqname)
end
@goto st31
@label ctr88
begin
input.block_size_idx = 1
input.block_first_idx = 1
Ragel.@anchor!
Ragel.@yield 31
end
begin
Ragel.@anchor!
end
begin
output.metadata.used_fields = 0; Ragel.@copy_from_anchor!(output.seqname)
end
@goto st31
@label st31
p+= 1;
if ( p == pe  )
@goto _test_eof31

end
@label st_case_31
if ( (data[1+(p )]) == 10 )
begin
@goto ctr72

end
elseif ( (data[1+(p )]) == 13 )
begin
@goto st33

end
elseif ( (data[1+(p )]) == 32 )
begin
@goto st32

end
end
if ( (data[1+(p )])> 11  )
begin
if ( 48 <= (data[1+(p )])&& (data[1+(p )])<= 57  )
begin
@goto ctr4

end

end

end

elseif ( (data[1+(p )])>= 9  )
begin
@goto st32

end

end
begin
@goto st0

end
@label st32
p+= 1;
if ( p == pe  )
@goto _test_eof32

end
@label st_case_32
if ( (data[1+(p )]) == 10 )
begin
@goto ctr72

end
elseif ( (data[1+(p )]) == 13 )
begin
@goto st33

end
elseif ( (data[1+(p )]) == 32 )
begin
@goto st32

end
end
if ( 9 <= (data[1+(p )])&& (data[1+(p )])<= 11  )
begin
@goto st32

end

end
begin
@goto st0

end
@label ctr10
begin
output.last = Ragel.@int64_from_anchor!
end
@goto st33
@label ctr14
begin
Ragel.@anchor!
end
begin
Ragel.@copy_from_anchor!(output.metadata.name)
end
begin
output.metadata.used_fields += 1
end
@goto st33
@label ctr19
begin
output.metadata.score = Ragel.@int64_from_anchor!
end
begin
output.metadata.used_fields += 1
end
@goto st33
@label ctr24
begin
output.metadata.used_fields += 1
end
@goto st33
@label ctr28
begin
output.metadata.thick_first = 1 + Ragel.@int64_from_anchor!
end
begin
output.metadata.used_fields += 1
end
@goto st33
@label ctr33
begin
output.metadata.thick_last = Ragel.@int64_from_anchor!
end
begin
output.metadata.used_fields += 1
end
@goto st33
@label ctr39
begin
input.red = input.green = input.blue = (Ragel.@int64_from_anchor!) / 255.0
end
begin
output.metadata.item_rgb = RGB{Float32}(input.red, input.green, input.blue)
end
begin
output.metadata.used_fields += 1
end
@goto st33
@label ctr54
begin
input.blue = (Ragel.@int64_from_anchor!) / 255.0
end
begin
output.metadata.item_rgb = RGB{Float32}(input.red, input.green, input.blue)
end
begin
output.metadata.used_fields += 1
end
@goto st33
@label ctr58
begin
output.metadata.block_count = Ragel.@int64_from_anchor!

if (output.metadata.block_count > length(output.metadata.block_sizes))
resize!(output.metadata.block_sizes, output.metadata.block_count)
end

if (output.metadata.block_count > length(output.metadata.block_firsts))
resize!(output.metadata.block_firsts, output.metadata.block_count)
end
end
begin
output.metadata.used_fields += 1
end
@goto st33
@label ctr63
begin
if input.block_size_idx > length(output.metadata.block_sizes)
error("More size blocks encountered than BED block count field suggested.")
end
output.metadata.block_sizes[input.block_size_idx] = Ragel.@int64_from_anchor!
input.block_size_idx += 1
end
begin
output.metadata.used_fields += 1
end
@goto st33
@label ctr68
begin
if input.block_first_idx > length(output.metadata.block_firsts)
error("More start blocks encountered than BED block count field suggested.")
end
output.metadata.block_firsts[input.block_first_idx] = 1 + Ragel.@int64_from_anchor!
input.block_first_idx += 1
end
begin
output.metadata.used_fields += 1
end
@goto st33
@label ctr81
begin
Ragel.@copy_from_anchor!(output.metadata.name)
end
begin
output.metadata.used_fields += 1
end
@goto st33
@label st33
p+= 1;
if ( p == pe  )
@goto _test_eof33

end
@label st_case_33
if ( (data[1+(p )])== 10  )
begin
@goto ctr72

end

end
begin
@goto st0

end
@label ctr89
begin
input.block_size_idx = 1
input.block_first_idx = 1
Ragel.@anchor!
Ragel.@yield 34
end
begin
Ragel.@anchor!
end
@goto st34
@label st34
p+= 1;
if ( p == pe  )
@goto _test_eof34

end
@label st_case_34
if ( (data[1+(p )]) == 9 )
begin
@goto ctr74

end
elseif ( (data[1+(p )]) == 10 )
begin
@goto ctr72

end
elseif ( (data[1+(p )]) == 11 )
begin
@goto st32

end
elseif ( (data[1+(p )]) == 13 )
begin
@goto st33

end
elseif ( (data[1+(p )]) == 32 )
begin
@goto st34

end
end
if ( 33 <= (data[1+(p )])&& (data[1+(p )])<= 126  )
begin
@goto st35

end

end
begin
@goto st0

end
@label ctr87
begin
Ragel.@anchor!
end
@goto st35
@label ctr90
begin
input.block_size_idx = 1
input.block_first_idx = 1
Ragel.@anchor!
Ragel.@yield 35
end
begin
Ragel.@anchor!
end
@goto st35
@label st35
p+= 1;
if ( p == pe  )
@goto _test_eof35

end
@label st_case_35
if ( (data[1+(p )])== 9  )
begin
@goto ctr77

end

end
if ( 32 <= (data[1+(p )])&& (data[1+(p )])<= 126  )
begin
@goto st35

end

end
begin
@goto st0

end
@label ctr77
begin
output.metadata.used_fields = 0; Ragel.@copy_from_anchor!(output.seqname)
end
@goto st36
@label st36
p+= 1;
if ( p == pe  )
@goto _test_eof36

end
@label st_case_36
if ( 48 <= (data[1+(p )])&& (data[1+(p )])<= 57  )
begin
@goto ctr4

end

end
begin
@goto st0

end
@label ctr69
begin
if input.block_first_idx > length(output.metadata.block_firsts)
error("More start blocks encountered than BED block count field suggested.")
end
output.metadata.block_firsts[input.block_first_idx] = 1 + Ragel.@int64_from_anchor!
input.block_first_idx += 1
end
@goto st37
@label st37
p+= 1;
if ( p == pe  )
@goto _test_eof37

end
@label st_case_37
if ( (data[1+(p )]) == 10 )
begin
@goto ctr23

end
elseif ( (data[1+(p )]) == 13 )
begin
@goto ctr24

end
end
if ( 48 <= (data[1+(p )])&& (data[1+(p )])<= 57  )
begin
@goto ctr66

end

end
begin
@goto st0

end
@label ctr64
begin
if input.block_size_idx > length(output.metadata.block_sizes)
error("More size blocks encountered than BED block count field suggested.")
end
output.metadata.block_sizes[input.block_size_idx] = Ragel.@int64_from_anchor!
input.block_size_idx += 1
end
@goto st38
@label st38
p+= 1;
if ( p == pe  )
@goto _test_eof38

end
@label st_case_38
if ( (data[1+(p )]) == 9 )
begin
@goto ctr78

end
elseif ( (data[1+(p )]) == 10 )
begin
@goto ctr23

end
elseif ( (data[1+(p )]) == 13 )
begin
@goto ctr24

end
end
if ( 48 <= (data[1+(p )])&& (data[1+(p )])<= 57  )
begin
@goto ctr60

end

end
begin
@goto st0

end
@label ctr15
begin
Ragel.@anchor!
end
@goto st39
@label st39
p+= 1;
if ( p == pe  )
@goto _test_eof39

end
@label st_case_39
if ( (data[1+(p )]) == 9 )
begin
@goto ctr79

end
elseif ( (data[1+(p )]) == 10 )
begin
@goto ctr80

end
elseif ( (data[1+(p )]) == 13 )
begin
@goto ctr81

end
end
if ( 32 <= (data[1+(p )])&& (data[1+(p )])<= 126  )
begin
@goto st39

end

end
begin
@goto st0

end
@label ctr86
begin
Ragel.@anchor!
end
@goto st40
@label st40
p+= 1;
if ( p == pe  )
@goto _test_eof40

end
@label st_case_40
if ( (data[1+(p )]) == 9 )
begin
@goto ctr83

end
elseif ( (data[1+(p )]) == 10 )
begin
@goto ctr2

end
elseif ( (data[1+(p )]) == 11 )
begin
@goto st2

end
elseif ( (data[1+(p )]) == 13 )
begin
@goto st3

end
elseif ( (data[1+(p )]) == 32 )
begin
@goto st40

end
end
if ( 33 <= (data[1+(p )])&& (data[1+(p )])<= 126  )
begin
@goto st35

end

end
begin
@goto st0

end
@label st_out
@label _test_eof41
cs = 41;
@goto _test_eof
@label _test_eof1
cs = 1;
@goto _test_eof
@label _test_eof2
cs = 2;
@goto _test_eof
@label _test_eof3
cs = 3;
@goto _test_eof
@label _test_eof4
cs = 4;
@goto _test_eof
@label _test_eof5
cs = 5;
@goto _test_eof
@label _test_eof6
cs = 6;
@goto _test_eof
@label _test_eof7
cs = 7;
@goto _test_eof
@label _test_eof8
cs = 8;
@goto _test_eof
@label _test_eof9
cs = 9;
@goto _test_eof
@label _test_eof10
cs = 10;
@goto _test_eof
@label _test_eof11
cs = 11;
@goto _test_eof
@label _test_eof12
cs = 12;
@goto _test_eof
@label _test_eof13
cs = 13;
@goto _test_eof
@label _test_eof14
cs = 14;
@goto _test_eof
@label _test_eof15
cs = 15;
@goto _test_eof
@label _test_eof16
cs = 16;
@goto _test_eof
@label _test_eof17
cs = 17;
@goto _test_eof
@label _test_eof18
cs = 18;
@goto _test_eof
@label _test_eof19
cs = 19;
@goto _test_eof
@label _test_eof20
cs = 20;
@goto _test_eof
@label _test_eof21
cs = 21;
@goto _test_eof
@label _test_eof22
cs = 22;
@goto _test_eof
@label _test_eof23
cs = 23;
@goto _test_eof
@label _test_eof24
cs = 24;
@goto _test_eof
@label _test_eof25
cs = 25;
@goto _test_eof
@label _test_eof26
cs = 26;
@goto _test_eof
@label _test_eof27
cs = 27;
@goto _test_eof
@label _test_eof28
cs = 28;
@goto _test_eof
@label _test_eof29
cs = 29;
@goto _test_eof
@label _test_eof30
cs = 30;
@goto _test_eof
@label _test_eof42
cs = 42;
@goto _test_eof
@label _test_eof31
cs = 31;
@goto _test_eof
@label _test_eof32
cs = 32;
@goto _test_eof
@label _test_eof33
cs = 33;
@goto _test_eof
@label _test_eof34
cs = 34;
@goto _test_eof
@label _test_eof35
cs = 35;
@goto _test_eof
@label _test_eof36
cs = 36;
@goto _test_eof
@label _test_eof37
cs = 37;
@goto _test_eof
@label _test_eof38
cs = 38;
@goto _test_eof
@label _test_eof39
cs = 39;
@goto _test_eof
@label _test_eof40
cs = 40;
@goto _test_eof
@label _test_eof
begin

end
if ( p == eof  )
begin
if ( cs  == 42 )
begin
input.block_size_idx = 1
input.block_first_idx = 1
Ragel.@anchor!
Ragel.@yield 0
end

break;
end

end

end
@label _out
begin

end

end
end)