text:
"""
Structures to keep information sorted; for 2D arrays
"""
mutable struct pri
    g::Array{Float64,2}     # approximation
    gInit::Array{Float64,2} # initial state
    # Energies
    Ep::Array{Float64,1}
    Em::Array{Float64,1}
    E::Array{Float64,1}
    # Additional/optional quantities for debugging etc
    p::Array{Float64,2}
    q::Array{Float64,2}
    d::Array{Float64,1}
    d2::Array{Float64,1}
    name::String
end

pri(gInit, nSteps, name="NoName") =
    pri(gInit, gInit,
        zeros(nSteps), zeros(nSteps), zeros(nSteps),
        gInit, gInit,
        zeros(nSteps), zeros(nSteps),
        name)

mutable struct lpri
    g::Array{Float64,2}     # approximation
    gInit::Array{Float64,2} # initial state
    # Energies
    Ep::Array{Float64,1}
    Em::Array{Float64,1}
    E::Array{Float64,1}
    # Additional/optional quantities for debugging etc
    p::Array{Float64,2}
    q::Array{Float64,2}
    go::Array{Float64,2}
    qo::Array{Float64,2}
    po::Array{Float64,2}
    d::Array{Float64,1}
    d2::Array{Float64,1}
    d3::Array{Float64,1}
    d4::Array{Float64,1}
    d5::Array{Float64,1}
    name::String
end

lpri(gInit, nSteps, name="NoName") =
    pri(gInit, gInit,
        zeros(nSteps), zeros(nSteps), zeros(nSteps),
        gInit, gInit, gInit, gInit, gInit,
        zeros(nSteps), zeros(nSteps), zeros(nSteps), zeros(nSteps), zeros(nSteps),
        name)

"""
    Structures to keep information sorted; for 1D arrays
"""
mutable struct pri1D
    g      # approximation
    gInit  # initial state
    # Energies
    Ep
    Em
    E
    # Additional/optional quantities for debugging etc
    p
    q
    d
    d2
    name::String
end

pri1D(gInit, nSteps, name="NoName") =
    pri(gInit, gInit,
        zeros(nSteps), zeros(nSteps), zeros(nSteps),
        gInit, gInit,
        zeros(nSteps), zeros(nSteps),
        name)

max_stars_repo_name: tsipenyuk/FPRS

max_issues_repo_name: tsipenyuk/FPRS

max_forks_repo_name: tsipenyuk/FPRS


text:
# Alignment Types
# ===============
#
# Types for sequence alignments.
#
# This file is a part of BioJulia.
# License is MIT: https://github.com/BioJulia/Bio.jl/blob/master/LICENSE.md

abstract AbstractAlignment

# Alignments
# ----------

"""Global-global alignment with end gap penalties."""
immutable GlobalAlignment <: AbstractAlignment end

"""Global-local alignment."""
immutable SemiGlobalAlignment <: AbstractAlignment end

"""Global-global alignment without end gap penalties."""
immutable OverlapAlignment <: AbstractAlignment end

"""Local-local alignment."""
immutable LocalAlignment <: AbstractAlignment end

# Distances
# ---------

"""Edit distance."""
immutable EditDistance <: AbstractAlignment end

"""
Levenshtein distance.

A special case of `EditDistance` with the costs of mismatch, insertion, and
deletion are 1.
"""
immutable LevenshteinDistance <: AbstractAlignment end

"""
Hamming distance.

A special case of `EditDistance` with the costs of insertion and deletion are
infinitely large.
"""
immutable HammingDistance <: AbstractAlignment end

ext: jl


text:
module IntegratedGradients

export gen_batch_data,
    accuracy,
    predict,
    truth,
    seq_classifier_loss,
	integrate_gradient,
    check_condition,
    check_at_zero,
    check_at_one,
    check_at_x,
    OneHotVector_f,
    onehot_f,
    UniformHotVector_f,
    uniformhot_f

using MultivariateTimeSeries
using Flux
using Flux: onehot, batchseq, crossentropy, OneHotVector
using Base.Iterators

"""
symbols are discrete symbols
"""
function gen_batch_data{T}(mts::MTS, labels::Vector{T}, alphabet, batchsize::Int=50;
                        b_normalize::Bool=true,
                        b_stop_token::Bool=true,
                        b_shuffle::Bool=true,
                        rng::AbstractRNG=Base.GLOBAL_RNG)

    mts = b_normalize ? normalize01(mts) : mts
    mts = b_stop_token ? append_stop_token(mts) : mts
    X = vec(mts)
    Y_ = [lab in alphabet ? onehot_f(lab, alphabet) : uniformhot_f(alphabet) for lab in labels]
    rp = collect(1:length(mts))
    if b_shuffle
        rp = randperm(rng, length(mts))
        X, Y_ = X[rp], Y_[rp]
    end
    Y = []
    for (x,y) in zip(X,Y_)
        n = length(x)-1
        ymat = [zero(y) for i=1:n]
        push!(ymat, y)
        push!(Y, ymat)
    end
    Xs = collect(partition(X, batchsize))
    Ys = collect(partition(Y, batchsize))
    Xs = [batchseq(x,zero(x[1][1])) for x in Xs]
    Ys = [batchseq(y,zero(y[1][1])) for y in Ys]

    Xs, Ys, rp
end

function accuracy(m, Xs, Ys)
    batchsize = size(Xs[1][1],2)
    s = 0
    for (X,Y) in zip(Xs,Ys)
        Flux.reset!(m)
        Flux.truncate!(m)
        s += count(Flux.argmax(m.(X)[end]) .== Flux.argmax(Y[end]))
    end
    s / (batchsize*length(Xs))
end

function predict(m, Xs, ind)
    Flux.reset!(m)
    Flux.truncate!(m)
	m.(Xs[ind])[end]
end
truth(Ys, ind) = Ys[ind][end]

function seq_classifier_loss(m)
    (X,Y) -> begin
        l = crossentropy(m.(X)[end],Y[end])
        Flux.truncate!(m)
        return l
    end
end

"""
See: Sundararajan, Taly, Yan, "Axiomatic attribution for deep networks"
Esp. equation 3.
Also see: github.com/ankurtaly/Attributions
"""
function integrate_gradient(m, X, target_index::Int, N::Int=100; skiplast::Bool=false)
    k = [i / N for i = 1:N] #assumes a zero baseline
    XP = [param(x * k') for x in X]
    Flux.reset!(m)
    Flux.truncate!(m)
    y = m.(XP)[end][target_index, :]
    Flux.back!(y, 1)
    A = hcat([x .* mean(xp.grad, 2) for (x,xp) in zip(X,XP)]...)
	return skiplast ? A[:, 1:(end-1)] : A
end

function check_condition(m, X, target_index::Int, N::Int=100; verbose=true)
    F0 = check_at_zero(m, X, target_index)
    F1 = check_at_x(m, X, target_index)

    A = integrate_gradient(m, X, target_index, N)
    err = abs(sum(A) - (F1-F0))
    verbose && println("Error is: $err")

    (err, sum(A), F1-F0)
end

function check_at_zero(m, X)
    XP0 = [zeros(x) for x in X]
    Flux.reset!(m)
    Flux.truncate!(m)
    y0 = m.(XP0)[end]
    y0
end
function check_at_zero(m, X, target_index::Int)
    y0 = check_at_zero(m, X)[target_index,:]
    F0 = y0[1].tracker.data
    F0
end
function check_at_one(m, X)
    XP0 = [ones(x) for x in X]
    Flux.reset!(m)
    Flux.truncate!(m)
    y0 = m.(XP0)[end]
    y0
end

function check_at_x(m, X)
    XP1 = [x for x in X]
    Flux.reset!(m)
    Flux.truncate!(m)
    y1 = m.(XP1)[end]
    y1
end
function check_at_x(m, X, target_index::Int)
    y1 = check_at_x(m, X)[target_index,:]
    F1 = y1[1].tracker.data
    F1
end

struct OneHotVector_f <: AbstractVector{Float64}
    o::OneHotVector
end
Base.size(xs::OneHotVector_f) = size(xs.o)
Base.getindex(xs::OneHotVector_f, i) = Float64(getindex(xs.o, i))

onehot_f(l, labels) = OneHotVector_f(onehot(l,labels))
onehot_f(l, labels, unk) = OneHotVector_f(onehot(l,labels,unk))

struct UniformHotVector_f <: AbstractVector{Float64}
    sz::Int
end
Base.size(xs::UniformHotVector_f) = (xs.sz,)
Base.getindex(xs::UniformHotVector_f, i::Integer) = 1.0/xs.sz

uniformhot_f(labels) = UniformHotVector_f(length(labels))

end # module


text:
using StatsBase
using Compat
using Images
using ImageView
using Colors
using FixedPointNumbers
using VoronoiDelaunay
using MultivariateStats
using MAT
using PiecewiseAffineTransforms

include("utils.jl")
include("model.jl")
include("procrustes.jl")
include("warps.jl")
include("gradient2d.jl")
include("train.jl")
include("fit.jl")
include("view.jl")


text:
using CategoricalArrays, DataFrames, LinearAlgebra, MixedModels, Random, RData, SparseArrays, Test

if !@isdefined(dat) || !isa(dat, Dict{Symbol, DataFrame})
    dat = Dict(Symbol(k) => v for (k, v) in load(joinpath(dirname(@__FILE__), "dat.rda")))
end

@testset "UBlk" begin
    ex22 = UniformBlockDiagonal(reshape(Vector(1.0:12.0), (2, 2, 3)))
    Lblk = UniformBlockDiagonal(fill(0., (2,2,3)))
    vf1 = VectorFactorReTerm(categorical(repeat(1:3, inner=4)),
                             vcat(ones(1,12), repeat([-1.0, 1.0], outer=6)'),
                             :G, ["(Intercept)", "U"], [2])
    vf2 = VectorFactorReTerm(categorical(repeat(['A','B'], outer=6)),
                             vcat(ones(1,12), repeat([-1.0, 0.0, 1.0], inner=2, outer=2)'),
                             :G, ["(Intercept)", "U"], [2])
    prd = vf2'vf1

    @testset "size" begin
        @test size(ex22) == (6, 6)
        @test size(ex22, 1) == 6
        @test size(ex22, 2) == 6
        @test size(ex22.data) == (2, 2, 3)
        @test length(ex22.facevec) == 3
        @test size(vf1) == (12, 6)
        @test size(vf2) == (12, 4)
        @test size(prd) == (4, 6)
        @test nnz(prd) == 24
    end

    @testset "elements" begin
        @test ex22[1, 1] == 1
        @test ex22[2, 1] == 2
        @test ex22[3, 1] == 0
        @test ex22[2, 2] == 4
        @test ex22[3, 3] == 5
        @test ex22[:, 3] == [0,0,5,6,0,0]
        @test ex22[5, 6] == 11
    end

    @testset "facevec" begin
        @test ex22.facevec[3] == reshape(9:12, (2,2))
    end

    @testset "scaleInflate" begin
        MixedModels.scaleInflate!(Lblk, ex22, vf1)
        @test Lblk.facevec[1] == [2. 3.; 2. 5.]
        setθ!(vf1, [1.,1.,1.])
        Λ = vf1.Λ
        MixedModels.scaleInflate!(Lblk, ex22, vf1)
        target = Λ'ex22.facevec[1]*Λ + I
        @test Lblk.facevec[1] == target
        @test MixedModels.scaleInflate!(Matrix(Lblk), ex22, vf1)[1:2, 1:2] == target
    end

    @testset "updateL" begin
        @test ones(2, 2) == MixedModels.rankUpdate!(Hermitian(zeros(2, 2)), ones(2))
        d3 = dat[:d3]
        modelmat = ones(2, size(d3, 1))
        copyto!(view(modelmat, 2, :), d3[:U])
        Vf1 = VectorFactorReTerm(d3[:G], modelmat, :G, ["(Intercept)", "U"], [2])
        Vf2 = VectorFactorReTerm(d3[:H], modelmat, :H, ["(Intercept)", "U"], [2])
        @test getΛ(Vf1) == LowerTriangular(Matrix(I, 2, 2))
        setθ!(Vf2, [1.75, 0.0, 1.0])
        A11 = Vf1'Vf1
        L11 = MixedModels.cholUnblocked!(MixedModels.scaleInflate!(UniformBlockDiagonal(fill(0., size(A11.data))), A11, Vf1), Val{:L})
        L21 = Vf2'Vf1
        A21cb1 = copy(L21.colblocks[1])
        lmul!(Λ(Vf2)', rmul!(L21, Λ(Vf1)))
        L21cb1 = copy(L21.colblocks[1])
        @test L21cb1 == Vf2.Λ * A21cb1 * Vf1.Λ
        rdiv!(L21, adjoint(LowerTriangular(L11)))
        @test L21.colblocks[1] == rdiv!(L21cb1, adjoint(LowerTriangular(L11.facevec[1])))
        A22 = Vf2'Vf2
        L22 = MixedModels.scaleInflate!(UniformBlockDiagonal(fill(0., size(A22.data))), A22, Vf2)
        for b in L21.rowblocks[1]
            BLAS.syr!('L', -1.0, b, L22.facevec[1])
        end
    end
end

@testset "RBlk" begin
    ex22 = RepeatedBlockDiagonal(reshape(Vector(1.0:4.0), (2, 2)), 5)
    vf1 = VectorFactorReTerm(categorical(repeat(1:3, inner=4)),
                             vcat(ones(1,12), repeat([-1.0, 1.0], outer=6)'),
                             :G, ["(Intercept)", "U"], [2])
    Λ1 = Λ(vf1)
    vf2 = VectorFactorReTerm(categorical(repeat(['A','B'], outer=6)),
                             vcat(ones(1,12), repeat([-1.0, 0.0, 1.0], inner=2, outer=2)'),
                             :G, ["(Intercept)", "U"], [2])
    Λ2 = Λ(vf2)

    @testset "size" begin
        @test size(ex22) == (10, 10)
        @test size(ex22, 1) == 10
        @test size(ex22, 2) == 10
        @test size(ex22.data) == (2, 2)
        @test ex22.nblocks == 5
        @test Λ1 == I
    end

    @testset "elements" begin
        @test ex22[1, 1] == 1
        @test ex22[2, 1] == 2
        @test ex22[3, 1] == 0
        @test ex22[2, 2] == 4
        @test ex22[3, 3] == 1
    end
end


text:
function write_data_to_filestore(base_repository_file_path::String, function_call::Symbol, asset_symbol::String, date_string::String, data_frame::DataFrame)::String

    # -
    # checks go here ...
    # -

    # build a path into the data repository -
    function_call_string = string(function_call)
    final_repo_path = "$(base_repository_file_path)/$(function_call_string)/$(asset_symbol)/$(date_string)"
    final_repo_path_with_file_name = "$(base_repository_file_path)/$(function_call_string)/$(asset_symbol)/$(date_string)/data.csv"

    # check - do we have the repo path directory structure?
    if (isdir(final_repo_path) == false)
        mkpath(final_repo_path)
    end

    # write file to disk -
    CSV.write(final_repo_path_with_file_name,data_frame)

    # return -
    return final_repo_path_with_file_name
end

function read_data_from_filestore(repository_file_path::String)::DataFrame

    # -
    # checks go here ...
    # -

    # read file from repo -
    return CSV.read(repository_file_path)
end


text:
"""
    rasterio!(dataset::AbstractDataset, buffer::Array{<:Real, 3}, bands::Vector{Cint}; <keyword arguments>)
    rasterio!(dataset::AbstractDataset, buffer::Array{<:Real, 3}, bands::Vector{Cint}, rows, cols; <keyword arguments>)
    rasterio!(rasterband::AbstractRasterBand, buffer::Matrix{<:Real}; <keyword arguments>)
    rasterio!(rasterband::AbstractRasterBand, buffer::Matrix{<:Real}, rows, cols; <keyword arguments>)

Read/write a region of image data from multiple bands.

This method allows reading a region of one or more `RasterBand`s from this
dataset into a buffer, or writing data from a buffer into a region of the
`RasterBand`s. It automatically takes care of data type translation if the
element type (`<:Real`) of the buffer is different than that of the
`GDALRasterBand`. The method also takes care of image decimation / replication
if the buffer size (`xsz × ysz`) is different than the size of the
region being accessed (`xsize × ysize`).

The `pxspace`, `linespace` and `bandspace` parameters allow reading into
or writing from various organization of buffers.

For highest performance full resolution data access, read and write on \"block
boundaries\" as returned by `blocksize()`, or use the `readblock!()` and
`writeblock!()` methods.

### Parameters
* `rows`        A continuous range of rows expressed as a `UnitRange{<:Integer}`,
                such as 2:9.
* `cols`        A continuous range of columns expressed as a `UnitRange{<:Integer}`,
                such as 2:9.
* `access`      Either `GDAL.GF_Read` to read a region of data, or
                `GDAL.GF_Write` to write a region of data.
* `xoffset`     The pixel offset to the top left corner of the region to be
                accessed. It will be `0` (default) to start from the left.
* `yoffset`     The line offset to the top left corner of the region to be
                accessed. It will be `0` (default) to start from the top.
* `xsize`       The width of the region of the band to be accessed in pixels.
* `ysize`       The height of the region of the band to be accessed in lines.
* `buffer`      The buffer into which the data should be read, or from which it
                should be written. It must contain `≥ xsz * ysz * <# of bands>`
                words of type `eltype(buffer)`. It is organized in left to
                right, top to bottom pixel order. Spacing is controlled by the
                `pxspace`, and `linespace` parameters
* `xsz`         The width of the buffer into which the desired region is
                to be read, or from which it is to be written.
* `ysz`         The height of the buffer into which the desired region is
                to be read, or from which it is to be written.
* `bands`       The list of bands (`1`-based) to be read/written.
* `pxspace`     The byte offset from the start of a pixel value in the `buffer`
                to the start of the next pixel value within a scanline. By
                default (i.e., `0`) the size of `eltype(buffer)` will be used.
* `linespace`   The byte offset from the start of one scanline in pBuffer to
                the start of the next. By default (i.e., `0`) the value of
                `sizeof(eltype(buffer)) * xsz` will be used.
* `bandspace`   The byte offset from the start of one bands data to the start
                of the next. By default (`0`), it will be `linespace * ysz`
                implying band sequential organization of the buffer.

### Returns
`CE_Failure` if the access fails, otherwise `CE_None`.
"""
function rasterio! end

function rasterio!(
        dataset::AbstractDataset,
        buffer::Array{<:Real, 3},
        bands::Vector{Cint},
        access::GDALRWFlag  = GDAL.GF_Read,
        pxspace::Integer    = 0,
        linespace::Integer  = 0,
        bandspace::Integer  = 0
    )
    rasterio!(dataset, buffer, bands, 0, 0, width(dataset), height(dataset),
        access, pxspace, linespace, bandspace)
    return buffer
end

function rasterio!(
        dataset::AbstractDataset,
        buffer::Array{<:Real, 3},
        bands::Vector{Cint},
        rows::UnitRange{<:Integer},
        cols::UnitRange{<:Integer},
        access::GDALRWFlag  = GDAL.GF_Read,
        pxspace::Integer    = 0,
        linespace::Integer  = 0,
        bandspace::Integer  = 0
    )
    xsize = cols[end] - cols[1] + 1; xsize < 0 && error("invalid window width")
    ysize = rows[end] - rows[1] + 1; ysize < 0 && error("invalid window height")
    rasterio!(dataset, buffer, bands, cols[1], rows[1], xsize, ysize, access,
        pxspace, linespace, bandspace)
    return buffer
end

function rasterio!(
        rasterband::AbstractRasterBand,
        buffer::Matrix{<:Real},
        access::GDALRWFlag  = GDAL.GF_Read,
        pxspace::Integer    = 0,
        linespace::Integer  = 0
    )
    rasterio!(rasterband, buffer, 0, 0, width(rasterband), height(rasterband),
        access, pxspace, linespace)
    return buffer
end

function rasterio!(
        rasterband::AbstractRasterBand,
        buffer::Matrix{<:Real},
        rows::UnitRange{<:Integer},
        cols::UnitRange{<:Integer},
        access::GDALRWFlag  = GDAL.GF_Read,
        pxspace::Integer    = 0,
        linespace::Integer  = 0
    )
    xsize = length(cols); xsize < 1 && error("invalid window width")
    ysize = length(rows); ysize < 1 && error("invalid window height")
    rasterio!(rasterband, buffer, cols[1]-1, rows[1]-1, xsize, ysize, access,
        pxspace, linespace)
    return buffer
end

read!(rb::AbstractRasterBand, buffer::Matrix{<:Real}) =
    rasterio!(rb, buffer, GDAL.GF_Read)

function read!(
        rb::AbstractRasterBand,
        buffer::Matrix{<:Real},
        xoffset::Integer,
        yoffset::Integer,
        xsize::Integer,
        ysize::Integer
    )
    rasterio!(rb, buffer, xoffset, yoffset, xsize, ysize)
    return buffer
end

function read!(
        rb::AbstractRasterBand,
        buffer::Matrix{<:Real},
        rows::UnitRange{<:Integer},
        cols::UnitRange{<:Integer}
    )
    rasterio!(rb, buffer, rows, cols)
    return buffer
end

read(rb::AbstractRasterBand) =
    rasterio!(rb, Array{pixeltype(rb)}(undef, width(rb), height(rb)))

function read(
        rb::AbstractRasterBand,
        xoffset::Integer,
        yoffset::Integer,
        xsize::Integer,
        ysize::Integer
    )
    buffer = Array{pixeltype(rb)}(undef, width(rb), height(rb))
    rasterio!(rb, buffer, xoffset, yoffset, xsize, ysize)
    return buffer
end

function read(
        rb::AbstractRasterBand,
        rows::UnitRange{<:Integer},
        cols::UnitRange{<:Integer}
    )
    buffer = Array{pixeltype(rb)}(undef, length(cols), length(rows))
    rasterio!(rb, buffer, rows, cols)
    return buffer
end

function write!(rb::AbstractRasterBand, buffer::Matrix{<:Real})
    rasterio!(rb, buffer, GDAL.GF_Write)
    return buffer
end

function write!(
        rb::AbstractRasterBand,
        buffer::Matrix{<:Real},
        xoffset::Integer,
        yoffset::Integer,
        xsize::Integer,
        ysize::Integer
    )
    rasterio!(rb, buffer, xoffset, yoffset, xsize, ysize, GDAL.GF_Write)
    return buffer
end

function write!(
        rb::AbstractRasterBand,
        buffer::Matrix{<:Real},
        rows::UnitRange{<:Integer},
        cols::UnitRange{<:Integer}
    )
    rasterio!(rb, buffer, rows, cols, GDAL.GF_Write)
    return buffer
end

function read!(dataset::AbstractDataset, buffer::Matrix{<:Real}, i::Integer)
    read!(getband(dataset, i), buffer)
    return buffer
end

function read!(
        dataset::AbstractDataset,
        buffer::Array{<:Real, 3},
        indices::Vector{Cint}
    )
    rasterio!(dataset, buffer, indices, GDAL.GF_Read)
    return buffer
end

function read!(dataset::AbstractDataset, buffer::Array{<:Real, 3})
    nband = nraster(dataset)
    @assert size(buffer, 3) == nband
    rasterio!(dataset, buffer, collect(Cint, 1:nband), GDAL.GF_Read)
    return buffer
end

function read!(
        dataset::AbstractDataset,
        buffer::Matrix{<:Real},
        i::Integer,
        xoffset::Integer,
        yoffset::Integer,
        xsize::Integer,
        ysize::Integer
    )
    read!(getband(dataset, i), buffer, xoffset, yoffset, xsize, ysize)
    return buffer
end

function read!(
        dataset::AbstractDataset,
        buffer::Array{<:Real, 3},
        indices::Vector{Cint},
        xoffset::Integer,
        yoffset::Integer,
        xsize::Integer,
        ysize::Integer
    )
    rasterio!(dataset, buffer, indices, xoffset, yoffset, xsize, ysize)
    return buffer
end

function read!(
        dataset::AbstractDataset,
        buffer::Matrix{<:Real},
        i::Integer,
        rows::UnitRange{<:Integer},
        cols::UnitRange{<:Integer}
    )
    read!(getband(dataset, i), buffer, rows, cols)
    return buffer
end

function read!(
        dataset::AbstractDataset,
        buffer::Array{<:Real, 3},
        indices::Vector{Cint},
        rows::UnitRange{<:Integer},
        cols::UnitRange{<:Integer}
    )
    rasterio!(dataset, buffer, indices, rows, cols)
    return buffer
end

read(dataset::AbstractDataset, i::Integer) = read(getband(dataset, i))

function read(
        dataset::AbstractDataset,
        indices::Vector{Cint}
    )
    buffer = Array{pixeltype(getband(dataset, indices[1]))}(undef,
        width(dataset), height(dataset), length(indices))
    rasterio!(dataset, buffer, indices)
    return buffer
end

function read(dataset::AbstractDataset)
    buffer = Array{pixeltype(getband(dataset, 1))}(undef, width(dataset),
        height(dataset), nraster(dataset))
    read!(dataset, buffer)
    return buffer
end

function read(
        dataset::AbstractDataset,
        i::Integer,
        xoffset::Integer,
        yoffset::Integer,
        xsize::Integer,
        ysize::Integer
    )
    buffer = read(getband(dataset, i), xoffset, yoffset, xsize, ysize)
    return buffer
end

function read(
        dataset::AbstractDataset,
        indices::Vector{<:Integer},
        xoffset::Integer,
        yoffset::Integer,
        xsize::Integer,
        ysize::Integer
    )
    buffer = Array{pixeltype(getband(dataset, indices[1]))}(undef,
        width(dataset), height(dataset), length(indices))
    rasterio!(dataset, buffer, indices, xsize, ysize, xoffset, yoffset)
    return buffer
end

function read(
        dataset::AbstractDataset,
        i::Integer,
        rows::UnitRange{<:Integer},
        cols::UnitRange{<:Integer}
    )
    buffer = read(getband(dataset, i), rows, cols)
    return buffer
end

function read(
        dataset::AbstractDataset,
        indices::Vector{Cint},
        rows::UnitRange{<:Integer},
        cols::UnitRange{<:Integer}
    )
    buffer = Array{pixeltype(getband(dataset, indices[1]))}(undef,
        width(dataset), height(dataset), length(indices))
    rasterio!(dataset, buffer, indices, rows, cols)
    return buffer
end

function write!(dataset::AbstractDataset, buffer::Matrix{<:Real}, i::Integer)
    write!(getband(dataset, i), buffer)
    return dataset
end

function write!(
        dataset::AbstractDataset,
        buffer::Array{<:Real, 3},
        indices::Vector{Cint}
    )
    rasterio!(dataset, buffer, indices, GDAL.GF_Write)
    return dataset
end

function write!(
        dataset::AbstractDataset,
        buffer::Matrix{<:Real},
        i::Integer,
        xoffset::Integer,
        yoffset::Integer,
        xsize::Integer,
        ysize::Integer
    )
    write!(getband(dataset, i), buffer, xoffset, yoffset, xsize, ysize)
    return dataset
end

function write!(
        dataset::AbstractDataset,
        buffer::Array{<:Real, 3},
        indices::Vector{Cint},
        xoffset::Integer,
        yoffset::Integer,
        xsize::Integer,
        ysize::Integer
    )
    rasterio!(dataset, buffer, indices, xoffset, yoffset, xsize, ysize,
        GDAL.GF_Write)
    return dataset
end

function write!(
        dataset::AbstractDataset,
        buffer::Matrix{<:Real},
        i::Integer,
        rows::UnitRange{<:Integer},
        cols::UnitRange{<:Integer}
    )
    write!(getband(dataset, i), buffer, rows, cols)
    return dataset
end

function write!(
        dataset::AbstractDataset,
        buffer::Array{<:Real, 3},
        indices::Vector{Cint},
        rows::UnitRange{<:Integer},
        cols::UnitRange{<:Integer}
    )
    rasterio!(dataset, buffer, indices, rows, cols, GDAL.GF_Write)
    return dataset
end

for (T,GT) in _GDALTYPE
    eval(quote
        function rasterio!(
                dataset::AbstractDataset,
                buffer::Array{$T, 3},
                bands::Vector{Cint},
                xoffset::Integer,
                yoffset::Integer,
                xsize::Integer,
                ysize::Integer,
                access::GDALRWFlag   = GDAL.GF_Read,
                pxspace::Integer     = 0,
                linespace::Integer   = 0,
                bandspace::Integer   = 0,
                extraargs            = Ptr{GDAL.GDALRasterIOExtraArg}(C_NULL)
            )
            # `psExtraArg`  (new in GDAL 2.0) pointer to a GDALRasterIOExtraArg
            # structure with additional arguments to specify resampling and
            # progress callback, or `NULL` for default behaviour. The
            # `GDAL_RASTERIO_RESAMPLING` configuration option can also be
            # defined to override the default resampling to one of `BILINEAR`,
            # `CUBIC`, `CUBICSPLINE`, `LANCZOS`, `AVERAGE` or `MODE`.
            (dataset == C_NULL) && error("Can't read invalid rasterband")
            xbsize, ybsize, zbsize = size(buffer)
            nband = length(bands)
            @assert nband == zbsize
            result = ccall((:GDALDatasetRasterIOEx,GDAL.libgdal),GDAL.CPLErr,
                (GDALDataset,GDAL.GDALRWFlag,Cint,Cint,Cint,Cint,Ptr{Cvoid},
                Cint,Cint,GDAL.GDALDataType,Cint,Ptr{Cint},GDAL.GSpacing,
                GDAL.GSpacing,GDAL.GSpacing,Ptr{GDAL.GDALRasterIOExtraArg}),
                dataset.ptr,access,xoffset,yoffset,xsize,ysize,pointer(buffer),
                xbsize,ybsize,$GT,nband,pointer(bands),pxspace,linespace,
                bandspace,extraargs)
            @cplerr result "Access in DatasetRasterIO failed."
            return buffer
        end

        function rasterio!(
                rasterband::AbstractRasterBand,
                buffer::Matrix{$T},
                xoffset::Integer,
                yoffset::Integer,
                xsize::Integer,
                ysize::Integer,
                access::GDALRWFlag   = GDAL.GF_Read,
                pxspace::Integer     = 0,
                linespace::Integer   = 0,
                extraargs            = Ptr{GDAL.GDALRasterIOExtraArg}(C_NULL)
            )
            # `psExtraArg`  (new in GDAL 2.0) pointer to a GDALRasterIOExtraArg
            # structure with additional arguments to specify resampling and
            # progress callback, or `NULL` for default behaviour. The
            # `GDAL_RASTERIO_RESAMPLING` configuration option can also be
            # defined to override the default resampling to one of `BILINEAR`,
            # `CUBIC`, `CUBICSPLINE`, `LANCZOS`, `AVERAGE` or `MODE`.
            (rasterband == C_NULL) && error("Can't read invalid rasterband")
            xbsize, ybsize = size(buffer)
            result = ccall((:GDALRasterIOEx,GDAL.libgdal),GDAL.CPLErr,
                (GDALRasterBand,GDAL.GDALRWFlag,Cint,Cint,Cint,Cint,Ptr{Cvoid},
                Cint,Cint,GDAL.GDALDataType,GDAL.GSpacing, GDAL.GSpacing,
                Ptr{GDAL.GDALRasterIOExtraArg}),rasterband.ptr,access,xoffset,
                yoffset,xsize,ysize,pointer(buffer),xbsize,ybsize,$GT,pxspace,
                linespace,extraargs)
            @cplerr result "Access in RasterIO failed."
            return buffer
        end
    end)
end

"""
    readblock!(rb::AbstractRasterBand, xoffset::Integer, yoffset::Integer, buffer)

Read a block of image data efficiently.

This method accesses a "natural" block from the raster band without resampling,
or data type conversion. For a more generalized, but potentially less efficient
access use RasterIO().

### Parameters
* `xoffset` the horizontal block offset, with zero indicating the left most
            block, 1 the next block and so forth.
* `yoffset` the vertical block offset, with zero indicating the top most block,
            1 the next block and so forth.
* `buffer`  the buffer into which the data will be read. The buffer must be
            large enough to hold GetBlockXSize()*GetBlockYSize() words of type
            GetRasterDataType().
"""
function readblock!(
        rb::AbstractRasterBand,
        xoffset::Integer,
        yoffset::Integer,
        buffer
    )
    result = GDAL.gdalreadblock(rb.ptr, xoffset, yoffset, buffer)
    @cplerr result "Failed to read block at ($xoffset,$yoffset)"
    return buffer
end

"""
    writeblock!(rb::AbstractRasterBand, xoffset::Integer, yoffset::Integer, buffer)

Write a block of image data efficiently.

This method accesses a "natural" block from the raster band without resampling,
or data type conversion. For a more generalized, but potentially less efficient
access use RasterIO().

### Parameters
* `xoffset` the horizontal block offset, with zero indicating the left most
            block, 1 the next block and so forth.
* `yoffset` the vertical block offset, with zero indicating the left most block,
            1 the next block and so forth.
* `buffer`  the buffer from which the data will be written. The buffer must be
            large enough to hold GetBlockXSize()*GetBlockYSize() words of type
            GetRasterDataType().
"""
function writeblock!(
        rb::AbstractRasterBand,
        xoffset::Integer,
        yoffset::Integer,
        buffer
    )
    result = GDAL.gdalwriteblock(rb.ptr, xoffset, yoffset, buffer)
    @cplerr result "Failed to write block at ($xoffset,$yoffset)"
    return rb
end


text:
eigvals(A::Operator,n::Integer;tolerance::Float64=100eps()) =
    eigs(A,n;tolerance=tolerance)[1]

"""
    λ, V = eigs(A::Operator,n::Integer;tolerance::Float64=100eps())

Compute the eigenvalues and eigenvectors of the operator `A`. This is done in the following way:

* Truncate `A` into an n×n matrix `A₁`.
* Compute eigenvalues and eigenvectors of `A₁`.
* Filter out those eigenvectors of `A₁`, which are approximately eigenvectors
of `A` as well. The `tolerance` argument controls, which eigenvectors of the approximation are kept.
"""
function eigs(A::Operator,n::Integer;tolerance::Float64=100eps())
    typ = eltype(A)

    ds=domainspace(A)
    C = Conversion(ds,rangespace(A))

    A1,C1 = zeros(typ,n,n),zeros(typ,n,n)
    A1[1:end,1:n] = A[1:n,1:n]
    C1[1:end,1:n] = C[1:n,1:n]

    λ,V=eigen(A1,C1)

    pruneeigs(λ,V,ds,tolerance)
end

eigvals(Bcs::Operator,A::Operator,n::Integer;tolerance::Float64=100eps()) =
    eigs(Bcs,A,n;tolerance=tolerance)[1]

function eigs(Bcs_in::Operator,A_in::Operator,n::Integer;tolerance::Float64=100eps())
    Bcs, A = promotedomainspace([Bcs_in, A_in])

    nf = size(Bcs,1)
    @assert isfinite(nf)

    typ = promote_type(eltype(Bcs),eltype(A))

    ds=domainspace(A)
    C = Conversion(ds,rangespace(A))

    A1,C1 = zeros(typ,n,n),zeros(typ,n,n)
    A1[1:nf,1:n] = Bcs[1:nf,1:n]
    A1[nf+1:end,1:n] = A[1:n-nf,1:n]
    C1[nf+1:end,1:n] = C[1:n-nf,1:n]

    λ,V = eigen(A1,C1)

    λ, V = pruneeigs(λ,V,ds,tolerance)
    p = sortperm(λ; lt=(x,y) -> isless(abs(x),abs(y)))
    λ[p], V[p]
end

function pruneeigs(λ,V,ds,tolerance)
    retλ=eltype(λ)[]
    retV=VFun{typeof(ds),eltype(V)}[]
    n=length(λ)
    for k=1:n
        if slnorm(V,n-3:n,k)≤tolerance
            push!(retλ,λ[k])
            push!(retV,Fun(ds,V[:,k]))
        end
    end
    retλ,retV
end


text:
#! /usr/bin/env julia
# This script builds/pulls all static contents needed by storage server.
#
# Usage:
#  1. make sure you've added StorageMirrorServer.jl
#  2. generate/pull all tarballs: `julia gen_static_full.jl`
#  3. set a cron job to run step 2 regularly
#
# Note:
#   * Initialization would typically take days, depending on the network bandwidth and CPU
#   * set `JULIA_NUM_THREADS` to use multiple threads
#
# Disk space requirements for a complete storage (increases over time):
#   * `STATIC_DIR`: at least 500GB, would be better to have more than 3TB free space

using StorageMirrorServer
using Pkg

# This holds all the data you need to set up a storage server
# For example, my nginx service serves all files in `/mnt/mirrors` as static contents using autoindex
output_dir = "julia"

# check https://status.julialang.org/ for available public storage servers
upstreams = [
    "https://kr.storage.juliahub.com",
    "https://us-east.storage.juliahub.com",
]

registries = [
    # (name, uuid, original_git_url)
    ("General", "23338594-aafe-5451-b93e-139f81909106", "https://github.com/JuliaRegistries/General")
]

# These are default parameter settings for StorageMirrorServer
# you can modify them accordingly to fit your settings
parameters = Dict(
    # if needed, you can pass custom http parameters
    :http_parameters => Dict{Symbol, Any}(
        :retry => true,
        :retries => 2,
        :timeout => 7200,
        # download data using proxy
        # it also respects `http_proxy`, `https_proxy` and `no_proxy` environment variables
        # :proxy => "http://localhost:1080"
    ),

    # whether to show the progress bar
    :show_progress => true,

    # This script generates a `failed_resource.txt` that records failed-to-downloaded files. Some of
    # these have already disappears in the network and no longer available. By default, items in
    # this file are skipped in next 24 hours. You can configure `skip_duration` to make it larger.
    # Or, you could manually create a `blocklist.txt` to permanently skip them.
    :skip_duration => 24
)

for reg in registries
    mirror_tarball(reg, upstreams, output_dir; parameters...)
end


text:
# m6_11s.jl

using Pkg, DrWatson

using MonteCarloMeasurements
using StanSample
using StatisticalRethinking

N = 200
b_GP = 1                               # Direct effect of G on P
b_GC = 0                               # Direct effect of G on C
b_PC = 1                               # Direct effect of P on C
b_U = 2                                # Direct effect of U on P and C

df = DataFrame(
  :u => 2 * rand(Bernoulli(0.5), N) .- 1,
  :g => rand(Normal(), N)
)

df[!, :p] = [rand(Normal(b_GP * df[i, :g] + b_U * df[i, :u]), 1)[1] for i in 1:N]
df[!, :c] = [rand(Normal(b_PC * df[i, :p] + b_GC * df[i, :g] + b_U * df[i, :u]), 1)[1] for i in 1:N]

precis(df)

stan6_11 = "
data {
    int <lower=0> N;
    vector[N] C;
    vector[N] P;
    vector[N] G;
}
parameters {
    real <lower=0> sigma;
    real a;
    real b_PC;
    real b_GC;
}
model {
    vector[N] mu;
    sigma ~ exponential(1);
    a ~ normal(0, 1);
    b_PC ~ normal(0, 1);
    b_GC ~ normal(0, 1);
    mu = a + b_PC * P + b_GC * G;
    C ~ normal(mu, sigma);
}
";

m6_11s = SampleModel("m6.11s", stan6_11)
m6_11_data = Dict(:N => nrow(df), :C => df.c, :P => df.p, :G => df.g)
rc6_11s = stan_sample(m6_11s, data=m6_11_data)

if success(rc6_11s)
    part6_11s = read_samples(m6_11s, :particles)
    part6_11s |> display
end

# End of m6.11s.jl


text:
function Mesh2D(domain::CubePanelDomain{FT}, ne) where {FT <: AbstractFloat}
    return cube_panel_mesh(domain, NoWarp(), ne, FT)
end

function Mesh2D(
    domain::SphereDomain{FT},
    warp_type::AbstractSphereWarp,
    ne,
) where {FT <: AbstractFloat}
    radius = domain.radius
    # map the cube to [-radius, radius],[-radius, radius],[-radius, radius]
    mesh = cube_panel_mesh(domain, warp_type, ne, FT)
    mesh.coordinates .-= FT(0.5)
    mesh.coordinates .*= (FT(2) * radius)

    for i in 1:(mesh.nverts)
        mesh.coordinates[i, :] .=
            cubed_sphere_warp(warp_type, mesh.coordinates[i, :]...)
    end
    return mesh
end

"""
    cube_panel_mesh(ne)

This function builds a cube panel mesh with a resolution of `ne` elements along each edge.

                v7                     v8 (1,1,1)
                 o--------e4----------o
                /|                   /|
               / |                  / |
              /  |                 /  |
             e7  e11              e8 e12
            /    |               /    |
           /     |            v6/     |
       v5 o--------e3----------o      |
          |    v3o------e2-----|------o v4 (1,1,0)
          |     /              |     /
          |    /               |    /
          e9  e5              e10  e6
          |  /                 |  /
          | /                  | /
          |/                   |/
          o--------e1----------o
         v1                    v2
       (0,0,0)               (1,0,0)

       Partitioning with Space-Filling Curves on the Cubed-Sphere - John M. Dennis  (2003 iEEE)
       https://www.researchgate.net/publication/224742710_Partitioning_with_space-filling_curves_on_the_cubed-sphere

       panel 1 => 1 2 3 4
       panel 2 => 2 4 6 8
       panel 3 => 3 4 7 8
       panel 4 => 1 3 5 7
       panel 5 => 1 2 5 6
       panel 6 => 5 6 7 8

            +-------+
            |       |
            |   3   |
            |       |
    +-------+-------+-------+-------+
    |       |       |       |       |
    |   4   |   1   |   2   |   6   |
    |       |       |       |       |
    +-------+-------+-------+-------+
            |       |
            |   5   |
            |       |
            +-------+
"""
function cube_panel_mesh(
    domain::Union{CubePanelDomain{FT}, SphereDomain{FT}},
    warp_type::AbstractWarp,
    ne::I,
    ::Type{FT},
) where {FT <: AbstractFloat, I <: Integer}

    nverts = (ne + 1)^3 - (ne - 1)^3
    nfaces = 12 * ne + 6 * (2 * ne * (ne - 1))
    nelems = 6 * ne * ne
    nbndry = 0

    nx = ne + 1

    nfaces_edg = 12 * ne

    emat = reshape(1:nelems, ne, ne, 6)
    ndmat = zeros(I, ne + 1, ne + 1)

    panel_verts = [
        1 2 3 1 1 5
        2 4 4 3 2 6
        3 6 7 5 5 7
        4 8 8 7 6 8
    ]

    edge_nodes = reshape(1:((ne - 1) * 12), ne - 1, 12) .+ 8

    panel_edges = [
        5 10 11 9 9 7
        6 12 12 11 10 8
        1 6 2 5 1 3
        2 8 4 7 3 4
    ]

    face_interior = reshape(1:((ne - 1) * (ne - 1)), ne - 1, ne - 1)

    nfc1i = (nx - 2) * (nx - 1) # panels with normals along first direction
    nfc2i = (nx - 1) * (nx - 2) # panels with normals along second direction
    nfci = nfc1i + nfc2i
    fci1 = reshape(1:nfc1i, nx - 2, nx - 1)
    fci2 = reshape(1:nfc2i, nx - 1, nx - 2)

    fcmat1 = zeros(I, nx, nx - 1) # face numbering
    fcmat2 = zeros(I, nx - 1, nx) # for each panel

    edge_faces = reshape(1:(12 * ne), ne, 12)

    # node coordinates
    xc = range(FT(0), FT(1); step = FT(1 / ne))
    xci = view(xc, 2:ne)
    zc = zeros(FT, ne - 1)
    oc = ones(FT, ne - 1)
    zc2 = zeros(FT, (ne - 1) * (ne - 1))
    oc2 = ones(FT, (ne - 1) * (ne - 1))

    xci12 = repeat(xci, ne - 1)
    xci21 = repeat(xci', ne - 1, 1)[:]

    coordinates = vcat(
        hcat(
            [0, 1, 0, 1, 0, 1, 0, 1],  # x1,
            [0, 0, 1, 1, 0, 0, 1, 1],  # x2,
            [0, 0, 0, 0, 1, 1, 1, 1],
        ), # x3 vertex coordinates
        vcat(
            hcat(xci, zc, zc),    # edge  1
            hcat(xci, oc, zc),    # edge  2
            hcat(xci, zc, oc),    # edge  3
            hcat(xci, oc, oc),
        ),   # edge  4
        vcat(
            hcat(zc, xci, zc),    # edge  5
            hcat(oc, xci, zc),    # edge  6
            hcat(zc, xci, oc),    # edge  7
            hcat(oc, xci, oc),
        ),   # edge  8
        vcat(
            hcat(zc, zc, xci),    # edge  9
            hcat(oc, zc, xci),    # edge 10
            hcat(zc, oc, xci),    # edge 11
            hcat(oc, oc, xci),
        ),   # edge 12
        hcat(xci12, xci21, zc2),   # panel 1
        hcat(oc2, xci12, xci21),   # panel 2
        hcat(xci12, oc2, xci21),   # panel 3
        hcat(zc2, xci12, xci21),   # panel 4
        hcat(xci12, zc2, xci21),   # panel 5
        hcat(xci12, xci21, oc2),   # panel 6
    )

    face_verts = zeros(I, nfaces, 2)
    face_neighbors = zeros(I, nfaces, 5)
    face_boundary = Vector{I}(zeros(nfaces)) # all interior nodes (no boundaries)
    elem_verts = zeros(I, nelems, 4)
    elem_faces = zeros(I, nelems, 4)

    for sfc in 1:6
        ndmat[1, 1],
        ndmat[ne + 1, 1],  # panel vertices
        ndmat[1, ne + 1],
        ndmat[ne + 1, ne + 1] = panel_verts[:, sfc]

        ndmat[1, 2:ne] .= edge_nodes[:, panel_edges[1, sfc]] # panel edges
        ndmat[end, 2:ne] .= edge_nodes[:, panel_edges[2, sfc]]
        ndmat[2:ne, 1] .= edge_nodes[:, panel_edges[3, sfc]]
        ndmat[2:ne, end] .= edge_nodes[:, panel_edges[4, sfc]]

        offset = 8 + 12 * (ne - 1) + (sfc - 1) * (ne - 1) * (ne - 1) # interior
        ndmat[2:ne, 2:ne] .= face_interior .+ offset

        fcmat1[1, :] = edge_faces[:, panel_edges[1, sfc]]
        fcmat1[end, :] = edge_faces[:, panel_edges[2, sfc]]
        fcmat2[:, 1] = edge_faces[:, panel_edges[3, sfc]]
        fcmat2[:, end] = edge_faces[:, panel_edges[4, sfc]]
        off = ne * 12 + (sfc - 1) * nfci
        fcmat1[2:(end - 1), :] .= fci1 .+ off
        fcmat2[:, 2:(end - 1)] .= fci2 .+ (off + nfc1i)

        face_verts[fcmat1[:], 1] .= ndmat[:, 1:ne][:] # face nodes
        face_verts[fcmat1[:], 2] .= ndmat[:, 2:(ne + 1)][:]
        face_verts[fcmat2[:], 1] .= ndmat[1:ne, :][:]
        face_verts[fcmat2[:], 2] .= ndmat[2:(ne + 1), :][:]

        if sfc == 1
            bdy1 = emat[:, 1:1, 4]'
            bdy2 = emat[:, 1:1, 2]'
            bdy3 = emat[:, 1:1, 5]
            bdy4 = emat[:, 1:1, 3]
        elseif sfc == 2
            bdy1 = emat[end:end, :, 5]
            bdy2 = emat[end:end, :, 3]
            bdy3 = emat[end:end, :, 1]'
            bdy4 = emat[end:end, :, 6]'
        elseif sfc == 3
            bdy1 = emat[end:end, :, 4]
            bdy2 = emat[end:end, :, 2]
            bdy3 = emat[:, end:end, 1]
            bdy4 = emat[:, end:end, 6]
        elseif sfc == 4
            bdy1 = emat[1:1, :, 5]
            bdy2 = emat[1:1, :, 3]
            bdy3 = emat[1:1, :, 1]'
            bdy4 = emat[1:1, :, 6]'
        elseif sfc == 5
            bdy1 = emat[1:1, :, 4]
            bdy2 = emat[1:1, :, 2]
            bdy3 = emat[:, 1:1, 1]
            bdy4 = emat[:, 1:1, 6]
        else # sfc == 6
            bdy1 = emat[:, end:end, 4]'
            bdy2 = emat[:, end:end, 2]'
            bdy3 = emat[:, end:end, 5]
            bdy4 = emat[:, end:end, 3]
        end

        face_neighbors[fcmat1[:], 1] .= vcat(bdy1, emat[:, :, sfc])[:]
        face_neighbors[fcmat1[:], 3] .= vcat(emat[:, :, sfc], bdy2)[:]
        face_neighbors[fcmat2[:], 1] .= hcat(bdy3, emat[:, :, sfc])[:]
        face_neighbors[fcmat2[:], 3] .= hcat(emat[:, :, sfc], bdy4)[:]

        elem_verts[emat[:, :, sfc][:], :] .= hcat(
            ndmat[1:ne, 1:ne][:], # node numbers
            ndmat[2:(ne + 1), 1:ne][:], # for each element
            ndmat[1:ne, 2:(ne + 1)][:],
            ndmat[2:(ne + 1), 2:(ne + 1)][:],
        )

        elem_faces[emat[:, :, sfc][:], :] .= hcat(
            fcmat1[1:(nx - 1), :][:], # face numbers for
            fcmat1[2:nx, :][:],   # each element
            fcmat2[:, 1:(nx - 1)][:],
            fcmat2[:, 2:nx][:],
        )
    end

    ref_fc_verts = [1 2 1 3; 3 4 2 4]

    for fc in 1:nfaces
        elems = (face_neighbors[fc, 1], face_neighbors[fc, 3])
        for e in 1:2
            el = elems[e]
            if el ≠ 0
                localface = findfirst(elem_faces[el, :] .== fc)
                if isnothing(localface)
                    error(
                        "rectangular_mesh: Fatal error, face could not be located in neighboring element",
                    )
                else
                    face_neighbors[fc, 2 + (e - 1) * 2] = localface
                end
            end
        end
        # setting up relative orientation
        or1 =
            elem_verts[elems[1], ref_fc_verts[:, face_neighbors[fc, 2]]] ==
            face_verts[fc, :] ? 1 : -1
        or2 =
            elem_verts[elems[2], ref_fc_verts[:, face_neighbors[fc, 4]]] ==
            face_verts[fc, :] ? 1 : -1
        face_neighbors[fc, 5] = or1 * or2
    end

    boundary_tags = sort(unique(face_boundary))
    face_boundary_offset = ones(I, length(boundary_tags) + 1)
    face_boundary_tags = sort(face_boundary)
    face_boundary = sortperm(face_boundary)

    for i in 1:(length(boundary_tags) - 1)
        tag = boundary_tags[i + 1]
        face_boundary_offset[i + 1] = findfirst(face_boundary_tags .== tag)
    end
    face_boundary_offset[end] = length(face_boundary) + 1

    boundary_tag_names = (:interior,)

    # add unique vertex iterator information
    vtconn = map(i -> zeros(I, i), zeros(I, nverts))

    for el in 1:nelems
        for lv in 1:4
            vt = elem_verts[el, lv]
            push!(vtconn[vt], el, lv)
        end
    end
    unique_verts = I[]
    uverts_conn = I[]
    uverts_offset = I.([1])
    for vt in 1:nverts
        lconn = length(vtconn[vt])
        if lconn > 0
            push!(unique_verts, vt)
            push!(uverts_conn, vtconn[vt]...)
            push!(uverts_offset, uverts_offset[end] + lconn)
        end
    end

    return Mesh2D(
        domain,
        warp_type,
        nverts,
        nfaces,
        nelems,
        nbndry,
        coordinates,
        unique_verts,
        uverts_conn,
        uverts_offset,
        face_verts,
        face_neighbors,
        face_boundary,
        boundary_tags,
        boundary_tag_names,
        face_boundary_offset,
        elem_verts,
        elem_faces,
    )
end


text:
# van_der_Pol_orbit_diagram_vs_frequency_with_winding_number_v4.jl
# =================================================================

# with zoom
# new transient time

using DrWatson
@quickactivate "NonlinearDynamicsTextbook"
include(srcdir("style.jl"))
using DynamicalSystems, PyPlot, OrdinaryDiffEq
using StaticArrays
using Random
using Statistics

function van_der_Pol_ODE(du,u,p,t)
    d, a, omega = p
    du[1] =  u[2]
    du[2] =  - u[1] - d*(u[1]*u[1]-1) * u[2] + a*sin(omega*t)
end

function Poincare_orbit(d,a,omega,y_init,ttrans,nattr,twind,pcol)

    p = [d a omega]
    period = 2*pi / omega
    ntrans = ceil( ttrans / period )   # no. of periods required for transient
    nwind = ceil( twind / period )   # no. of periods required for transient

 # transient to attractor
 # ----------------------
    tspan = (0., ntrans*period)
    prob = ODEProblem(van_der_Pol_ODE, y_init, tspan, p)
    sol = solve(prob, Tsit5(), reltol=1e-8, abstol=1e-8, maxiters = 1e12 )

  # attractor  with root of Poincare map
  # ---------
    tspan = (0., nattr*period)
    y_init = sol.u[end]
    prob = ODEProblem(van_der_Pol_ODE, y_init, tspan, p)
    sol = solve(prob, Tsit5(), reltol=1e-8, abstol=1e-8, maxiters = 1e12, saveat = period)

    u1vec = [u[1] for u in sol.u]
    npts = length(u1vec)

    # Code for root of the Poincare map with 'saveat = period/2'
    # ----------------------------------------------------------
    # for j = 2:2:npts
    #     u1vec[j] = -u1vec[j]
    # end

    # sol = solve(prob, Tsit5(), reltol=1e-8, abstol=1e-8, saveat = period/2)

    # u1vec = [u[1] for u in sol.u]
    # npts = length(u1vec)
    # for j = 2:2:npts
    #     u1vec[j] = -u1vec[j]
    # end

  # plot
  # ----
    plt.scatter(omega*ones(npts),u1vec,s=1, c = pcol)

  # compute winding number
  # ----------------------
    tspan = (0., nwind*period)
    # y_init = sol.u[end]
    prob = ODEProblem(van_der_Pol_ODE, y_init, tspan, p)
    sol = solve(prob, Tsit5(), reltol=1e-8, abstol=1e-8, maxiters = 1e12,  saveat = period/100)

    u1vec = [u[1] for u in sol.u]
    u2vec = [u[2] for u in sol.u]
    nts = length(u1vec)

    theta = 0.
    theta_old = atan.( u2vec[1] , u1vec[1])

    for its = 2:nts
        theta_new = atan.( u2vec[its] , u1vec[its]  )    # is dereasing = clockwise rotation
        # delta_th = theta_new  - theta_old  # < 0
        delta_theta = mod( theta_new  - theta_old  + pi, 2 .* pi) - pi
        theta = theta + delta_theta

        theta_old = theta_new
    end

    wind_no = - theta / ( 2 * pi * nwind )
    println(1 / wind_no)

    return y_init, wind_no

end # of function

# -------- main -----

println("this takes 56 min ..")

@time begin

# open plot
# ---------
fig = figure("van der Pol oscillator a=1",figsize=(figx,1.6*figy))

# parameters and initial values
# -----------------------------
d = 5.
a = 1.

ttrans = 6000   # minimal transient time
nattr = 500     # no. of points on the attractor
twind = 8000    # averaging of winding number
y_init = [0.1 0.1]

# compute and plot orbit diagram
# ------------------------------
omega_min = 0.2
omega_max = 2.
nomega =  1000 # 800
omega_vec = LinRange(omega_min, omega_max, nomega)
wind_no_vec = zeros(nomega)  # winding numbers

subplot(2,2,1)

pcol = COLORS[1]
for iomega = 1:length(omega_vec)
    omega = omega_vec[iomega]
    y_init, wind_no =  Poincare_orbit(d,a,omega,y_init,ttrans,nattr,twind, pcol)
    wind_no_vec[iomega] = 1 / wind_no
end # of frequency loop

xlabel(L"\omega")
ylabel(L"u_1")

ax = gca()
ax.set_xlim([omega_min,omega_max])

# plot winding number
subplot(2,2,3)
plt.plot(omega_vec,wind_no_vec,c = "k")

xlabel(L"\omega")
ylabel(L"W")
ax = gca()
ax.set_xlim([omega_min,omega_max])

# zoom
# ====
omega_min = 0.8
omega_max = 1.
nomega =  1000
omega_vec = LinRange(omega_min, omega_max, nomega)
wind_no_vec = zeros(nomega)  # winding numbers

subplot(2,2,2)

pcol = COLORS[1]
for iomega = 1:length(omega_vec)
    omega = omega_vec[iomega]
    y_init, wind_no =  Poincare_orbit(d,a,omega,y_init,ttrans,nattr,twind,pcol)
    wind_no_vec[iomega] = 1 / wind_no
end # of frequency loop

xlabel(L"\omega")
ylabel(L"u_1")

ax = gca()
ax.set_xlim([omega_min,omega_max])

# plot winding number
subplot(2,2,4)
plt.plot(omega_vec,wind_no_vec,c = "k")

xlabel(L"\omega")
ylabel(L"W")
ax = gca()
ax.set_xlim([omega_min,omega_max])

add_identifiers!(fig)
fig.tight_layout(pad=0.3)

end # of time

# Output
# ------
# dname = "/Users/parlitz/ownCloud/NonlinearDynamicsTextbook/figure_generation/9/van_der_Pol/orbit_diagram/"
# fname = "van_der_Pol_orbit_diagram_vs_frequency_wind_no_v4_d=5_a=1_v5"
# ftype = ".png"

# savefig(dname*fname*ftype)

max_stars_repo_name: JuliaDynamics/NonlinearDynamicsTextbook

max_issues_repo_name: JuliaDynamics/NonlinearDynamicsTextbook

max_forks_repo_name: JuliaDynamics/NonlinearDynamicsTextbook


text:
#=
This file is part of the replication code for: Hasenzagl, T., Pellegrino, F., Reichlin, L., & Ricco, G. (2020). A Model of the Fed's View on Inflation.
Please cite the paper if you are using any part of the code for academic work (including, but not limited to, conference and peer-reviewed papers).
=#

function ex_ismember(a, b)
     x = sum(a .== b', 2) .== 1;
     return x;
end


text:
"""
    Continuity
"""
abstract type Continuity end

struct ContinuousTrait <: Continuity end
const Continuous = ContinuousTrait()

struct DiscreteTrait <: Continuity end
const Discrete = DiscreteTrait()

Continuity(::T) where {T} = Continuity(T)
Continuity(::Type{T}) where {T} = Discrete
Continuity(::Type{T}) where {T<:AbstractRange} = Continuous


text:
using Base58, BitConverter
@testset "Script" begin
    @testset "parse" begin
        script_pubkey = IOBuffer(hex2bytes("6a47304402207899531a52d59a6de200179928ca900254a36b8dff8bb75f5f5d71b1cdc26125022008b422690b8461cb52c3cc30330b23d574351872b7c361e9aae3649071c1a7160121035d5c93d9ac96881f19ba1f686f15f009ded7c62efe85a872e6a19b43c15a2937"))
        script = Bitcoin.scriptparse(script_pubkey)
        want = hex2bytes("304402207899531a52d59a6de200179928ca900254a36b8dff8bb75f5f5d71b1cdc26125022008b422690b8461cb52c3cc30330b23d574351872b7c361e9aae3649071c1a71601")
        @test script.instructions[1] == want
        want = hex2bytes("035d5c93d9ac96881f19ba1f686f15f009ded7c62efe85a872e6a19b43c15a2937")
        @test script.instructions[2] == want
        script_pubkey = IOBuffer(hex2bytes("fdfe0000483045022100c679944ff8f20373685e1122b581f64752c1d22c67f6f3ae26333aa9c3f43d730220793233401f87f640f9c39207349ffef42d0e27046755263c0a69c436ab07febc01483045022100eadc1c6e72f241c3e076a7109b8053db53987f3fcc99e3f88fc4e52dbfd5f3a202201f02cbff194c41e6f8da762e024a7ab85c1b1616b74720f13283043e9e99dab8014c69522102b0c7be446b92624112f3c7d4ffc214921c74c1cb891bf945c49fbe5981ee026b21039021c9391e328e0cb3b61ba05dcc5e122ab234e55d1502e59b10d8f588aea4632102f3bd8f64363066f35968bd82ed9c6e8afecbd6136311bb51e91204f614144e9b53aeffffffff05a08601000000000017a914081fbb6ec9d83104367eb1a6a59e2a92417d79298700350c00000000001976a914677345c7376dfda2c52ad9b6a153b643b6409a3788acc7f341160000000017a914234c15756b9599314c9299340eaabab7f1810d8287c02709000000000017a91469be3ca6195efcab5194e1530164ec47637d44308740420f00000000001976a91487fadba66b9e48c0c8082f33107fdb01970eb80388ac00000000"))
        want = hex2bytes("522102b0c7be446b92624112f3c7d4ffc214921c74c1cb891bf945c49fbe5981ee026b21039021c9391e328e0cb3b61ba05dcc5e122ab234e55d1502e59b10d8f588aea4632102f3bd8f64363066f35968bd82ed9c6e8afecbd6136311bb51e91204f614144e9b53ae")
        script = Bitcoin.scriptparse(script_pubkey)
        @test script.instructions[4] == want
    end
    @testset "Serialize" begin
        want = "6a47304402207899531a52d59a6de200179928ca900254a36b8dff8bb75f5f5d71b1cdc26125022008b422690b8461cb52c3cc30330b23d574351872b7c361e9aae3649071c1a7160121035d5c93d9ac96881f19ba1f686f15f009ded7c62efe85a872e6a19b43c15a2937"
        script_pubkey = IOBuffer(hex2bytes(want))
        script = Bitcoin.scriptparse(script_pubkey)
        @test bytes2hex(Bitcoin.serialize(script)) == want
    end
    @testset "Evaluate" begin
        modified_tx = hex2bytes("0100000001813f79011acb80925dfe69b3def355fe914bd1d96a3f5f71bf8303c6a989c7d1000000001976a914a802fc56c704ce87c42d7c92eb75e7896bdc41ae88acfeffffff02a135ef01000000001976a914bc3b654dca7e56b04dca18f2566cdaf02e8d9ada88ac99c39800000000001976a9141c4bc762dd5423e332166702cb75f40df79fea1288ac1943060001000000")
        h256 = Bitcoin.hash256(modified_tx)
        z = to_int(h256)
        stream = IOBuffer(hex2bytes("0100000001813f79011acb80925dfe69b3def355fe914bd1d96a3f5f71bf8303c6a989c7d1000000006b483045022100ed81ff192e75a3fd2304004dcadb746fa5e24c5031ccfcf21320b0277457c98f02207a986d955c6e0cb35d446a89d3f56100f4d7f67801c31967743a9c8e10615bed01210349fc4e631e3624a545de3f89f5d8684c7b8138bd94bdd531d2e213bf016b278afeffffff02a135ef01000000001976a914bc3b654dca7e56b04dca18f2566cdaf02e8d9ada88ac99c39800000000001976a9141c4bc762dd5423e332166702cb75f40df79fea1288ac19430600"))
        tx = parse(stream)::Tx
        tx_in = tx.tx_ins[1]
        combined_script = Bitcoin.Script(nothing)
        append!(combined_script.instructions, copy(tx_in.script_sig.instructions))
        append!(combined_script.instructions, copy(Bitcoin.script_pubkey(tx_in).instructions))
        @test Bitcoin.evaluate(combined_script, z) == true
    end
    @testset "Address" begin
        address_1 = "1BenRpVUFK65JFWcQSuHnJKzc4M8ZP8Eqa"
        h160 = base58checkdecode(UInt8.(collect(address_1)))[2:end]
        p2pkh_script_pubkey = Bitcoin.p2pkh_script(h160)
        @test script2address(p2pkh_script_pubkey, false) == address_1
        address_2 = "mrAjisaT4LXL5MzE81sfcDYKU3wqWSvf9q"
        @test script2address(p2pkh_script_pubkey, true) == address_2
        address_3 = "3CLoMMyuoDQTPRD3XYZtCvgvkadrAdvdXh"
        h160 = base58checkdecode(UInt8.(collect(address_3)))[2:end]
        p2sh_script_pubkey = Bitcoin.p2sh_script(h160)
        @test script2address(p2sh_script_pubkey, false) == address_3
        address_4 = "2N3u1R6uwQfuobCqbCgBkpsgBxvr1tZpe7B"
        @test script2address(p2sh_script_pubkey, true) == address_4
    end
    @testset "P2WPKH" begin
        h160 = hex2bytes("74d691da1574e6b3c192ecfb52cc8984ee7b6c56")
        p2wpkh_script = Bitcoin.p2wpkh_script(h160)
        @test Bitcoin.is_p2wpkh(p2wpkh_script)
    end
end


text:
using Test, LinearAlgebra, PhasedArray, StaticArrays, CoordinateTransformations, Interpolations, Random, Rotations

const EXAMPLE_LUT = SVector([-5.7078+9.35399im -2.5379+10.66im 0.880432+10.9225im 4.21258+10.1158im 7.13237+8.31898im 9.35399+5.7078im 10.66+2.5379im 10.9225-0.880432im 10.1158-4.21258im 8.31898-7.13237im 5.7078-9.35399im 2.5379-10.66im -0.880432-10.9225im -4.21258-10.1158im -7.13237-8.31898im -9.35399-5.7078im -10.66-2.5379im -10.9225+0.880432im -10.1158+4.21258im -8.31898+7.13237im; -2.92983+11.3667im 1.89319+11.5399im 5.95279+9.87774im 8.67235+7.17072im 10.0222+4.2519im 10.3557+1.69283im 10.1422-0.309334im 9.74-1.86734im 9.2859-3.24392im 8.70125-4.68534im 7.77128-6.30552im 6.24428-8.03485im 3.92146-9.61231im 0.748499-10.6018im -3.07119-10.4589im -6.97975-8.70517im -10.101-5.20192im -11.5001-0.382397im -10.5936+4.75934im -7.47524+8.99718im; -0.216611+11.5061im 5.35705+10.2762im 9.10426+6.86225im 10.5977+2.85826im 10.3932-0.408505im 9.46519-2.30716im 8.64987-2.92284im 8.33038-2.79908im 8.44385-2.58407im 8.67441-2.7732im 8.65067-3.60217im 8.05841-5.08176im 6.62685-7.05999im 4.08195-9.14687im 0.275511-10.5469im -4.41347-10.1469im -8.77984-7.11999im -11.1258-1.69957im -10.2009+4.57227im -6.07889+9.51627im;1.70403+9.96745im 6.80512+7.7488im 9.4351+3.47579im 9.59045-0.925037im 8.37188-4.06076im 7.08296-5.34748im 6.55379-5.01314im 6.84712-3.83431im 7.54192-2.63336im 8.1795-1.97996im 8.42301-2.10676im 8.09846-3.03599im 7.0956-4.77848im 5.1519-7.18815im 1.87367-9.50075im -2.66495-10.2227im -7.25878-7.95956im -9.83949-2.67411im -8.80547+3.7818im -4.31549+8.63307im; 2.58851+7.52972im 6.36233+5.13796im 7.60694+1.07401im 6.71037-2.98171im 5.09368-5.87641im 4.10786-6.99832im 4.31087-6.42438im 5.32356-4.88562im 6.4295-3.26498im 7.2145-2.17533im 7.46964-1.83023im 7.10368-2.23904im 6.1511-3.53087im 4.49189-5.75432im 1.76965-8.25608im -2.03981-9.48682im -5.93235-7.862im -7.97165-3.20938im -6.72227+2.58651im -2.53476+6.74812im; 2.65306+4.98345im 4.89296+3.14456im 4.94449+0.00609865im 3.40884-3.31952im 1.78895-6.01659im 1.32315-7.3719im 2.21557-7.11829im 3.74402-5.72856im 5.0443-4.08801im 5.81967-2.86509im 6.02191-2.27207im 5.56169-2.31398im 4.48553-3.1823im 2.8431-5.00265im 0.546714-7.21154im -2.28902-8.41962im -4.9136-7.24029im -5.93083-3.53102im -4.46613+1.10049im -1.04682+4.38743im; 2.28216+2.76921im 3.19345+1.88159im 2.43028-0.0756372im 0.656211-2.57115im -0.778546-5.07559im -0.835239-6.77379im 0.444139-7.05616im 2.17514-6.0952im 3.48497-4.67232im 4.13565-3.48093im 4.19436-2.78641im 3.61634-2.62313im 2.41185-3.16898im 0.750127-4.5462im -1.11641-6.28675im -2.89148-7.2718im -4.08302-6.49968im -4.01169-3.90781im -2.44014-0.572563im 0.0448655+1.97723im; 1.83884+1.02319im 1.77609+1.1203im 0.590593+0.257649im -1.09378-1.43161im -2.24822-3.58215im -2.11921-5.39966im -0.838565-6.13043im 0.763675-5.69152im 1.92109-4.62517im 2.38188-3.54888im 2.20869-2.81842im 1.46806-2.56576im 0.233282-2.91209im -1.24983-3.91966im -2.53723-5.24068im -3.26216-6.09047im -3.22145-5.81225im -2.34342-4.32608im -0.824032-2.15118im 0.801839-0.134057im; 1.55077-0.169921im 0.990389+0.583706im -0.223209+0.520155im -1.57787-0.399746im -2.41894-1.90247im -2.32723-3.38619im -1.42979-4.2352im -0.288417-4.2298im 0.541021-3.60663im 0.791734-2.7882im 0.456765-2.14186im -0.337265-1.89663im -1.39584-2.16497im -2.4216-2.93952im -3.03034-3.97791im -2.95759-4.80743im -2.2056-4.99035im -0.998067-4.36148im 0.304165-3.07186im 1.27485-1.51534im; 1.45956-0.605368im 0.958095+0.206997im 0.123812+0.541103im -0.738487+0.333007im -1.32277-0.27992im -1.46311-1.00807im -1.21287-1.54739im -0.799262-1.72811im -0.487362-1.57483im -0.455091-1.25732im -0.741344-0.993681im -1.25664-0.965799im -1.82185-1.26631im -2.21663-1.86893im -2.24503-2.61925im -1.81619-3.27032im -0.996652-3.57269im 0.00473669-3.37546im 0.906467-2.68569im 1.44455-1.67001im]
,[-6.05477+9.15928im -2.92805+10.582im 0.485278+10.9689im 3.85111+10.2821im 6.83996+8.5888im 9.15928+6.05477im 10.582+2.92805im 10.9689-0.485278im 10.2821-3.85111im 8.5888-6.83996im 6.05477-9.15928im 2.92805-10.582im -0.485278-10.9689im -3.85111-10.2821im -6.83996-8.5888im -9.15928-6.05477im -10.582-2.92805im -10.9689+0.485278im -10.2821+3.85111im -8.5888+6.83996im; -1.85229+10.2583im 0.125939+10.0823im 1.65825+9.72805im 3.02163+9.33267im 4.46866+8.81454im 6.11648+7.95984im 7.9025+6.51552im 9.57352+4.27158im 10.6959+1.1526im 10.7169-2.66578im 9.13052-6.65172im 5.75145-9.93518im 0.963961-11.551im -4.25862-10.8537im -8.66404-7.87352im -11.2267-3.36423im -11.5572+1.50995im -9.98569+5.66294im -7.31158+8.47201im -4.40008+9.88433im; 2.32966+9.42276im 2.90401+8.58528im 2.69771+8.27122im 2.41763+8.40792im 2.57174+8.66968im 3.39564+8.71228im 4.91768+8.22935im 6.98437+6.92317im 9.19164+4.49905im 10.7563+0.780573im 10.5653-3.91931im 7.72874-8.44848im 2.38227-11.0803im -3.99127-10.4541im -9.1787-6.52537im -11.4405-0.695218im -10.3918+4.98253im -7.01941+8.89024im -2.95495+10.5135im 0.395107+10.3614im; 5.49062+7.08307im 5.11083+6.5063im 3.78307+6.77099im 2.44312+7.46082im 1.70405+8.09974im 1.81853+8.40605im 2.83353+8.21762im 4.71836+7.37907im 7.26585+5.60874im 9.73579+2.493im 10.6645-1.99877im 8.5916-6.75894im 3.37442-9.68142im -3.19291-9.01066im -8.30866-4.77566im -9.94985+1.1705im -7.91714+6.37193im -3.64795+9.18597im 0.860986+9.5092im 4.12675+8.37315im; 7.22412+4.17167im 6.57231+4.34252im 4.83524+5.29677im 3.00893+6.36361im 1.79323+7.10101im 1.45678+7.36378im 2.01696+7.11406im 3.51693+6.36654im 5.92561+4.94878im 8.59626+2.45252im 10.0008-1.26968im 8.51171-5.33284im 3.86572-7.75216im -2.0734-6.89915im -6.4878-3.00572im -7.5591+2.00388im -5.31414+5.86753im -1.19521+7.29844im 3.00733+6.59293im 6.04548+5.10292im; 7.68445+1.47502im 7.27835+2.39481im 5.64459+3.86568im 3.74469+5.08031im 2.3759+5.73246im 1.82336+5.83397im 2.08756+5.41418im 3.24326+4.55491im 5.30984+3.213im 7.69939+1.18895im 9.03165-1.53379im 7.90794-4.31362im 4.1157-5.69674im -0.712463-4.62099im -4.23839-1.5051im -5.06215+2.04657im -3.29416+4.34303im -0.0300219+4.5657im 3.49157+3.23854im 6.33615+1.80823im; 7.19303-0.570016im 7.24467+0.814603im 5.97234+2.51897im 4.23478+3.68909im 2.87922+4.12406im 2.24873+3.96792im 2.36568+3.31865im 3.29102+2.27606im 4.98074+0.930567im 6.90681-0.636702im 7.97693-2.27709im 7.17668-3.57541im 4.41031-3.79126im 0.830211-2.55616im -1.93561-0.37611im -2.8617+1.67763im -1.95045+2.59107im 0.197472+1.9669im 2.93443+0.426366im 5.56805-0.733088im; 5.91623-1.7095im 6.34813-0.259612im 5.52823+1.34498im 4.09749+2.32072im 2.83516+2.47207im 2.18118+1.98769im 2.24191+1.0704im 3.02492-0.106705im 4.39591-1.33057im 5.91086-2.33402im 6.81313-2.90305im 6.44273-2.88759im 4.73381-2.17793im 2.30921-0.910476im 0.129227+0.432054im -1.05343+1.26404im -1.03421+1.1553im 0.0635849+0.0774827im 2.00228-1.34476im 4.23862-2.14238im; 3.9379-1.77683im 4.44186-0.675618im 4.0173+0.476719im 3.01398+1.10376im 1.9985+0.992059im 1.42103+0.27258im 1.47752-0.786439im 2.1598-1.90524im 3.29831-2.79855im 4.54519-3.19518im 5.41629-2.95136im 5.50112-2.13123im 4.6906-0.968832im 3.22474+0.19088im 1.58417+0.96663im 0.286035+1.08017im -0.305234+0.466316im -0.0127989-0.651365im 1.10377-1.74274im 2.63825-2.21163im; 1.45027-0.844732im 1.68234-0.438207im 1.50331-0.0300361im 1.03215+0.101834im 0.530564-0.177733im 0.268351-0.817607im 0.413718-1.62702im 0.988208-2.35709im 1.87145-2.77413im 2.83284-2.72152im 3.59225-2.17278im 3.91054-1.25277im 3.67653-0.204476im 2.94852+0.686521im 1.93736+1.18077im 0.940967+1.16338im 0.249812+0.689672im 0.0478472-0.0214697im 0.334226-0.661207im 0.907742-0.964745im])

Random.seed!(1234)

include("est_doa.jl")
include("ideal_manifold.jl")
include("real_manifold.jl")
include("pattern.jl")
include("filter.jl")
include("manifold.jl")


text:
using ZipFile

mutable struct Archive <: AbstractDict{AbstractString,Any}
    io::IO
    reader
    writer
    cache::Dict
    cache_is_active::Bool
end

# Create Archive interface for "io".
# Try to create a Reader, but don't read anything yet.
# If the archive is being newly created, "reader" will be "nothing".

function Archive(io::IO)

    reader = nothing
    cache = Dict()
    try
        reader = ZipFile.Reader(io, false)
        cache = Dict([Pair(f.name, "") for f in reader.files])
    catch ex
    end
    Archive(io, reader, nothing, cache, false)
end

# Open a ZIP Archive from io, buffer or file.

open_zip(io::IO) = Archive(io)
open_zip(data::Array{UInt8,1}) = Archive(IOBuffer(data, read=true, write=true))
open_zip(filename::AbstractString) = Archive(Base.open(filename, "a+"))
open_zip(f::Function, args...) = with_close(f, open_zip(args...))

with_close(f::Function, io) = try f(io) finally close(io) end

function Base.close(z::Archive)

    # Write out cached files...
    if z.cache_is_active
        z.cache_is_active = false
        for (n,v) in z.cache
            z[n] = v
        end
    end

    # Close reader, writer and io...
    z.reader == nothing || close(z.reader)
    z.writer == nothing || close(z.writer)
    close(z.io)
end

# Read file from ZIP using AbstractDict syntax: data = z[filename].

function Base.get(z::Archive, filename::AbstractString, default=nothing)

    # In read/write mode, read from cache...
    if z.cache_is_active
        return get(z.cache, filename, default)
    end

    # Reading with no Reader!
    # Close the Writer and create a new Reader...
    if z.reader == nothing
        @assert z.writer != nothing
        close(z.writer)
        z.writer = nothing
        seek(z.io,0)
        z.reader = ZipFile.Reader(z.io, false)
    end

    # Search Reader file list for "filename"...
    for f in z.reader.files
        if f.name == filename
            rewind(f)
            return readfile(f)
        end
    end

    return default
end

function rewind(f::ZipFile.ReadableFile)
    f._datapos = -1
    f._currentcrc32 = 0
    f._pos = 0
    f._zpos = 0
end

# Add files to ZIP using AbstractDict syntax: z[filename] = data.

function Base.setindex!(z::Archive, data, filename::AbstractString)

    # If there is an active reader, then setindex!() is writing to a
    # ZIP Archive that already has content.
    # Load all the existsing content into the cache then close the Reader.
    # The cached content will be written out to the new file later in close().
    if z.reader != nothing
        @assert z.writer == nothing
        z.cache = Dict(collect(z))
        z.cache_is_active = true
        close(z.reader)
        z.reader = nothing
        truncate(z.io, 0)
    end

    # In read/write mode, write to the cache...
    if z.cache_is_active
        return setindex!(z.cache, data, filename)
    end

    # Create a writer as needed...
    if z.writer == nothing
        z.writer = ZipFile.Writer(z.io, false)
    end

    # Write "data" for "filename" to Zip Archive...
    with_close(ZipFile.addfile(z.writer, filename, method=ZipFile.Deflate)) do io
        write(io, data)
    end

    # Store "filename" in cache so that keys() always has a full list of
    # the ZIP Archive's content...
    setindex!(z.cache, "", filename)

    return data
end

# Read files from ZIP using iterator syntax.
# The iterator wraps the z.cache iterator. However, unless mixed read/write
# calls have occured, the cache holds only filenames, so get(z, filename) is
# called to read the data from the archive.

Base.eltype(::Type{Archive}) =
    Tuple{AbstractString,Union{String,Vector{UInt8},AbstractString}}

Base.keys(z::Archive) = keys(z.cache)
Base.length(z::Archive) = length(z.cache)

function Base.iterate(z::Archive, state = nothing)
    i = state == nothing ? iterate(z.cache) :
                           iterate(z.cache, state)
    if i == nothing
        return nothing
    end
    ((filename, data), state) = i
    if basename(filename) == ""
        return iterate(z, state)
    end
    if data == ""
        data = get(z, filename)
    end
    ((filename, data), state)
end

# Read entire file...

function readfile(io::ZipFile.ReadableFile)
     b = read(io)
     return isvalid(String, b)  ? String(b)  : b
end

# Extract ZIP archive to "outputpath".
# Based on fhs/ZipFile.jl#16, thanks @timholy.

function unzip(archive, outputpath::AbstractString=pwd())
    open_zip(archive) do file
        for (filename, data) in file
            filename = joinpath(outputpath, filename)
            mkpath_write(filename, data)
        end
    end
end

# Write "data" to "filename" (creating path as needed).
function mkpath_write(filename::AbstractString, data)
    mkpath(dirname(filename))
    write(filename, data)
end

# Write content of "dict" to "io" in ZIP format.

function create_zip(io::IO, dict::T) where T <: AbstractDict

    open_zip(io) do z
        for (filename, data) in dict
            z[string(filename)] = data
        end
    end
    nothing
end

# Write to ZIP format from (filename, data) tuples.

create_zip(io::IO, files::Array{T}) where T <: Tuple = create_zip(io, files...)

# Write "files" and "data" to ZIP format.

create_zip(io::IO, files::Array, data::Array) = create_zip(io, zip(files, data)...)

# Write to ZIP format from filenames.

function create_zip(io::IO, files::Array)
    create_zip(io::IO, files, map(read, files))
end

# Write to ZIP format from filename => data pairs.

create_zip(io::IO, args...) = create_zip(io::IO, Dict(args))

# Write ZIP Archive to "filename".

function create_zip(filename::AbstractString, args...)
    create_zip(Base.open(filename, "w"), args...)
end

# Use temporary memory buffer if "filename" or "io" are not provided.

function create_zip(arg, args...)

    buf = UInt8[]
    with_close(IOBuffer(buf, read=true, write=true)) do io
        create_zip(io, arg, args...)
    end
    buf
end


text:
export @code_yao

function code_yao end

"""
    @code_yao <generic circuit call>

Evaluates the arguments to the function call, determines their types, and
calls `code_yao` on the resulting expression.
"""
macro code_yao(ex)
    (ex isa Expr) && (ex.head === :call) || error("expect a generic circuit call")
    return IRTools.xcall(YaoLang, :code_yao, ex.args...) |> esc
end


text:
info("Loading simulation framework")

packages = [:StatsBase,
            :Distributions,
            :DataFrames,
            :HypothesisTests,
            :IterTools,
            :DocStringExtensions,
            :Combinatorics,
            :DataStructures]

for package in packages
    eval(:(using $package))
    eval(:(@everywhere using $package))
end

# Load all simulations files on all workers
@everywhere function include_all(curr_dir)
    filenames = ["common.jl", "utils.jl", "library.jl", "transfection.jl",
                 "selection.jl", "sequencing.jl", "processing.jl",
                 "designs.jl"]
    for filename in filenames
        include(joinpath(curr_dir, filename))
    end
end
curr_dir = Base.source_dir()
@eval @everywhere include_all($curr_dir)


text:
## real data

include("loadall.jl")

cmagi=readcore("data/magia.cnf")
printcore(cmagi)

cd001=readcore("data/data001.cnf")
printcore(cd001)

cd002=readcore("data/data002.cnf")
printcore(cd002)

ctime=readcore("data/time.cnf")
printcore(ctime)

## rename steps
c6=clause2of(:C6, cd001)
r11=rename_clause(:R11, c6.vars, c6.body)
r11.cid
r11.vars
r11.body

## readclause from string
cc=readcore(IOBuffer("[x].[+P(x)]\n[].[-Q(a)]"))
printcore(cc)

## read entire file and create core

dd1=read("data/data001.cnf", String)
cc1=readcore(IOBuffer(dd1))
printcore(cc1)

#dd1 is
sd1 = "@ 1st example\nGoal\n[y].[-Q(a,y)]\n [x,y].[-Q(x,y)]\n\nFact\n[y].[+P(a,y)]\n[y].[+P(b,y)]\n[x].[+R(x,x)]\n[x].[+R(a,c)]\n\n\nTheory\n[x,y].[-P(x,y),+Q(x,y),-R(x,y)]\n[x,y].[-P(x,f(y)),+Q(x,y),-R(x,y)]\n"

sc1=readcore(IOBuffer(sd1))
printcore(sc1)

# templates
println("make all templates")
tmpl = alltemplateof(cd001)
printcore(cd001)

printtemplates0(cd001.level0, cd001)
printtemplates1(tmpl, cd001)

# resolution
print("\nstep1 R1 = <L1,L6>")
printclause(:C2, cd001)
printclause(:C7, cd001)
r1= dvc_resolution(:L1, :L6, cd001)
printclause(:R1, cd001)

print("\n\nstep1 R2 = <L7_R1, L2>")
printclause(:C1, cd001)
r2= dvc_resolution(:L7_R1, :L2, cd001)
printclause(:R2, cd001)

println("\n\n final core")
printcore(cd001)

println(proofcof(:R2, cd001))

itemp1 = alltemplateof(cd001)
applytemp(:L1, cd001)

itemp2 = alltemplateof(cd002)

goal1 = lidsof(:C1, cd002)
gs1 = []
for g1 in goal1
 push!(gs1, applytemp(g1, cd002))
end

#### dostepagoal のサンプル

##### friend3
cf03=readcore("data/friend3.cnf")
printcore(cf03)

tf03=alltemplateof(cf03)
tnf=tf03[Symbol("-F")]

g0 = [lidsof(:C1, cf03)]
g1 = dostep1goals(g0, cf03)
g2 = dostep1goals(g1, cf03)
g3 = dostep1goals(g2, cf03)

conds = contradictionsof(cf03)

printaproof1(:R20, cf03)
printaproof0(:R20, cf03)

tpr=templateof(:+, :R, cd002)
 g0=[:L12]
 g1=dostepagoal(g0, cd002)
 printaproof0(:R3, cd002)
 printaproof0(:R4, cd002)
 printaproof1(:R3, cd002)

cd010=readcore("data/data010.cnf")
printcore(cd010)
td010=alltemplateof(cd010)
tnp=td010[Symbol("-P")]
g0=[[:L7]]
g1=dostepagoal(g0[1], cd010)

function doit(cnf)
 cdx=readcore(cnf)
# printcore(cdx)
 tdx=alltemplateof(cdx)
 g0=[lidsof(:C1, cdx)]
 #gn=dostepgoals(g0, cdx)
 gn=dostepgoals1(g0, cdx)
 return cdx,tdx,g0,gn
end
@testset "data011" begin
 cdx,td,g0,g1=doit("data/data011.cnf")
 g2=dostepgoals1(g1, cdx)
 g3=dostepgoals1(g2, cdx)
 g4=dostepgoals1(g3, cdx)
 @test length(g3[1]) == 4
 @test_skip isempty(g4)
end
@testset "data012" begin
 cdx,td,g0,g1=doit("data/data012.cnf")
 g2=dostepgoals1(g1, cdx)
 g3=dostepgoals1(g2, cdx)
 g4=dostepgoals1(g3, cdx)
 @test length(g3[1]) == 4
 @test_skip isempty(g4)
end

@testset "data013" begin
 cdx,td,g0,g1=doit("data/data013.cnf")
 g2=dostepgoals1(g1, cdx)
 g3=dostepgoals1(g2, cdx)
 g4=dostepgoals1(g3, cdx)
 @test length(g3) == 2
 @test length(g3[1]) == 4
 @test length(g3[2]) == 4
 @test_skip isempty(g4)
end

@testset "resolvent was satisfiable" begin
 cdx,td,g0,g1=doit("data/data014.cnf")
 g2=dostepgoals1(g1, cdx)
 g3=dostepgoals1(g2, cdx)
 @test length(g1[1]) == 2
 @test length(g2[1]) == 3
 @test length(g3[1]) == 4
 cf2=clause2of(:R3,cdx)
 @test satisfiable(cf2.vars, cf2.body)
end

 cdx,td,g0,g1=doit("data/data010.cnf")
 g2=dostep1goals(g1, cdx)
 g3=dostep1goals(g2, cdx)
 g4=dostep1goals(g3, cdx)

r11,c11 = simpleprover("data/data011.cnf", 5, 1)
r12,c12 = simpleprover("data/data012.cnf", 5, 1)
r13,c13 = simpleprover("data/data013.cnf", 5, 1)
r14,c14 = simpleprover("data/data014.cnf", 5, 1)
r15,c15 = simpleprover("data/data015.cnf", 5, 1)
r16,c16 = simpleprover("data/data016.cnf", 5, 1)
r17,c17 = simpleprover("data/data017.cnf", 5, 1)

r10,c10 = simpleprover("data/data010.cnf", 5, 1)
printaproof1(r10[1], c10)
printaproof0(r10[1], c10)

rm,cm = simpleprover("data/magia.cnf", 5, 1)
printaproof1(rm[1], cm)
printaproof0(rm[1], cm)

### estimate cnf

r3, c3 = simpleprover("data/data003.cnf", 10, 3)
atl=alltemplateof(c3)
printclauses(c3)
printaproof1(:R1, c3)

tk,ck=simpleprover("data/kuukai.cnf",5,1)
printaproof1(:R2,ck)
tk2,ck2=simpleprover("data/kuukai2.cnf",5,1)
printaproof1(:R2,ck2)

ted,ced=simpleprover("data/everyonedie.cnf",8,1)
printproofs1(ced)

tt2,ct2=simpleprover("data/time2.cnf",6,1)
printproofs1(ct2)

# (a) ok but not (c) maybe loop check
to1,ct1=simpleprover("data/to1.cnf",10,1);printproofs1(ct1)

# ofcouse function z() can't be found
to1,ct1=simpleprover("data/to1.cnf",10,1);printproofs1(ct1)
to2,ct2=simpleprover("data/to2.cnf",10,1);printproofs1(ct2)
to3,ct3=simpleprover("data/to3.cnf",10,1);printproofs1(ct3)

td1,cd1=simpleprover("data/db1.cnf",7,2);printproofs1(cd1)

tq1,cq1=simpleprover("data/20Q01.cnf",20,2);printproofs1(cq1)

# friends law
tf7,cf7=simpleprover("data/friend7.cnf",3,1);printproofs1(cf7)
tf8,cf8=simpleprover("data/friend8.cnf",3,1);printproofs1(cf8)

## Before prooving
cdop001, mdop001=pairmakefromcore("data/dop001.cnf")
printpvms(mdop001, cdop001)

chis001, mhis001=pairmakefromcore("data/his001.cnf")
printpvms(mhis001, chis001)

## After proving
rdop001,cdop001=simpleprover("data/dop001.cnf",20,5)
ccdop001, mdop001=pairmakefromcore(cdop001)
# ccdop001 == cdop001
printpvms(mdop001, cdop001)
#printatrace1(:R9, varsof(:C1, cdop001), cdop001)
#inf = traceof(cdop001)
#inf[1]
#inf[2]

max_stars_repo_name: sazare/cheapViews

max_issues_repo_name: sazare/cheapViews

max_forks_repo_name: sazare/cheapViews


text:
using SafeTestsets

@safetestset "ProspectTheory" begin
    # test values based on http://psych.fullerton.edu/mbirnbaum/calculators/cpt_calculator.htm
    using Test, UtilityModels
    import UtilityModels: compute_weights
    α = .8; β = .9; γg = .6; γl =.7; λ = 2.25
    model = ProspectTheory(;α, β, γg, γl, λ)
    p = [.3,.2,.3,.2]
    v = [10.0,3.0,-2.0,-1.0]
    gamble = Gamble(;p, v)
    eu = mean(model, gamble)
    @test eu ≈ .5672 atol = 1e-4
    ω = compute_weights(model, gamble)
    @test ω ≈ [0.1293,0.3281,0.0992,0.3165] atol = 1e-4

    α = 1.2; β = 1.5; γg = .8; γl = .9; λ = 1.5
    model = ProspectTheory(;α, β, γg, γl, λ)
    p = [.1,.2,.5,.2]
    v = [1.0,3.0,-5.0,-2.0]
    gamble = Gamble(;p, v)
    eu = mean(model, gamble)
    @test eu ≈ -8.1017 atol = 1e-4
    ω = compute_weights(model, gamble)
    @test ω ≈ [0.1811,0.4962,0.0848,0.2415] atol = 1e-4
end

@safetestset "TAX" begin
    # tested against http://psych.fullerton.edu/mbirnbaum/calculators/taxcalculator.htm
    # using gambles from Birnbaum 2008
    using Test, UtilityModels

    model = TAX()
    p = [.25,.25,.50]
    v = [100.0,0.0,-50.0]
    gamble = Gamble(;p, v)
    eu = mean(model, gamble)
    @test eu ≈ -15.5125 atol = 1e-4

    model = TAX()
    p = [.80,.10,.10]
    v = [110.0,44.0,40.0]
    gamble = Gamble(;p, v)
    eu = mean(model, gamble)
    @test eu ≈ 65.02513599372996 atol = 1e-8

    model = TAX()
    p = [.05,.05,.90]
    v = [96.0,12.0,3.0]
    gamble = Gamble(;p, v)
    eu = mean(model, gamble)
    @test eu ≈ 8.803653482548164 atol = 1e-8

    using Test, UtilityModels
    δ = 1.0; β = .9; γ = .70
    model = TAX(;δ, β, γ)
    p = [.05,.05,.90]
    v = [96.0,12.0,3.0]
    gamble = Gamble(;p, v)
    eu = mean(model, gamble)
    # calculator uses certainty equivalent
    @test (eu)^(1/β) ≈ 33.567163255247856 atol = 1e-8
end

@safetestset "ExpectedUtility" begin
    using Test, UtilityModels
    α = 1.0
    model = ExpectedUtility(α)
    p = [.3,.2,.3,.2]
    v = [10.0,3.0,-2.0,-1.0]
    gamble = Gamble(;p, v)
    eu = mean(model, gamble)
    @test eu ≈ p'*v atol = 1e-4

    α = .8
    model = ExpectedUtility(α)
    p = [.3,.2,.3,.2]
    v = [10.0,3.0,-2.0,-1.0]
    gamble = Gamble(;p, v)
    eu = mean(model, gamble)
    @test eu ≈ (sign.(v).*abs.(v).^α)'*p atol = 1e-4
end


text:
import SeisIO.Formats: formats, FmtVer, FormatDesc, HistVec
printstyled("  formats()\n", color=:light_green)

Fake_fmt = FormatDesc(
  "Fake data format",
  "\"goat-c\"",
  "Two guys running a startup from a taco truck, Mountain View, California, USA",
  "https://www.youtube.com/watch?v=TMZi25Pq3T8",
  "careers@linkedin.com",
  HistVec(),
  [ "much like SEG Y, everything is in XML for no reason",
    "still a better idea than SEED",
    "abandoned 2004-01-14. (RIP)"],
  [ "Mountain View, CA",
    "Christmas Island"],
  ["https://lmgtfy.com/?q=goatse"],
  0xff
  )
Fake_fmt.ver = [ FmtVer("1.0", "1999-01-01", false); FmtVer() ]
formats["Fake"] = Fake_fmt
@test formats["Fake"].docs ==  ["https://lmgtfy.com/?q=goatse"]
@test formats["Fake"].status ==  0xff
delete!(formats, "Fake")

Fake_fmt_2 = FormatDesc()
formats["Fake2"] = Fake_fmt_2
@test formats["Fake2"].docs ==  []
@test formats["Fake2"].status ==  0x00
delete!(formats, "Fake2")

redirect_stdout(out) do
  show(formats["ah1"])
  show(formats["sac"])
  show(formats["suds"])
  show(formats["uw"])
end


text:
"""
Return stuff stored in `PoissonExpt` after using `mod!`.
"""
function Base.getindex(pa::ParamExpt, s::Symbol)
	@assert s in [:data]
	if(s==:data)
		return pa.data
	end
end


text:
# This file was generated by the Julia Swagger Code Generator
# Do not modify this file directly. Modify the swagger specification instead.

@doc raw"""ServiceAccount binds together: * a name, understood by users, and perhaps by peripheral systems, for an identity * a principal that can be authenticated and authorized * a set of secrets

    IoK8sApiCoreV1ServiceAccount(;
        apiVersion=nothing,
        automountServiceAccountToken=nothing,
        imagePullSecrets=nothing,
        kind=nothing,
        metadata=nothing,
        secrets=nothing,
    )

    - apiVersion::String : APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources
    - automountServiceAccountToken::Bool : AutomountServiceAccountToken indicates whether pods running as this service account should have an API token automatically mounted. Can be overridden at the pod level.
    - imagePullSecrets::Vector{IoK8sApiCoreV1LocalObjectReference} : ImagePullSecrets is a list of references to secrets in the same namespace to use for pulling any images in pods that reference this ServiceAccount. ImagePullSecrets are distinct from Secrets because Secrets can be mounted in the pod, but ImagePullSecrets are only accessed by the kubelet. More info: https://kubernetes.io/docs/concepts/containers/images/#specifying-imagepullsecrets-on-a-pod
    - kind::String : Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
    - metadata::IoK8sApimachineryPkgApisMetaV1ObjectMeta : Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
    - secrets::Vector{IoK8sApiCoreV1ObjectReference} : Secrets is the list of secrets allowed to be used by pods running using this ServiceAccount. More info: https://kubernetes.io/docs/concepts/configuration/secret
"""
mutable struct IoK8sApiCoreV1ServiceAccount <: SwaggerModel
    apiVersion::Any # spec type: Union{ Nothing, String } # spec name: apiVersion
    automountServiceAccountToken::Any # spec type: Union{ Nothing, Bool } # spec name: automountServiceAccountToken
    imagePullSecrets::Any # spec type: Union{ Nothing, Vector{IoK8sApiCoreV1LocalObjectReference} } # spec name: imagePullSecrets
    kind::Any # spec type: Union{ Nothing, String } # spec name: kind
    metadata::Any # spec type: Union{ Nothing, IoK8sApimachineryPkgApisMetaV1ObjectMeta } # spec name: metadata
    secrets::Any # spec type: Union{ Nothing, Vector{IoK8sApiCoreV1ObjectReference} } # spec name: secrets

    function IoK8sApiCoreV1ServiceAccount(;apiVersion=nothing, automountServiceAccountToken=nothing, imagePullSecrets=nothing, kind=nothing, metadata=nothing, secrets=nothing)
        o = new()
        validate_property(IoK8sApiCoreV1ServiceAccount, Symbol("apiVersion"), apiVersion)
        setfield!(o, Symbol("apiVersion"), apiVersion)
        validate_property(IoK8sApiCoreV1ServiceAccount, Symbol("automountServiceAccountToken"), automountServiceAccountToken)
        setfield!(o, Symbol("automountServiceAccountToken"), automountServiceAccountToken)
        validate_property(IoK8sApiCoreV1ServiceAccount, Symbol("imagePullSecrets"), imagePullSecrets)
        setfield!(o, Symbol("imagePullSecrets"), imagePullSecrets)
        validate_property(IoK8sApiCoreV1ServiceAccount, Symbol("kind"), kind)
        setfield!(o, Symbol("kind"), kind)
        validate_property(IoK8sApiCoreV1ServiceAccount, Symbol("metadata"), metadata)
        setfield!(o, Symbol("metadata"), metadata)
        validate_property(IoK8sApiCoreV1ServiceAccount, Symbol("secrets"), secrets)
        setfield!(o, Symbol("secrets"), secrets)
        o
    end
end # type IoK8sApiCoreV1ServiceAccount

const _property_map_IoK8sApiCoreV1ServiceAccount = Dict{Symbol,Symbol}(Symbol("apiVersion")=>Symbol("apiVersion"), Symbol("automountServiceAccountToken")=>Symbol("automountServiceAccountToken"), Symbol("imagePullSecrets")=>Symbol("imagePullSecrets"), Symbol("kind")=>Symbol("kind"), Symbol("metadata")=>Symbol("metadata"), Symbol("secrets")=>Symbol("secrets"))
const _property_types_IoK8sApiCoreV1ServiceAccount = Dict{Symbol,String}(Symbol("apiVersion")=>"String", Symbol("automountServiceAccountToken")=>"Bool", Symbol("imagePullSecrets")=>"Vector{IoK8sApiCoreV1LocalObjectReference}", Symbol("kind")=>"String", Symbol("metadata")=>"IoK8sApimachineryPkgApisMetaV1ObjectMeta", Symbol("secrets")=>"Vector{IoK8sApiCoreV1ObjectReference}")
Base.propertynames(::Type{ IoK8sApiCoreV1ServiceAccount }) = collect(keys(_property_map_IoK8sApiCoreV1ServiceAccount))
Swagger.property_type(::Type{ IoK8sApiCoreV1ServiceAccount }, name::Symbol) = Union{Nothing,eval(Base.Meta.parse(_property_types_IoK8sApiCoreV1ServiceAccount[name]))}
Swagger.field_name(::Type{ IoK8sApiCoreV1ServiceAccount }, property_name::Symbol) =  _property_map_IoK8sApiCoreV1ServiceAccount[property_name]

function check_required(o::IoK8sApiCoreV1ServiceAccount)
    true
end

function validate_property(::Type{ IoK8sApiCoreV1ServiceAccount }, name::Symbol, val)
end