text:
using CornerPoints

function transpack(xs)
  n = (unique ∘ map)(length, xs)
  @assert (isone ∘ length)(n) # all vectors inside xs have the same length
  n = n[1] # convert from size one array to scalar
  ys = []
  for i = 1:n
    push!(ys, map(a->a[i], xs))
  end
  ys
end

# st: set of tuples
# ta: tuple of arrays
# given Set{(1, 2), (3, 4)} and ([1, 3], [2, 4]) it will give true, i.e., it
# checks if the set of tuples and the tuple of arrays store the same data,
# disregarding the order between the elements themselves (the set will be
# always ordered and the ta can be any permutation of the same elements).
function same(dt, ta)
  stta = Set(transpack(ta))
  dt == stta
end

@testset "CornerPoints" begin
  @testset "compute_free_cps" begin
    LWH = (10, 20, 30)
    @testset "single box smaller than container in all dimensions" begin
      xyzpqr = ([1], [1], [1], [5], [10], [15])
      answer = Set([
        (1,  1, 16, 1, 1, 1, 2, 3, 1),
        (1, 11,  1, 1, 1, 1, 2, 1, 4),
        (6,  1,  1, 1, 1, 1, 1, 3, 4)
      ])
      @test same(answer, compute_free_cps(xyzpqr, LWH))
    end
    @testset "single box using all space in one dimension" begin
      xyzpqr = ([1], [1], [1], [10], [10], [15])
      answer = Set([
        (1,  1, 16, 1, 1, 1, 2, 3, 1),
        (1, 11,  1, 1, 1, 1, 2, 1, 4)
      ])
      @test same(answer, compute_free_cps(xyzpqr, LWH))
    end
    @testset "single box using all space in all dimensions" begin
      xyzpqr = ([1], [1], [1], [10], [20], [30])
      answer = Set()
      @test same(answer, compute_free_cps(xyzpqr, LWH))
    end
    @testset "single box using all space in all dimensions" begin
      xyzpqr = ([1], [1], [1], [10], [20], [30])
      answer = Set()
      @test same(answer, compute_free_cps(xyzpqr, LWH))
    end
    @testset "four boxes (all first three cps used) nine cps" begin
      LWH = (10, 20, 30)
      xyzpqr = (
        [ 1, 6,  1,  1],
        [ 1, 1, 11,  1],
        [ 1, 1,  1, 16],
        [ 5, 2,  3,  4],
        [10, 4,  5,  6],
        [15, 7,  8,  9]
      )
      answer = Set([
       (1,  7, 16, 1, 1, 1, 5, 4, 1),
       (5,  1, 16, 1, 1, 1, 4, 6, 1),
       (6,  1,  8, 1, 1, 1, 1, 6, 2),
       (1, 11,  9, 1, 1, 1, 5, 1, 3),
       (1,  1, 25, 1, 1, 1, 5, 6, 4),
       (4, 11,  1, 1, 1, 1, 3, 1, 7),
       (6,  5,  1, 1, 1, 1, 1, 2, 7),
       (1, 16,  1, 1, 1, 1, 5, 3, 7),
       (8,  1,  1, 1, 1, 1, 2, 6, 7)
      ])
      @test same(answer, compute_free_cps(xyzpqr, LWH))
    end
    @testset "tricky, 2 boxes, 3 cps, 1 concrete, 1 not, and 1 both" begin
      xyzpqr = ([1, 6], [1, 1], [1, 1], [5, 5], [10, 10], [15, 20])
      # The first box is half each dimension. The second box fill up the first
      # dimension, leaves the same gap as the first box in the second
      # dimension, and exceeds the first box in the third dimension. This way,
      # the second box display three different behaviours: it has no corner
      # point with height and width one (because lenght was all filled up); the
      # corner point of lenght and height one is the same as the one of the
      # first box but with a min-box-length of six; the corner point with
      # length and width one is above the one of the first box, but has
      # min-box-length of six.
      answer = Set([
        (1, 1, 16, 1, 1, 1, 3, 4, 1)
        (1, 1, 21, 6, 1, 1, 3, 4, 2)
        (1, 11, 1, 1, 1, 1, 3, 1, 5)
        (1, 11, 1, 6, 1, 1, 3, 2, 5)
      ])

      @test same(answer, compute_free_cps(xyzpqr, LWH))
    end
    @testset "the 'entirely in the air' corner point" begin
      xyzpqr = ([1, 2, 2, 6, 1, 1], [1, 1, 1, 1, 11, 1], [1, 1, 2, 1, 1, 16], [1, 4, 4, 1, 3, 2], [10, 10, 1, 5, 1, 6], [15, 1, 14, 7, 6, 1])
      answer = Set([
        (1, 1, 17, 1, 1, 1, 7, 8, 6),
        (1, 7, 16, 1, 1, 1, 7, 6, 1),
        (1, 11, 7, 1, 1, 1, 7, 1, 5),
        (1, 12, 1, 1, 1, 1, 7, 5, 9),
        (2, 2, 2, 1, 1, 1, 1, 3, 2),
        (2, 2, 7, 1, 10, 1, 1, 3, 5),
        (2, 2, 8, 5, 1, 1, 1, 3, 4),
        (2, 6, 2, 5, 1, 1, 1, 4, 2),
        (2, 6, 7, 5, 6, 1, 1, 4, 5),
        (2, 7, 2, 1, 1, 15, 1, 6, 2),
        (2, 7, 7, 1, 5, 10, 1, 6, 5),
        (3, 1, 16, 1, 1, 1, 6, 8, 3),
        (3, 2, 2, 1, 1, 15, 6, 3, 2),
        (3, 2, 7, 1, 10, 10, 6, 3, 5),
        (3, 2, 8, 4, 1, 9, 6, 3, 4),
        (3, 6, 2, 4, 1, 15, 6, 4, 2),
        (3, 6, 7, 4, 6, 10, 6, 4, 5),
        (4, 2, 2, 1, 10, 1, 5, 3, 2),
        (4, 6, 2, 3, 6, 1, 5, 4, 2),
        (4, 11, 1, 1, 1, 1, 5, 2, 9),
        (6, 1, 8, 1, 1, 1, 3, 8, 4),
        (6, 6, 1, 1, 1, 1, 2, 4, 9),
        (7, 1, 1, 1, 1, 1, 4, 8, 9)
      ])

      @test same(answer, compute_free_cps(xyzpqr, LWH))
    end
  end
end


text:
# Data taken from https://github.com/goedman/Stan.jl/blob/master/Examples/Mamba/EightSchools/schools8.jl

const schools8data = [
  Dict(
    "J" => 8,
    "y" => [28,  8, -3,  7, -1,  1, 18, 12],
    "sigma" => [15, 10, 16, 11,  9, 11, 10, 18],
    "tau" => 25
  )
]

ext: jl


text:
module DeepJulia

export Device,
gpu,
cpu,
to,

# tensor
# here we implement the autograd
# and implement basic operations on Tensors

Tensor,
size,
getindex,
length,
adjoint,
show,
to!,
zerograd!,
backward!,
sum,
+,
-,
*,
/,
broadcasted,

# functional
# here we keep any useful functions
# with implemented gradients

logistic,
logloss,

# loss
# wrapper on losses

Loss,
LogLoss,
MSE,
get_loss,

# modules
# modules for building Neural Networks

NNModule,
LinearLayer,
Activation,
SigmoidActivation,
ModuleList,
forward,
params,

# optim
# optimizers for NNModules

Optimizer,
SGD,
step,

# dataset

Dataset,
length,
batchify,
FashionMNIST,
shuffle!,

# init
# initialization functions

xavier_uniform!,
zero!

include("device.jl")
include("tensor.jl")
include("functional.jl")
include("loss.jl")
include("modules.jl")
include("optim.jl")
include("dataset.jl")
include("init.jl")

end # module

max_stars_repo_name: taraspiotr/DeepJulia

max_issues_repo_name: taraspiotr/DeepJulia

max_forks_repo_name: taraspiotr/DeepJulia


text:
module CreateTableAbilities

import SearchLight.Migrations: create_table, column, primary_key, add_index, drop_table

function up()
  create_table(:abilities) do
    [
      primary_key()
      column(:name, :string, limit = 100)
    ]
  end

  add_index(:abilities, :name)
end

function down()
  drop_table(:abilities)
end

end


text:
using MathOptInterface
const MOI = MathOptInterface

include("scaled_psd_cone_bridge.jl")

import LinearAlgebra

# SeDuMi solves the primal/dual pair
# min c'x,       max b'y
# s.t. Ax = b,   c - A'x ∈ K
#       x ∈ K
# where K is a product of `MOI.Zeros`, `MOI.Nonnegatives`,
# `MOI.SecondOrderCone`, `MOI.RotatedSecondOrderCone` and
# `SeDuMi.ScaledPSDCone`.

MOI.Utilities.@product_of_sets(
    Cones,
    MOI.Zeros,
    MOI.Nonnegatives,
    MOI.SecondOrderCone,
    MOI.RotatedSecondOrderCone,
    ScaledPSDCone,
)

const OptimizerCache = MOI.Utilities.GenericModel{
    Float64,
    MOI.Utilities.ObjectiveContainer{Float64},
    MOI.Utilities.VariablesContainer{Float64},
    MOI.Utilities.MatrixOfConstraints{
        Float64,
        MOI.Utilities.MutableSparseMatrixCSC{
            Float64,
            Int,
            MOI.Utilities.OneBasedIndexing,
        },
        Vector{Float64},
        Cones{Float64},
    },
}

# This wrapper copies the MOI problem to the SeDuMi dual so the natively
# supported supported sets are `VectorAffineFunction`-in-`S` where `S` is one
# of the sets just listed above.

mutable struct Solution
    x::Vector{Float64}
    y::Vector{Float64}
    slack::Vector{Float64}
    objective_value::Float64
    dual_objective_value::Float64
    objective_constant::Float64
    info::Dict{String, Any}
end

mutable struct Optimizer <: MOI.AbstractOptimizer
    cones::Union{Nothing,Cones{Float64}}
    sol::Union{Nothing, Solution}
    silent::Bool
    options::Dict{Symbol, Any}
    function Optimizer(; kwargs...)
        optimizer = new(nothing, nothing, false, Dict{Symbol, Any}())
        if !isempty(kwargs)
            @warn("""Passing optimizer attributes as keyword arguments to
            SeDuMi.Optimizer is deprecated. Use
                MOI.set(model, MOI.RawOptimizerAttribute("key"), value)
            or
                JuMP.set_optimizer_attribute(model, "key", value)
            instead.
            """)
        end
        for (key, value) in kwargs
            MOI.set(optimizer, MOI.RawOptimizerAttribute(String(key)), value)
        end
        return optimizer
    end

end

function MOI.get(::Optimizer, ::MOI.Bridges.ListOfNonstandardBridges)
    return [ScaledPSDConeBridge{Float64}]
end

MOI.get(::Optimizer, ::MOI.SolverName) = "SeDuMi"

function MOI.is_empty(optimizer::Optimizer)
    return optimizer.cones === nothing
end
function MOI.empty!(optimizer::Optimizer)
    optimizer.cones = nothing
    optimizer.sol = nothing
    return
end

###
### MOI.RawOptimizerAttribute
###

function MOI.set(optimizer::Optimizer, param::MOI.RawOptimizerAttribute, value)
    optimizer.options[param.name] = value
end

function MOI.get(optimizer::Optimizer, param::MOI.RawOptimizerAttribute)
    return optimizer.options[param.name]
end

###
### MOI.Silent
###

MOI.supports(::Optimizer, ::MOI.Silent) = true

function MOI.set(optimizer::Optimizer, ::MOI.Silent, value::Bool)
    optimizer.silent = value
end

MOI.get(optimizer::Optimizer, ::MOI.Silent) = optimizer.silent

###
### MOI.AbstractModelAttribute
###

function MOI.supports(
    ::Optimizer,
    ::Union{
        MOI.ObjectiveSense,
        MOI.ObjectiveFunction{MOI.ScalarAffineFunction{Float64}},
    },
)
    return true
end

function MOI.supports_constraint(
    ::Optimizer,
    ::Type{MOI.VectorAffineFunction{Float64}},
    ::Type{<:Union{
        MOI.Zeros,
        MOI.Nonnegatives,
        MOI.SecondOrderCone,
        MOI.RotatedSecondOrderCone,
        ScaledPSDCone,
    }},
)
    return true
end

function _map_sets(f, sets, ::Type{S}) where {S}
    F = MOI.VectorAffineFunction{Float64}
    cis = MOI.get(sets, MOI.ListOfConstraintIndices{F,S}())
    return Int[f(MOI.get(sets, MOI.ConstraintSet(), ci)) for ci in cis]
end

function MOI.optimize!(
    dest::Optimizer,
    src::OptimizerCache,
)
    MOI.empty!(dest)
    index_map = MOI.Utilities.identity_index_map(src)
    Ac = src.constraints
    A = Ac.coefficients

    model_attributes = MOI.get(src, MOI.ListOfModelAttributesSet())
    objective_function_attr =
        MOI.ObjectiveFunction{MOI.ScalarAffineFunction{Float64}}()
    b = zeros(A.n)
    max_sense = MOI.get(src, MOI.ObjectiveSense()) == MOI.MAX_SENSE
    objective_constant = 0.0
    if objective_function_attr in MOI.get(src, MOI.ListOfModelAttributesSet())
        obj = MOI.get(src, objective_function_attr)
        objective_constant = MOI.constant(obj)
        for term in obj.terms
            b[term.variable.value] += (max_sense ? 1 : -1) * term.coefficient
        end
    end

    # If m == n, SeDuMi thinks we give A'.
    # See https://github.com/sqlp/sedumi/issues/42#issuecomment-451300096
    A = SparseMatrixCSC(A.m, A.n, A.colptr, A.rowval, -A.nzval)
    if A.m != A.n
        A = SparseMatrixCSC(A')
    end

    options = dest.options
    if dest.silent
        options = copy(options)
        options[:fid] = 0
    end

    K = Cone(
        Ac.sets.num_rows[1],
        Ac.sets.num_rows[2] - Ac.sets.num_rows[1],
        _map_sets(MOI.dimension, Ac, MOI.SecondOrderCone),
        _map_sets(MOI.dimension, Ac, MOI.RotatedSecondOrderCone),
        _map_sets(MOI.side_dimension, Ac, ScaledPSDCone),
    )

    c = Ac.constants
    x, y, info = sedumi(A, b, c, K; options...)

    dest.cones = deepcopy(Ac.sets)
    objective_value = (max_sense ? 1 : -1) * LinearAlgebra.dot(b, y)
    dual_objective_value = (max_sense ? 1 : -1) * LinearAlgebra.dot(c, x)
    dest.sol = Solution(
        x,
        y,
        c - A' * y,
        objective_value,
        dual_objective_value,
        objective_constant,
        info,
    )
    return index_map, false
end

function MOI.optimize!(dest::Optimizer, src::MOI.ModelLike)
    cache = OptimizerCache()
    index_map = MOI.copy_to(cache, src)
    MOI.optimize!(dest, cache)
    return index_map, false
end

function MOI.get(optimizer::Optimizer, ::MOI.SolveTimeSec)
    return optimizer.sol.info["cpusec"]
end
function MOI.get(optimizer::Optimizer, ::MOI.RawStatusString)
    return string("feasratio = ", optimizer.sol.info["feasratio"],
                  ", pinf = ", optimizer.sol.info["pinf"],
                  ", dinf = ", optimizer.sol.info["dinf"],
                  "numerr = ", optimizer.sol.info["numerr"])
end

# Implements getter for result value and statuses
# SeDuMI returns one of the following values (based on SeDuMi_Guide_11 by Pólik):
# feasratio:  1.0 problem with complementary solution
#            -1.0 strongly infeasible problem
#             between -1.0 and 1.0 nasty problem
# pinf = 1.0 : y is infeasibility certificate => SeDuMi primal/MOI dual is infeasible
# dinf = 1.0 : x is infeasibility certificate => SeDuMi dual/MOI primal is infeasible
# pinf = 0.0 = dinf : x and y are near feasible
# numerr: 0 desired accuracy (specified by pars.eps) is achieved
#         1 reduced accuracy (specified by pars.bigeps) is achieved
#         2 failure due to numerical problems

function MOI.get(optimizer::Optimizer, ::MOI.TerminationStatus)
    if optimizer.sol isa Nothing
        return MOI.OPTIMIZE_NOT_CALLED
    end
    pinf      = optimizer.sol.info["pinf"]
    dinf      = optimizer.sol.info["dinf"]
    numerr    = optimizer.sol.info["numerr"]
    if numerr == 2
        return MOI.NUMERICAL_ERROR
    end
    @assert iszero(numerr) || isone(numerr)
    accurate = iszero(numerr)
    if isone(pinf)
        if accurate
            return MOI.DUAL_INFEASIBLE
        else
            return MOI.ALMOST_DUAL_INFEASIBLE
        end
    end
    if isone(dinf)
        if accurate
            return MOI.INFEASIBLE
        else
            return MOI.ALMOST_INFEASIBLE
        end
    end
    @assert iszero(pinf) && iszero(dinf)
    # TODO when do we return SLOW_PROGRESS ?
    #      Maybe we should use feasratio
    if accurate
        return MOI.OPTIMAL
    else
        return MOI.ALMOST_OPTIMAL
    end
end

function MOI.get(optimizer::Optimizer, attr::MOI.ObjectiveValue)
    MOI.check_result_index_bounds(optimizer, attr)
    value = optimizer.sol.objective_value
    if !MOI.Utilities.is_ray(MOI.get(optimizer, MOI.PrimalStatus()))
        value += optimizer.sol.objective_constant
    end
    return value
end
function MOI.get(optimizer::Optimizer, attr::MOI.DualObjectiveValue)
    MOI.check_result_index_bounds(optimizer, attr)
    value = optimizer.sol.dual_objective_value
    if !MOI.Utilities.is_ray(MOI.get(optimizer, MOI.DualStatus()))
        value += optimizer.sol.objective_constant
    end
    return value
end

function MOI.get(optimizer::Optimizer,
                 attr::Union{MOI.PrimalStatus, MOI.DualStatus})
    if attr.result_index > MOI.get(optimizer, MOI.ResultCount()) || optimizer.sol isa Nothing
        return MOI.NO_SOLUTION
    end
    pinf      = optimizer.sol.info["pinf"]
    dinf      = optimizer.sol.info["dinf"]
    numerr    = optimizer.sol.info["numerr"]
    if numerr == 2
        return MOI.UNKNOWN_RESULT_STATUS
    end
    @assert iszero(numerr) || isone(numerr)
    accurate = iszero(numerr)
    if isone(attr isa MOI.PrimalStatus ? pinf : dinf)
        if accurate
            return MOI.INFEASIBILITY_CERTIFICATE
        else
            return MOI.NEARLY_INFEASIBILITY_CERTIFICATE
        end
    end
    if isone(attr isa MOI.PrimalStatus ? dinf : pinf)
        return MOI.INFEASIBLE_POINT
    end
    @assert iszero(pinf) && iszero(dinf)
    if accurate
        return MOI.FEASIBLE_POINT
    else
        return MOI.NEARLY_FEASIBLE_POINT
    end
end
function MOI.get(optimizer::Optimizer, attr::MOI.VariablePrimal, vi::MOI.VariableIndex)
    MOI.check_result_index_bounds(optimizer, attr)
    return optimizer.sol.y[vi.value]
end
function MOI.get(optimizer::Optimizer, attr::MOI.ConstraintPrimal,
                 ci::MOI.ConstraintIndex)
    MOI.check_result_index_bounds(optimizer, attr)
    return optimizer.sol.slack[MOI.Utilities.rows(optimizer.cones, ci)]
end

function MOI.get(optimizer::Optimizer, attr::MOI.ConstraintDual,
                 ci::MOI.ConstraintIndex)
    MOI.check_result_index_bounds(optimizer, attr)
    return optimizer.sol.x[MOI.Utilities.rows(optimizer.cones, ci)]
end

MOI.get(optimizer::Optimizer, ::MOI.ResultCount) = 1


text:
with(PNG("red-square.png", 100, 100)) do
    ctx = current_context()
    move(0.5, 0.5)
    @test Drawing.has_current_point(ctx) == true
    x, y = Drawing.get_current_point(ctx)
    @test x == 0.5
    @test y == 0.5
end

println("cairo: ok")


text:
module RegistryCI

# import GitCommand

include("AutoMerge/AutoMerge.jl")
include("registry_testing.jl")
include("utils.jl")

end # module


text:
#
# widestrings.jl --
#
# Implement strings of wide-characters for Andor SDK.
#
#-------------------------------------------------------------------------------
#
# This file is part of "AndorCameras.jl" released under the MIT license.
#
# Copyright (C) 2017-2021, Éric Thiébaut.
#

module WideStrings

export
    @L_str,
    WideString,
    trunc!

using Base: @propagate_inbounds, containsnul, axes1, OneTo

"""
    wstr = WideString(src, len=length(src))

converts `src` into a wide-character string of length `len`.  Argument `src`
may be a string, a symbol, a vector of `Char`, or a vector of `Cwchar_t`.

Wide-character strings are immutable (read-only) vectors of characters of type
`Cwchar_t`.  They are NUL-terminated and do not contain other NUL characters
than the final NUL.  They are intended to be passed to functions in external
C-library expecting NUL-terminated strings of `wchar_t` characters.

An exception is thrown if `src` contains a NULL in its first `len` elements.
Call `trunc(WideString,src)` to build a wide-character string from `src` but
that may be truncated at the first NUL character.  If `buf` is an ordinary
vector of wide-character, re-allocation can be avoded by calling
`trunc!(WideString,buf)`.

A wide-character string `wstr` can be converted to an ordinary Julia string by:

    str = String(wstr)

See also: [`@L`], [`trunc!`].

"""
struct WideString <: AbstractVector{Cwchar_t}
    buf::Vector{Cwchar_t}
end

buffer(str::WideString) = str.buf
Base.length(str::WideString) = length(buffer(str)) - 1
Base.size(str::WideString) = (length(str),)
Base.axes1(str::WideString) = Base.OneTo(length(str))
Base.axes(str::WideString) = (Base.axes1(str),)
Base.IndexStyle(::Type{WideString}) = IndexLinear()
Base.cconvert(::Type{Cwstring}, str::WideString) = buffer(str)
Base.unsafe_convert(::Type{Ptr{Cwchar_t}}, str::WideString) =
    pointer(buffer(str))

function Base.show(io::IO, str::WideString)
    @inbounds for c in str
        print(io, Char(c))
    end
end

function Base.show(io::IO, ::MIME"text/plain", str::WideString)
    q = Cwchar_t('"')
    print(io, "L\"")
    @inbounds for c in str
        if c == q
            print(io, "\\\"")
        else
            print(io, Char(c))
        end
    end
    print(io, "\"")
end

@inline Base.getindex(str::WideString, i::Integer) = begin
    buf = buffer(str)
    @boundscheck ((1 ≤ i) & (i < length(buf))) || out_of_range_index(str, i)
    @inbounds buf[i]
end

Base.string(str::WideString) = String(str)

function Base.String(str::WideString)
    buf = Vector{Char}(undef, length(str))
    @inbounds @simd for i in eachindex(buf, str)
        buf[i] = Char(str[i])
    end
    return String(buf)
end

function Base.trunc(::Type{WideString},
                    src::Union{AbstractString,
                               AbstractVector{<:Union{Char,Cwchar_t}}})
    buf = Vector{Cwchar_t}(undef, length(src) + 1)
    len = 0
    @inbounds for c in src
        if c == nul(c)
            resize!(buf, len + 1)
            break
        end
        len += 1
        buf[len] = Cwchar_t(c)
    end
    buf[end] = nul(Cwchar_t)
    return WideString(buf)
end

"""
    trunc!(WideString, buf)

yields a wide-character string truncated at the first NUL found in array `buf`
and that uses `buf` (possibly resized and NUL-terminated) as its storing
buffer.  The caller shall not change `buf` after this call.

"""
function trunc!(::Type{WideString}, buf::Vector{Cwchar_t})
    len = length(buf)
    @inbounds for i in OneTo(len)
        c = buf[i]
        if c == nul(c)
            len = i - 1
            break
        end
    end
    length(buf) == len + 1 || resize!(buf, len + 1)
    buf[end] = nul(Cwchar_t)
    return WideString(buf)
end

nul(x::Union{Char,Cwchar_t}) = nul(typeof(x))
nul(::Type{Char}) = '\0'
nul(::Type{Cwchar_t}) = zero(Cwchar_t)

# Extend convert for building structures.
Base.convert(::Type{String}, x::WideString) = String(x)
Base.convert(::Type{WideString}, x::Union{AbstractString,Symbol}) =
    WideString(x)

WideString(str::WideString) = str

WideString(sym::Symbol) = WideString(string(sym))

# Compared to `transcode(Cwchar_t,str)`, `WideString(str)` adds a final NUL
# character and make sure `str` does not contain any NUL characters.
function WideString(src::Union{AbstractString,
                               AbstractVector{<:Union{Char,Cwchar_t}}})
    return unsafe_WideString(src, length(src))
end

function WideString(src::Union{AbstractString,
                               AbstractVector{<:Union{Char,Cwchar_t}}},
                    len::Integer)
    0 ≤ len ≤ length(src) || throw(ArgumentError("invalid length"))
    return unsafe_WideString(src, Int(len))
end

function unsafe_WideString(src, len::Int)
    buf = Vector{Cwchar_t}(undef, len + 1)
    j = firstindex(src)
    @inbounds for i in 1:len
        c = src[j]
        c == nul(c) &&
            throw(ArgumentError("argument must not contain NULs"))
        buf[i] = Cwchar_t(c)
        j = nextind(src, j)
    end
    buf[end] = nul(Cwchar_t)
    return WideString(buf)
end

"""
    L"text"

yields a wide-character string.

"""
macro L_str(str)
    :(WideString($str))
end

end # module


text:
#
# Copyright (c) 2021 Tobias Thummerer, Lars Mikelsons, Josef Kircher
# Licensed under the MIT license. See LICENSE file in the project root for details.
#

###############
# Prepare FMU #
###############

myFMU = fmiLoad("SpringPendulum1D", ENV["EXPORTINGTOOL"], ENV["EXPORTINGVERSION"])

comp = fmiInstantiate!(myFMU; loggingOn=true)
@test comp != 0

# choose FMU or FMUComponent
fmuStruct = nothing
envFMUSTRUCT = ENV["FMUSTRUCT"]
if envFMUSTRUCT == "FMU"
    fmuStruct = myFMU
elseif envFMUSTRUCT == "FMUCOMPONENT"
    fmuStruct = comp
end
@assert fmuStruct != nothing "Unknown fmuStruct, environment variable `FMUSTRUCT` = `$envFMUSTRUCT`"

@test fmiEnterInitializationMode(fmuStruct) == 0
@test fmiExitInitializationMode(fmuStruct) == 0

@test fmiSetupExperiment(fmuStruct, 0.0) == 0

###########################
# Testing state functions #
###########################

if fmiCanGetSetState(myFMU) && fmiCanSerializeFMUstate(myFMU)
    @test fmiGetReal(fmuStruct, "mass.s") == 0.5
    FMUstate = fmiGetFMUstate(fmuStruct)
    @test typeof(FMUstate) == FMI.fmi2FMUstate
    len = fmiSerializedFMUstateSize(fmuStruct, FMUstate)
    @test len > 0
    serial = fmiSerializeFMUstate(fmuStruct, FMUstate)
    @test length(serial) == len
    @test typeof(serial) == Array{Char,1}

    fmiSetReal(fmuStruct, "mass.s", 10.0)
    FMUstate = fmiGetFMUstate(fmuStruct)
    @test fmiGetReal(fmuStruct, "mass.s") == 10.0

    FMUstate2 = fmiDeSerializeFMUstate(fmuStruct, serial)
    @test typeof(FMUstate2) == FMI.fmi2FMUstate
    fmiSetFMUstate(fmuStruct, FMUstate2)
    @test fmiGetReal(fmuStruct, "mass.s") == 0.5
    fmiSetFMUstate(fmuStruct, FMUstate)
    @test fmiGetReal(fmuStruct, "mass.s") == 10.0
    fmiFreeFMUstate!(fmuStruct, FMUstate)
    fmiFreeFMUstate!(fmuStruct, FMUstate2)
else
    @info "The FMU provided from the tool `$(ENV["EXPORTINGTOOL"])` does not support state get, set, serialization and deserialization. Skipping related tests."
end

############
# Clean up #
############

@test fmiTerminate(myFMU) == 0
fmiUnload(myFMU)


text:
function iri_expansion(active_context, value, document_relative::Bool = false, vocab::Bool = false)
end


text:
"""Accepts rating as a Float64 and then creates a TwoPartCost."""
function TwoPartCost(variable_cost::T, args...) where {T <: VarCostArgs}
    return TwoPartCost(VariableCost(variable_cost), args...)
end

"""Accepts rating as a Float64 and then creates a ThreePartCost."""
function ThreePartCost(variable_cost::T, args...) where {T <: VarCostArgs}
    return ThreePartCost(VariableCost(variable_cost), args...)
end

# FIXME: This function name implies that will return a struct named `PowerLoadPF`
# i.e. `PowerLoadPF` is not a constructor
function PowerLoadPF(
    name::String,
    available::Bool,
    bus::Bus,
    model::Union{Nothing, LoadModels.LoadModel},
    activepower::Float64,
    maxactivepower::Float64,
    power_factor::Float64,
)
    maxreactivepower = maxactivepower * sin(acos(power_factor))
    reactivepower = activepower * sin(acos(power_factor))
    return PowerLoad(
        name,
        available,
        bus,
        model,
        activepower,
        reactivepower,
        maxactivepower,
        maxreactivepower,
    )
end

function PowerLoadPF(::Nothing)
    return PowerLoadPF("init", true, Bus(nothing), nothing, 0.0, 0.0, 1.0)
end

"""Accepts anglelimits as a Float64."""
function Line(
    name,
    available::Bool,
    activepower_flow::Float64,
    reactivepower_flow::Float64,
    arc::Arc,
    r,
    x,
    b,
    rate,
    anglelimits::Float64,
)
    return Line(
        name,
        available,
        activepower_flow,
        reactivepower_flow,
        arc::Arc,
        r,
        x,
        b,
        rate,
        (min = -anglelimits, max = anglelimits),
    )
end

"""Allows construction with bus type specified as a string for legacy code."""
function Bus(
    number,
    name,
    bustype::String,
    angle,
    voltage,
    voltagelimits,
    basevoltage,
    area,
    load_zone;
    ext = Dict{String, Any}(),
)
    return Bus(
        number,
        name,
        get_enum_value(BusTypes.BusType, bustype),
        angle,
        voltage,
        voltagelimits,
        basevoltage,
        area,
        load_zone,
        ext,
        InfrastructureSystemsInternal(),
    )
end

"""Allows construction of a reserve from an iterator."""
function StaticReserve(
    name,
    contributingdevices::IS.FlattenIteratorWrapper,
    timeframe,
    requirement,
    forecasts,
    internal,
)
    return StaticReserve(
        name,
        collect(contributingdevices),
        timeframe,
        requirement,
        forecasts,
        internal,
    )
end


text:
# Gibbs sampling experiments for paper (ESS, parameter recovery)
using Distributions
using StatsBase
using MCMCDiagnostics

include("../dataset.jl")
include("../crp.jl")
include("../geometric_ia.jl")
include("../poisson_ia.jl")
include("../ntl_gibbs.jl")
include("../slice.jl")
include("../evaluation.jl")
include("../gibbs_util.jl")
include("../experiments_util.jl")

###########################################################################
# Experiment settings
###########################################################################
save_output = true
N_train = 1000 # size of sequence for synthetic data
N_test = 2000 # size of total sequence for computing predictive likelihoods

n_iter = 125000 # 50000  # total number of Gibbs iterations to run
n_burn = 25000   # burn-in
n_thin = 1000     # collect every `n_thin` samples

n_rep = 10 # number of sampling experiment repetitions

n_print = 1000 # prints updates every `n_print` iterations

ntl_alpha = 0.75 # -2.0 # "true" value of alpha that will be used to generate data

# set which components to update
gibbs_psi = true            # NTL Ψ paramters
gibbs_alpha = true          # NTL alpha parameter
gibbs_arrival_times = true  # arrival times
gibbs_ia_params = true     # arrival time distribution parameters
gibbs_perm_order = true   # order of blocks in partition/vertices in graph

datasets = ["synthetic crp-coupled","synthetic geometric"]
ia_params = [[1.0], [0.25]] # these correspond to the datasets
arrival_dists = ["crp-coupled","crp-uncoupled","geometric","poisson"]
# arrival_dists = ["geometric","poisson"]

n_ds = size(datasets,1)
n_ad = size(arrival_dists,1)

###########################################################################
# NTL alpha sampling settings
###########################################################################

ntl_gamma_a = 1.
ntl_gamma_b = 10.

# prior is specified as a distribution on (0,Inf);
#   transformation to alpha ∈ (-Inf,1) will be performed during sampling as appropriate
ntl_alpha_prior_dist = Gamma(ntl_gamma_a,ntl_gamma_b)
ntl_alpha_log_prior = x -> logpdf(ntl_alpha_prior_dist,x)

w_alpha = 5.0 # slice sampling "window" parameter

###########################################################################
# Experiment
###########################################################################

# initialize storage
N_data_all = zeros(Int64,n_ds)
K_data_all = zeros(Int64,n_ds)

PP_data_all = []
T_data_all = []
Z_data_all = []
spl_out_all = []

runtimes = zeros(Float64,n_ds,n_ad,n_rep)
ESS_alpha = zeros(Float64,n_ds,n_ad,n_rep)
ESS_logp = zeros(Float64,n_ds,n_ad,n_rep)
ESS_sigma_logd = zeros(Float64,n_ds,n_ad,n_rep)
ESS_T_logd = zeros(Float64,n_ds,n_ad,n_rep)
ESS_slack_logd = zeros(Float64,n_ds,n_ad,n_rep)

sigma_mean_d = zeros(Float64,n_ds,n_ad,n_rep)
sigma_se_d = zeros(Float64,n_ds,n_ad,n_rep)
T_mean_d = zeros(Float64,n_ds,n_ad,n_rep)
alpha_mean_d = zeros(Float64,n_ds,n_ad,n_rep)
alpha_se_d = zeros(Float64,n_ds,n_ad,n_rep)
slack_mean_d = zeros(Float64,n_ds,n_ad,n_rep)
slack_se_d = zeros(Float64,n_ds,n_ad,n_rep)

pred_ll_mean = zeros(Float64,n_ds,n_ad,n_rep)
pred_ll_se = zeros(Float64,n_ds,n_ad,n_rep)

for ds in 1:size(datasets,1)
  ## SET SEED
  srand(0)
  # generate synthetic data
  PP_test,T_test,Z_test = genSynDegrees(datasets[ds],N_test,ntl_alpha,ia_params[ds])
  PP_data_all = [PP_data_all; [PP_test]]
  T_data_all = [T_data_all; [T_test]]
  Z_data_all = [Z_data_all; [Z_test]]

  PP_data = seq2part(Z_test[1:N_train])
  T_data = get_arrivals(Z_test[1:N_train])

  slack_data = cumsum(PP_data)[1:(end-1)] .- T_data[2:end]
  # sort partition if necessary
  if gibbs_perm_order
    PP_sort = sortrows(hcat(PP_data,collect(1:size(PP_data,1))),rev=true)
    # PP_sort_perm = sortperm(PP_data,rev=true)
    # sort ties in ascending order of original order for plotting purposes
    maxdeg = maximum(PP_sort)
    for j in 1:maxdeg
      PP_sort[PP_sort[:,1].==j,2] = sort(PP_sort[PP_sort[:,1].==j,2],rev=false)
    end
    perm_data = PP_sort[:,2]
    PP = PP_sort[:,1]

    K_train = length(PP)
    PP_all_train_sort = PP_test[[perm_data;(K_train+1):end]]

  else
    PP = deepcopy(PP_data)
    perm_data = collect(1:size(PP,1))
  end

  K = size(PP,1)
  N = sum(PP)

  K_data_all[ds] = K
  N_data_all[ds] = N

  for ad in 1:size(arrival_dists,1)
    # set up required sampling functions and control
    ia_prior_params,ia_dist,initialize_arrival_params,update_arrival_params!,lpdf_ia_param_prior,n_ia_params =
        arrivalSamplerSetup(arrival_dists[ad],K,N)

    sampler_control = GibbsSamplerControls(
                        n_iter,n_burn,n_thin,n_print,
                        gibbs_psi,gibbs_alpha,gibbs_arrival_times,gibbs_ia_params,gibbs_perm_order,
                        arrival_dists[ad],ia_dist,ia_prior_params,n_ia_params,initialize_arrival_params,update_arrival_params!,
                        ntl_alpha_log_prior,ntl_alpha_prior_dist,lpdf_ia_param_prior,
                        w_alpha,0.5,[0.5]
                      )

    # run sampler
    println("Running sampler for ",ds," / ",n_ds," datasets; ",ad," / ",n_ad," arrival distributions.")
    for nr in 1:n_rep
      spl_out = GibbsSampler(sampler_control,PP,T_data)
      spl_out_all = [spl_out_all; [spl_out]]
      # process output
      runtimes[ds,ad,nr] = spl_out.t_elapsed
      ESS_alpha[ds,ad,nr] = ess_factor_estimate(spl_out.alpha)[1]
      ESS_logp[ds,ad,nr] = ess_factor_estimate(spl_out.log_joint)[1]

      sigma_d = mean( abs.(PP[spl_out.sigma] .- PP_data), 1 )
      ESS_sigma_logd[ds,ad,nr] = ess_factor_estimate(log.(sigma_d))[1]
      sigma_mean_d[ds,ad,nr] = mean(sigma_d)
      sigma_se_d[ds,ad,nr] = sqrt(var(sigma_d)/length(sigma_d))

      T_d = mean( abs.(spl_out.T .- T_data), 1 )
      ESS_T_logd[ds,ad,nr] = ess_factor_estimate(log.(T_d))[1]
      T_mean_d[ds,ad,nr] = mean(T_d)

      alpha_d = abs.(spl_out.alpha .- ntl_alpha)
      alpha_mean_d[ds,ad,nr] = mean(alpha_d)
      alpha_se_d[ds,ad,nr] = sqrt(var(alpha_d)/length(alpha_d))

      slack_d = mean(abs.(cumsum(PP[spl_out.sigma],1)[1:(end-1),:] .- spl_out.T[2:end,:] .- slack_data), 1)
      ESS_slack_logd[ds,ad,nr] = ess_factor_estimate(log.(slack_d))[1]
      slack_mean_d[ds,ad,nr] = mean(slack_d)
      slack_se_d[ds,ad,nr] = sqrt(var(slack_d)/length(slack_d))

      pred_ll = zeros(Float64,size(spl_out.alpha,1))
      for s in 1:size(spl_out.alpha,1)
        pred_ll[s] = logp_pred_partition(
                      PP[spl_out.sigma[:,s]],PP_all_train_sort[[spl_out.sigma[:,s];(K_train+1):end]],
                      [spl_out.T[:,s];T_test[(K_train+1):end]],
                      spl_out.alpha[s],ia_dist(spl_out.ia_params[:,s]),false,false) # treat as sequence
      end
      pred_ll_mean[ds,ad,nr] = mean(pred_ll)
      pred_ll_se[ds,ad,nr] = sqrt(var(pred_ll)/length(pred_ll))

      println("\n > Finished with ",nr," out of ",n_rep," repetitions.")
    end

  end

  println("\n Finished with ",ds," out of ",n_ds," datasets. \n")

end

######### Save output

if save_output
  using JLD
  using JSON
  using DataStructures

  datetime = Dates.format(now(), "yyyy-mm-dd_HH-MM-SS")
  try
      Base.Filesystem.mkdir("./ess_output")
  catch
      nothing
  end
  dirname = "./ess_output/gibbs_" * datetime * "_"
  fname = "ess_results.jld"
  pathname = dirname * fname

  save(pathname,
      "runtimes",runtimes,
      "ESS_alpha",ESS_alpha,
      "ESS_logp",ESS_logp,
      "ESS_sigma_logd",ESS_sigma_logd,
      "sigma_mean_d",sigma_mean_d,
      "sigma_se_d",sigma_se_d,
      "ESS_T_logd",ESS_T_logd,
      "T_mean_d",T_mean_d,
      "alpha_mean_d",alpha_mean_d,
      "alpha_se_d",alpha_se_d,
      "ESS_slack_logd",ESS_slack_logd,
      "slack_mean_d",slack_mean_d,
      "slack_se_d",slack_se_d,
      "pred_ll_mean",pred_ll_mean,
      "pred_ll_se",pred_ll_se,
      "spl_out_all",spl_out_all)

  save(dirname * "syn_data.jld",
      "PP_data_all",PP_data_all,
      "T_data_all",T_data_all,
      "Z_data_all",Z_data_all,
      "K_data_all",K_data_all)

  params = OrderedDict(
  "datasets" => datasets, "arrival_dists" => arrival_dists, "ntl_alpha" => ntl_alpha, "N_train" => N_train, "N_test" => N_test, "ia_params" => ia_params,
  "n_iter" => n_iter, "n_burn" => n_burn, "n_thin" => n_thin, "n_rep" => n_rep,
  "gibbs_psi" => gibbs_psi, "gibbs_alpha" => gibbs_alpha, "gibbs_arrival_times" => gibbs_arrival_times, "gibbs_ia_params" => gibbs_ia_params, "gibbs_perm_order" => gibbs_perm_order,
  "ntl_gamma_a" => ntl_gamma_a, "ntl_gamma_b" => ntl_gamma_b, "w_alpha" => w_alpha
  )

  open(dirname * "params.json", "w") do f
      write(f, JSON.json(params))
  end

end


text:
# https://projecteuler.net/problem=2
# Each new term in the Fibonacci sequence is generated by adding the previous two terms.
# By starting with 1 and 2, the first 10 terms will be:
# 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
# By considering the terms in the Fibonacci sequence whose values do not exceed four million,
# find the sum of the even-valued terms.

result = 0
a = 1
b = 2

while a <= 4000000
    if a % 2 == 0
        result += a
    end
    a = a + b
    a, b = b, a
end

println(result)

max_stars_repo_name: the-gigi/project-euler

max_issues_repo_name: the-gigi/project-euler

max_forks_repo_name: the-gigi/project-euler


text:
# Julia wrapper for header: /opt/ffmpeg/include/libavfilter/buffersink.h
# Automatically generated using Clang.jl wrap_c, version 0.0.0

export
    av_buffersink_get_buffer_ref,
    av_buffersink_poll_frame,
    av_buffersink_read,
    av_buffersink_read_samples,
    av_buffersink_get_frame_flags,
    av_buffersink_params_alloc,
    av_abuffersink_params_alloc,
    av_buffersink_set_frame_size,
    av_buffersink_get_frame_rate,
    av_buffersink_get_frame,
    av_buffersink_get_samples

function av_buffersink_get_buffer_ref(buffer_sink,bufref,flags::Integer)
    ccall((:av_buffersink_get_buffer_ref,libavfilter),Cint,(Ptr{AVFilterContext},Ptr{Ptr{AVFilterBufferRef}},Cint),buffer_sink,bufref,flags)
end

function av_buffersink_poll_frame(ctx)
    ccall((:av_buffersink_poll_frame,libavfilter),Cint,(Ptr{AVFilterContext},),ctx)
end

function av_buffersink_read(ctx,buf)
    ccall((:av_buffersink_read,libavfilter),Cint,(Ptr{AVFilterContext},Ptr{Ptr{AVFilterBufferRef}}),ctx,buf)
end

function av_buffersink_read_samples(ctx,buf,nb_samples::Integer)
    ccall((:av_buffersink_read_samples,libavfilter),Cint,(Ptr{AVFilterContext},Ptr{Ptr{AVFilterBufferRef}},Cint),ctx,buf,nb_samples)
end

function av_buffersink_get_frame_flags(ctx,frame,flags::Integer)
    ccall((:av_buffersink_get_frame_flags,libavfilter),Cint,(Ptr{AVFilterContext},Ptr{AVFrame},Cint),ctx,frame,flags)
end

function av_buffersink_params_alloc()
    ccall((:av_buffersink_params_alloc,libavfilter),Ptr{AVBufferSinkParams},())
end

function av_abuffersink_params_alloc()
    ccall((:av_abuffersink_params_alloc,libavfilter),Ptr{AVABufferSinkParams},())
end

function av_buffersink_set_frame_size(ctx,frame_size::Integer)
    ccall((:av_buffersink_set_frame_size,libavfilter),Void,(Ptr{AVFilterContext},UInt32),ctx,frame_size)
end

function av_buffersink_get_frame_rate(ctx)
    ccall((:av_buffersink_get_frame_rate,libavfilter),AVRational,(Ptr{AVFilterContext},),ctx)
end

function av_buffersink_get_frame(ctx,frame)
    ccall((:av_buffersink_get_frame,libavfilter),Cint,(Ptr{AVFilterContext},Ptr{AVFrame}),ctx,frame)
end

function av_buffersink_get_samples(ctx,frame,nb_samples::Integer)
    ccall((:av_buffersink_get_samples,libavfilter),Cint,(Ptr{AVFilterContext},Ptr{AVFrame},Cint),ctx,frame,nb_samples)
end

max_stars_repo_name: asafasban/AAVideoIO

max_issues_repo_name: asafasban/AAVideoIO

max_forks_repo_name: asafasban/AAVideoIO


text:
module CollegeStratData

using ArgCheck, DocStringExtensions
using CSV, DataFrames, DelimitedFiles
using CommonLH, EconometricsLH, FilesLH
using CollegeStratBase, DataCollegeStrat

# DataSettings
export DataSettings, make_data_settings, test_data_settings
export n_gpa, n_2year, n_colleges, n_parental, hsgpa_ub, parental_ub, hsgpa_masses, parental_masses, mass_gpa_yp, can_graduate, is_two_year, two_year_colleges, four_year_colleges, no_grad_idx, grad_idx, mean_by_gpa

# Helpers
export regressor_name, regressor_string, regressor_strings, gpa_regressors, parental_regressors, quality_regressors, school_regressors, intercept_name

# Data Files
export data_file, missing_file_list, read_regression_file, raw_file
export file_name_differences, compare_dirs

# Moments
export load_moment, n_entrants
export exper_profile, wage_regr_intercepts, workstart_earnings, wage_regr_grads
export get_regr_coef, get_intercept

export cdf_gpa_by_qual

include("constants.jl")

# Types
include("types.jl")
include("wage_regressions.jl")
include("datasettings.jl")

# Data handling routines. Must come first.
include("raw_data_files.jl");
include("each_raw_file.jl");
include("data_files.jl")
include("delim_xy_file.jl")
include("delim_single_col.jl");
include("regression_files.jl");

# Individual data moments
include("scalar_moments.jl")
include("worker_moments.jl");
include("by_year.jl");
include("by_gpa.jl")
include("by_gpa_yp.jl")
include("by_gpa_yp_qual.jl")
include("by_quality.jl")
include("by_quality_parental.jl")
include("by_quality_gpa.jl")
include("by_parental.jl")
include("by_grad_year.jl");
include("regression_moments.jl")

# Processing all moments (must come last)
# include("show_deviations.jl")
# include("show_data.jl")
include("helpers.jl")

"""
	$(SIGNATURES)

Mapping of data moment names to functions that load them.
The user can then simply call `load_moment` to load any moment.
"""
moment_map() = Dict([
    # :corrGpaYp => corr_gpa_yp,
    :coursesTried_otM => courses_tried_grad_year,
    :coursesTried_qtM => courses_tried_qual_year,
    :cumLoans_qtM => cum_loans_qual_year,
    :cumLoans90_qtM => cum_loans90_qual_year,
    :cumLoans90_tV => cum_loans90_year,
    :fracDrop4y_tV => frac_drop_4y_by_year,
    :fracDrop_qtM => frac_drop_qual_year,
    :fracDrop_gtM => frac_drop_gpa_year,
    :fracEnroll_qV => frac_enroll_by_qual,
    :fracEnrollUncond_qV => frac_enroll_uncond_by_qual,
    :fracEnter_gV => frac_enter_by_gpa,
    :fracEnter_pV => frac_enter_by_parental,
    :fracEnter_gpM => load_entry_gpa_yp,
    # Fraction in each quality among [gpa, yp] entrants
    :fracEnter_gpqM => load_qual_entry_gpa_yp_all,
    :fracEnter => frac_enter,
    :fracGrad => grad_rate,
    :fracGrad_gV => grad_rate_by_gpa,
    :fracGrad_qV => grad_rate_by_quality,
    :fracGrad_qpM => frac_grad_qual_parental,
    :fracGrad_qgM => grad_rate_qual_gpa,
    :fracLocal_qV => frac_local_by_quality,
    :fracQual_qpM => frac_qual_by_parental,
    :fracQual_qgM => frac_qual_by_gpa,
    :gpaMean_qV => afqt_mean_by_quality,
    :mass_gpM => mass_by_gpa_yp,
    :massEntry_qgM => mass_entry_qual_gpa,
    :statusByYear => status_by_year,
    :studyTime => study_time,
    :studyTime_qV => study_time_qual,
    :studyTime_qgM => study_time_qual_gpa,
    :timeToDrop4y_gV => time_to_drop_4y_by_gpa,
    :timeToDrop4y_qV => time_to_drop_4y_by_quality,
    :timeToDrop4y_qgM => time_to_drop_4y_qual_gpa,
    :timeToGrad4y_gV => time_to_grad_4y_by_gpa,
    :timeToGrad4y_qV => time_to_grad_4y_by_quality,
    :timeToGrad4y_qpM => time_to_grad_4y_qual_parental,
    :timeToGrad4y_qgM => time_to_grad_4y_qual_gpa,
    :tuition_qV => college_tuition,
    :workTime_gV => work_hours_by_gpa,
    :workTime_qV => work_hours_by_qual,
    :workTime_pV => work_hours_by_parental,
    # Regressions
    :transferRegr => transfer_regr,
    :tuitionRegr => tuition_regr,
    :wageRegrIntercepts => wage_regr_intercepts,
    :wageRegrGrads => wage_regr_grads
]);

"""
	$(SIGNATURES)

Load a data moment by name.

For regression moments, this returns a `RegressionTable`. For other moments, it returns means, std errors of means, and cell counts.
"""
function load_moment(ds :: DataSettings, mName :: Symbol)
    mm = moment_map();
    if !haskey(mm, mName)
        error("Moment $mName does not exist");
    end
    return mm[mName](ds)
end

end # module


text:
# Conjugates related to normal distribution
#
#	Normal - Normal (with known sigma)
#	InverseGamma - Normal (with known mu)
#	NormalInverseGamma - Normal
#

#### Normal prior on μ (with σ^2 known)

function posterior_canon(pri::Normal, ss::NormalKnownSigmaStats)
	p0 = 1.0 / abs2(pri.σ)
	p1 = 1.0 / abs2(ss.σ)
	h = pri.μ * p0 + ss.sx * p1
	prec = p0 + ss.tw * p1
	NormalCanon(h, prec)
end

function posterior_canon(pri::(Normal, Float64), G::Type{Normal}, x::Array)
	μpri::Normal, σ::Float64 = pri
	posterior_canon(μpri, suffstats(NormalKnownSigma(σ), x))
end

function posterior_canon(pri::(Normal, Float64), G::Type{Normal}, x::Array, w::Array{Float64})
	μpri::Normal, σ::Float64 = pri
	posterior_canon(μpri, suffstats(NormalKnownSigma(σ), x, w))
end

function posterior(pri::(Normal, Float64), G::Type{Normal}, x::Array)
	convert(Normal, posterior_canon(pri, G, x))
end

function posterior(pri::(Normal, Float64), G::Type{Normal}, x::Array, w::Array{Float64})
	convert(Normal, posterior_canon(pri, G, x, w))
end

complete(G::Type{Normal}, pri::(Normal, Float64), μ::Float64) = Normal(μ, pri[2])

#### InverseGamma on σ^2 (with μ known)

function posterior_canon(pri::InverseGamma, ss::NormalKnownMuStats)
	α1 = pri.shape + 0.5 * ss.tw
	β1 = pri.scale + 0.5 * ss.s2
	return InverseGamma(α1, β1)
end

function posterior_canon(pri::(Float64, InverseGamma), G::Type{Normal}, x::Array)
	μ::Float64, σ2pri::InverseGamma = pri
	posterior_canon(σ2pri, suffstats(NormalKnownMu(μ), x))
end

function posterior_canon(pri::(Float64, InverseGamma), G::Type{Normal}, x::Array, w::Array{Float64})
	μ::Float64, σ2pri::InverseGamma = pri
	posterior_canon(σ2pri, suffstats(NormalKnownMu(μ), x, w))
end

posterior(pri::(Float64, InverseGamma), G::Type{Normal}, x::Array) = posterior_canon(pri, G, x)
posterior(pri::(Float64, InverseGamma), G::Type{Normal}, x::Array, w::Array{Float64}) = posterior_canon(pri, G, x, w)

complete(G::Type{Normal}, pri::(Float64, InverseGamma), σ2::Float64) = Normal(pri[1], sqrt(σ2))

#### Gamma on precision σ^(-2) (with μ known)

function posterior_canon(pri::Gamma, ss::NormalKnownMuStats)
	α1 = pri.shape + 0.5 * ss.tw
	β1 = pri.scale + 0.5 * ss.s2
	return Gamma(α1, β1)
end

function posterior_canon(pri::(Float64, Gamma), G::Type{Normal}, x::Array)
	μ::Float64, τpri::Gamma = pri
	posterior_canon(τpri, suffstats(NormalKnownMu(μ), x))
end

function posterior_canon(pri::(Float64, Gamma), G::Type{Normal}, x::Array, w::Array{Float64})
	μ::Float64, τpri::Gamma = pri
	posterior_canon(τpri, suffstats(NormalKnownMu(μ), x, w))
end

posterior(pri::(Float64, Gamma), G::Type{Normal}, x::Array) = posterior_canon(pri, G, x)
posterior(pri::(Float64, Gamma), G::Type{Normal}, x::Array, w::Array{Float64}) = posterior_canon(pri, G, x, w)

complete(G::Type{Normal}, pri::(Float64, Gamma), τ::Float64) = Normal(pri[1], 1.0 / sqrt(τ))

#### NormalInverseGamma on (μ, σ^2)

function posterior_canon(prior::NormalInverseGamma, ss::NormalStats)
    mu0 = prior.mu
    v0 = prior.v0
    shape0 = prior.shape
    scale0 = prior.scale

    # ss.tw contains the number of observations if weight wasn't used to
    # compute the sufficient statistics.

    vn_inv = 1./v0 + ss.tw
    mu = (mu0/v0 + ss.s) / vn_inv  # ss.s = ss.tw*ss.m = n*xbar
    shape = shape0 + 0.5*ss.tw
    scale = scale0 + 0.5*ss.s2 + 0.5/(vn_inv*v0)*ss.tw*(ss.m-mu0).^2

    return NormalInverseGamma(mu, 1./vn_inv, shape, scale)
end

complete(G::Type{Normal}, pri::NormalInverseGamma, t::(Float64, Float64)) = Normal(t[1], sqrt(t[2]))

#### NormalGamma on (μ, σ^(-2))

function posterior_canon(prior::NormalGamma, ss::NormalStats)
    mu0 = prior.mu
    nu0 = prior.nu
    shape0 = prior.shape
    rate0 = prior.rate

    # ss.tw contains the number of observations if weight wasn't used to
    # compute the sufficient statistics.

    nu = nu0 + ss.tw
    mu = (nu0*mu0 + ss.s) / nu
    shape = shape0 + 0.5*ss.tw
    rate = rate0 + 0.5*ss.s2 + 0.5*nu0/nu*ss.tw*(ss.m-mu0).^2

    return NormalGamma(mu, nu, shape, rate)
end

complete(G::Type{Normal}, pri::NormalGamma, t::(Float64, Float64)) = Normal(t[1], 1. / sqrt(t[2]))


text:
using POMDPToolbox
using Base.Test

# Hack to get this to build with POMDPModels
# this can be removed once BoolDistribution is removed from POMDPModels
BoolDistribution = POMDPToolbox.BoolDistribution

# testing constructor and pdf
d = BoolDistribution(0.3)
@test pdf(d, true) == 0.3
@test pdf(d, false) == 0.7

# testing iterator
@test iterator(d) == [true, false]

# testing ==
d2 = BoolDistribution(0.3)
@test d == d2

# testing hash
@test hash(d) == hash(d.p)


text:
@test latexify("x/y"; env=:eq) ==
raw"\begin{equation}
\frac{x}{y}
\end{equation}
"

@test latexify("x = a^x/b"; env=:eq, starred=true) ==
raw"\begin{equation*}
x = \frac{a^{x}}{b}
\end{equation*}
"


text:
function get_module_2_excersise_3_author_name()
    return "YOUR NAME HERE"
end

function count_even_numbers(number_array)
    count_of_evens = 0
    length_of_array = length(number_array)
    # implement the loop here
    return count_of_evens
end


text:
using DelayEmbeddings
using DelayEmbeddings: AbstractDataset, Dataset, dimension
export ProbabilitiesEstimator, Probabilities
export EntropyEstimator
export probabilities, probabilities!
export genentropy, genentropy!
export Dataset, dimension

const Vector_or_Dataset = Union{AbstractVector, AbstractDataset}

"""
    Probabilities(x) → p
A simple wrapper type around an `x::AbstractVector` which ensures that `p` sums to 1.
Behaves identically to `Vector`.
"""
struct Probabilities{T} <: AbstractVector{T}
    p::Vector{T}
    function Probabilities(x::AbstractVector{T}) where T
        s = sum(x)
        if s ≠ 1
            x = x ./ s
        end
        return new{T}(x)
    end
end

# extend base Vector interface:
for f in (:length, :size, :eachindex, :eltype, :lastindex, :firstindex)
    @eval Base.$(f)(d::Probabilities) = $(f)(d.p)
end
Base.IteratorSize(d::Probabilities) = Base.HasLength()
@inline Base.iterate(d::Probabilities, i = 1) = iterate(d.p, i)
@inline Base.getindex(d::Probabilities, i) = d.p[i]
@inline Base.setindex!(d::Probabilities, v, i) = (d.p[i] = v)
@inline Base.:*(d::Probabilities, x::Number) = d.p * x
@inline Base.sum(d::Probabilities{T}) where T = one(T)

"""
An abstract type for entropy estimators that don't explicitly estimate probabilities,
but return the value of the entropy directly.
"""
abstract type EntropyEstimator end
const EntEst = EntropyEstimator # shorthand

"""
An abstract type for probabilities estimators.
"""
abstract type ProbabilitiesEstimator end
const ProbEst = ProbabilitiesEstimator # shorthand

"""
    probabilities(x::Vector_or_Dataset, est::ProbabilitiesEstimator) → p::Probabilities

Calculate probabilities representing `x` based on the provided
estimator and return them as a [`Probabilities`](@ref) container (`Vector`-like).
The probabilities are typically unordered and may or may not contain 0s, see the
documentation of the individual estimators for more.

The configuration options are always given as arguments to the chosen estimator.

    probabilities(x::Vector_or_Dataset, ε::AbstractFloat) → p::Probabilities

Convenience syntax which provides probabilities for `x` based on rectangular binning
(i.e. performing a histogram). In short, the state space is divided into boxes of length
`ε`, and formally we use `est = VisitationFrequency(RectangularBinning(ε))`
as an estimator, see [`VisitationFrequency`](@ref).

This method has a linearithmic time complexity (`n log(n)` for `n = length(x)`)
and a linear space complexity (`l` for `l = dimension(x)`).
This allows computation of probabilities (histograms) of high-dimensional
datasets and with small box sizes `ε` without memory overflow and with maximum performance.
To obtain the bin information along with `p`, use [`binhist`](@ref).

    probabilities(x::Vector_or_Dataset, n::Integer) → p::Probabilities
Same as the above method, but now each dimension of the data is binned into `n::Int` equal
sized bins instead of bins of length `ε::AbstractFloat`.

    probabilities(x::Vector_or_Dataset) → p::Probabilities
Directly count probabilities from the elements of `x` without any discretization,
binning, or other processing (mostly useful when `x` contains categorical or integer data).
"""
function probabilities end

"""
    probabilities!(args...)
Identical to `probabilities(args...)`, but allows pre-allocation of temporarily used
containers.

Only works for certain estimators. See for example [`SymbolicPermutation`](@ref).
"""
function probabilities! end

"""
    genentropy(p::Probabilities; q = 1.0, base = MathConstants.e)

Compute the generalized order-`q` entropy of some probabilities
returned by the [`probabilities`](@ref) function. Alternatively, compute entropy
from pre-computed `Probabilities`.

    genentropy(x::Vector_or_Dataset, est; q = 1.0, base)

A convenience syntax, which calls first `probabilities(x, est)`
and then calculates the entropy of the result (and thus `est` can be a
`ProbabilitiesEstimator` or simply `ε::Real`).

## Description

Let ``p`` be an array of probabilities (summing to 1). Then the generalized (Rényi) entropy is

```math
H_q(p) = \\frac{1}{1-q} \\log \\left(\\sum_i p[i]^q\\right)
```

and generalizes other known entropies,
like e.g. the information entropy
(``q = 1``, see [^Shannon1948]), the maximum entropy (``q=0``,
also known as Hartley entropy), or the correlation entropy
(``q = 2``, also known as collision entropy).

[^Rényi1960]: A. Rényi, *Proceedings of the fourth Berkeley Symposium on Mathematics, Statistics and Probability*, pp 547 (1960)
[^Shannon1948]: C. E. Shannon, Bell Systems Technical Journal **27**, pp 379 (1948)
"""
function genentropy end

function genentropy(prob::Probabilities; q = 1.0, α = nothing, base = MathConstants.e)
    if α ≠ nothing
        @warn "Keyword `α` is deprecated in favor of `q`."
        q = α
    end
    q < 0 && throw(ArgumentError("Order of generalized entropy must be ≥ 0."))
    haszero = any(iszero, prob)
    p = if haszero
        i0 = findall(iszero, prob.p)
        # We copy because if someone initialized Probabilities with 0s, I would guess
        # they would want to index the zeros as well. Not so costly anyways.
        deleteat!(copy(prob.p), i0)
    else
        prob.p
    end

    if q ≈ 0
        return log(base, length(p)) #Hartley entropy, max-entropy
    elseif q ≈ 1
        return -sum( x*log(base, x) for x in p ) #Shannon entropy
    elseif isinf(q)
        return -log(base, maximum(p)) #Min entropy
    else
        return (1/(1-q))*log(base, sum(x^q for x in p) ) #Renyi q entropy
    end
end

genentropy(x::AbstractArray{<:Real}) =
    error("For single-argument input, do `genentropy(Probabilities(x))` instead.")

function genentropy(x::Vector_or_Dataset, est; q = 1.0, α = nothing, base = MathConstants.e)
    if α ≠ nothing
        @warn "Keyword `α` is deprecated in favor of `q`."
        q = α
    end
    p = probabilities(x, est)
    genentropy(p; q = q, base = base)
end

"""
    genentropy!(p, x, est::ProbabilitiesEstimator; q = 1.0, base = MathConstants.e)

Similarly with `probabilities!` this is an in-place version of `genentropy` that allows
pre-allocation of temporarily used containers.

Only works for certain estimators. See for example [`SymbolicPermutation`](@ref).
"""
function genentropy!(p, x, est; q = 1.0, α = nothing, base = MathConstants.e)
    if α ≠ nothing
        @warn "Keyword `α` is deprecated in favor of `q`."
        q = α
    end
    probabilities!(p, x, est)
    genentropy(p; q = q, base = base)
end


text:
red(r::FloatInt) = RGB(r,0,0)
green(g::FloatInt) = RGB(0,g,0)
blue(b::FloatInt) = RGB(0,0,b)

clear() = RGB(0,0,0,0)
white(c::FloatInt) = RGB(c,c,c)
black(c::FloatInt) = RGB(1-c,1-c,1-c)
gray(c::FloatInt) = RGB(0.5c,0.5c,0.5c)

cyan(c::FloatInt) = RGB(0,c,c)
magenta(c::FloatInt) = RGB(c,0,c)
yellow(c::FloatInt) = RGB(c,c,0)

max_stars_repo_name: wookay/ColorMath

max_issues_repo_name: wookay/ColorMath

max_forks_repo_name: wookay/ColorMath


text:
using Documenter, ProfileSVG

makedocs(
    clean = false,
    modules=[ProfileSVG],
    format=Documenter.HTML(prettyurls = get(ENV, "CI", nothing) == "true",
                           assets = ["assets/profilesvg.css"]),
    sitename="ProfileSVG",
    pages=[
        "Introduction" => "index.md",
        "Coloration Schemes" => "coloration-schemes.md",
        "Other Options" => "other-options.md",
        "Reference" => "reference.md",
    ]
)

deploydocs(
    repo="github.com/kimikage/ProfileSVG.jl.git",
    push_preview = true
)


text:
@testset "hyperbolic_mesh" begin
    @testset "L" begin
        np1 = 33
        np = 2np1 - 1
        sp = AirfoilMeshers.TanhSpacing(0.01, -1, np1)
        s = AirfoilMeshers.nodes(sp)
        x = vcat(fill(0.0, np - np1), s)
        y = vcat(reverse(s), fill(0.0, np - np1))
        p0 = [MVector{2,Float64}(x[i], y[i]) for i in 1:np]
        mesher = HyperbolicMesher(
            :H,
            ExpStepSize(1e-3, 1.1),
            SymmetryBoundary(),
            SymmetryBoundary();
            f_blend=1,
            n_smooth=25,
        )
        mesh = gen_mesh(mesher, p0, 0.3; mg_level=2)
        save_mesh("output/L_inside.dat", mesh, :TECPLOT)
        reverse!(p0)
        mesher = HyperbolicMesher(
            :H,
            ExpStepSize(1e-3, 1.1),
            SymmetryBoundary(),
            SymmetryBoundary();
            f_blend=1,
            n_smooth=25,
        )
        mesh = gen_mesh(mesher, p0, 0.3; mg_level=2)
        save_mesh("output/L_outside.dat", mesh, :TECPLOT)
        save_mesh("output/L_out.cfl.dat", mesh, :PLOT3D; cfl3d=true)
        save_mesh("output/L_out.p3d.dat", mesh, :PLOT3D)
    end
    @testset "C0012" begin
        dist = SurfaceDistribution(5e-4, 1e-5, 0.01, 0.025)
        af = NACA"0012"s
        x0, y0 = gen_airfoil(af, 257)
        points = surface_mesh(dist, x0, y0; mg_level=2)
        mesher = HyperbolicMesher(
            :C,
            MinStepSize(ExpStepSize(5e-6, 1.14), 2),
            SymmetryBoundary(),
            SymmetryBoundary();
            f_blend=1e-5,
            n_smooth=10,
            wake_len=25,
            wake_maxl=1,
            wake_ratio=1.14,
            wake_aoa=10,
        )

        mesh = gen_mesh(mesher, points, 20; mg_level=2)
        save_mesh("output/C0012.dat", mesh, :TECPLOT)

        save_mesh("output/C0012.cas", mesh, :FLUENT)
    end
    @testset "Surface Jet" begin
        airfoil = NACA"0012"s
        xjet = 0.95
        hjet = 0.01
        tx, ty = t_upper(airfoil, xjet)
        lbjet = xjet - tx*hjet/2
        rbjet = xjet + tx*hjet/2
        npjet = 33
        dsjet = hjet / (npjet-1)
        ds_le = 5e-4
        ds_te = 1e-5
        ds_up_max = 0.01
        ds_lo_max = 0.025
        rs_max = 1.1
        snode = [
            TrailingNode(:L),
            LeadingNode(),
            SurfaceNode(:U,lbjet),
            SurfaceNode(:U,rbjet),
            TrailingNode(:U)
        ]
        sdist = [
            TanhSpacing(ds_te, ds_le; dsmax=ds_lo_max, rsmax=rs_max),
            TanhSpacing(ds_le, dsjet; dsmax=ds_up_max, rsmax=rs_max),
            EqualSpacing(npjet),
            TanhSpacing(dsjet, ds_te; dsmax=ds_up_max, rsmax=rs_max)
        ]
        dist = SurfaceDistribution(snode,sdist)
        x0, y0 = gen_airfoil(airfoil, 257)
        points = surface_mesh(dist, x0, y0; mg_level=2)
        mesher = HyperbolicMesher(
            :C,
            MinStepSize(ExpStepSize(5e-6, 1.14), 2),
            SymmetryBoundary(),
            SymmetryBoundary();
            f_blend=1e-5,
            n_smooth=10,
            wake_len=25,
            wake_maxl=1,
            wake_ratio=1.14,
            wake_aoa=0,
        )

        mesh = gen_mesh(mesher, points, 20; mg_level=2)
        save_mesh("output/surfjet.dat", mesh, :TECPLOT)
    end
end


text:
using Markdown

import Base.convert

function convert(::Type{OrgDoc}, md::Markdown.MD)
    elements = map(convert.(Component, md.content)) do e
        if e isa Element
            (e,)
        elseif e isa Vector
            e
        end
    end |> Iterators.flatten |> collect
    heading_positions = findall(e -> e isa Heading, elements)
    if length(heading_positions) == 0
        OrgDoc([Section(elements, nothing, nothing)])
    else
        sectioning = Union{Heading, Section}[]
        if heading_positions[1] > 1
            push!(sectioning, Section(elements[1:heading_positions[1]-1], nothing, nothing))
        end
        for (hpos, hend) in zip(heading_positions, vcat(heading_positions[2:end], length(elements)))
            if hend < length(elements)
                hend -= 1
            end
            if hpos < hend
                elements[hpos].section = Section(elements[hpos+1:hend], nothing, nothing)
            end
            push!(sectioning, elements[hpos])
        end
        OrgDoc(sectioning)
    end
end

convert(::Type{Component}, md::Markdown.MD) = convert(OrgDoc, md).contents

convert(::Type{Component}, h::Markdown.Header{level}) where {level} =
    Heading(level, nothing, nothing, convert.(Component, h.text), SubString{String}[], nothing)

convert(::Type{Component}, ::Markdown.HorizontalRule) = HorizontalRule()

convert(::Type{Component}, ::Markdown.LineBreak) = LineBreak()

convert(::Type{Component}, s::String) = TextPlain(s)

convert_mdmarkup(type::Symbol, text::String) =
    TextMarkup(type, SubString(text))

convert_mdmarkup(type::Symbol, text::Vector) =
    TextMarkup(type, convert.(Component, text))

convert(::Type{Component}, b::Markdown.Bold) =
    convert_mdmarkup(:bold, b.text)

convert(::Type{Component}, i::Markdown.Italic) =
    convert_mdmarkup(:bold, i.text)

function convert(::Type{Component}, code::Markdown.Code; inline::Bool=false)
    if inline
        convert_mdmarkup(:code, code.code)
    else
        SourceBlock(if code.language == ""
                        "julia" # assume Julia if unspecified
                    else code.language end,
                    nothing, split(code.code, '\n'))
    end
end

function convert(::Type{Component}, l::Markdown.Link)
    path = if occursin("://", l.url)
        LinkPath(split(l.url, r":(?://)", limit=2)...)
    else
        LinkPath(:fuzzy, SubString(l.url))
    end
    RegularLink(path, convert(Component, Markdown.Paragraph(l.text)).contents)
end

convert(::Type{Component}, l::Markdown.LaTeX) =
    LaTeXFragment(SubString(l.formula), (SubString("\\("), SubString("\\)")))

convert(::Type{Component}, f::Markdown.Footnote) =
    if isnothing(f.text)
        FootnoteReference(SubString(f.id), nothing)
    else
        FootnoteDefinition(SubString(f.id), convert.(f.text))
    end

convert(::Type{Component}, img::Markdown.Image) =
    RegularLink(LinkPath(split(img.url, "://", limit=2)...), nothing)

function convert(::Type{Component}, par::Markdown.Paragraph)
    Paragraph(
        map(par.content) do elt
            if elt isa Markdown.Code
                convert(Component, elt, inline=true)
            else
                convert(Component, elt)
            end
        end |> Vector{Object})
end

convert(::Type{Component}, a::Markdown.Admonition) =
    SpecialBlock(a.category, nothing, convert.(Component, a.content))

function convert(::Type{Component}, l::Markdown.List)
    olist, bullets = if Markdown.isordered(l)
        OrderedList, string.(1:length(l.items), '.')
    else
        UnorderedList, fill("-", length(l.items))
    end
    items = map(zip(bullets, l.items)) do (bullet, contents)
        Item(bullet, convert.(Component, contents))
    end
    olist(items)
end

# Might as well, just in case

convert(::Type{OrgDoc},
        md::Union{Markdown.HorizontalRule, Markdown.LineBreak,
                  Markdown.Bold, Markdown.Italic, Markdown.Code, Markdown.Link,
                  Markdown.LaTeX, Markdown.Footnote, Markdown.Image,
                  Markdown.Paragraph, Markdown.Admonition}) =
                      OrgDoc([Section([convert(Component, md)], nothing, nothing)])

convert(::Type{OrgDoc}, h::Markdown.Header) =
    OrgDoc([convert(Component, h)])


text: push!(LOAD_PATH, ".")

max_stars_repo_name: billmclean/ComputationalMathsNotes

max_issues_repo_name: billmclean/ComputationalMathsNotes

max_forks_repo_name: billmclean/ComputationalMathsNotes


text:
module GFA1

import Automa.RegExp
const re = RegExp

include("machines.jl")

end # module

function makevis(x, name)
    m = Automa.compile(x)
    write("$name.dot", Automa.machine2dot(m))
    run(`dot -Tpng -o $name.png $name.dot`)
end

cigar = re"([0-9]+[MIDNS])+"
overlap = re.cat(num, re.opt(re.cat(':', num))) | re.cat(num, ':') | re.cat(':', num) | cigar

link = re.cat('L', hspace, id, hspace, sgn, hspace, id, hspace, sgn, hspace, overlap, re.rep(re.cat(hspace, tag)))

segment_actions = Dict(
    :mark => :(@mark),
    :pos => :(pos = @relpos(p)),
    :countline => :(linenum += 1),
    :id => :(record.id = pos:@relpos(p) - 1)
    :segment => quote
        found = true
        @escape
    end
)

mutable struct SegmentRecord
    # data and filled range
    data::Vector{UInt8}
    filled::UnitRange{UInt}
    # indexes
    identifier::UnitRange{UInt}
    sequence::UnitRange{UInt}
    tags::Vector{UnitRange{UInt}}
end

function initialize!(sr::SegmentRecord)
    empty!(sr.data)
    filled = 1:0
    identifier = 1:0
    description = 1:0
    empty!(tags)
end

initcode = quote
    pos = 0
    found = false
    initialize!(record)
    cs = linenum = state
end

context = Automa.CodeGenContext()
@eval function parse_segment(g::SequenceGraph, data)
    $(Automa.generate_init_code(context, segment))
    p_end = p_eof = lastindex(data)
    $(Automa.generate_exec_code(context, machine, actions))

end


text:
"""
Most functions in this files are not used in this project.
"""
# TODO: test everything for single orbital case
iν_array(β::Real, grid::AbstractArray{Int64,1}) = [1.0im*((2.0 *el + 1)* π/β) for el in grid]
iν_array(β::Real, size::Integer)    = [1.0im*((2.0 *i + 1)* π/β) for i in 0:size-1]
iω_array(β::Real, grid::AbstractArray{Int64,1}) = [1.0im*((2.0 *el)* π/β) for el in grid]
iω_array(β::Real, size::Integer)    = [1.0im*((2.0 *i)* π/β) for i in 0:size-1]

function FUpDo_from_χDMFT(χupdo, GImp, freqList, mP, sP)
    FUpDo = Array{eltype(χupdo)}(undef, 2*sP.n_iω+1, 2*sP.n_iν, 2*sP.n_iν)
    #TODO: indices should not be computed by hand here, get them from input
    for f in freqList
        i = f[1] + sP.n_iω+1
        j = f[2] + sP.n_iν+1 + trunc(Int64,sP.shift*f[1]/2)
        k = f[3] + sP.n_iν+1 + trunc(Int64,sP.shift*f[1]/2)
        FUpDo[i,j,k] = χupdo[i,j,k]/(mP.β^2 * get_symm_f(GImp,f[2]) * get_symm_f(GImp,f[1]+f[2])
                           * get_symm_f(GImp,f[3]) * get_symm_f(GImp,f[1]+f[3]))
    end
    return FUpDo
end

"""
    G(ind::Int64, Σ::Array{Complex{Float64},1}, ϵkGrid, β::Float64, μ)

Constructs GF from k-independent self energy, using the Dyson equation
and the dispersion relation of the lattice.
"""
@inline function G(ind::Int64, Σ::Array{Complex{Float64},1},
                   ϵkGrid::Union{Array{Float64,1},Base.Generator}, β::Float64, μ::Float64)
    Σν = get_symm_f(Σ,ind)
    return map(ϵk -> G_from_Σ(ind, β, μ, ϵk, Σν), ϵkGrid)
end

@inline function G(ind::Int64, Σ::Array{Complex{Float64},2},
                   ϵkGrid, β::Float64, μ::Float64)
    Σνk = get_symm_f(Σ,ind)
    return reshape(map(((ϵk, Σνk_i),) -> G_from_Σ(ind, β, μ, ϵk, Σνk_i), zip(ϵkGrid, Σνk)), size(ϵkGrid)...)
end

@inline function G(ind::Int64, Σ::Array{Complex{Interval{Float64}},2},
                   ϵkGrid, β::Float64, μ::Float64)
    Σνk = get_symm_f(Σ,ind)
    return reshape(map(((ϵk, Σνk_i),) -> G_from_Σ(ind, β, μ, ϵk, Σνk_i), zip(ϵkGrid, Σνk)), size(ϵkGrid)...)
end

function Σ_Dyson(GBath::Array{Complex{Float64},1}, GImp::Array{Complex{Float64},1}, eps = 1e-3)
    @inbounds Σ::Array{Complex{Float64},1} =  1 ./ GBath .- 1 ./ GImp
    return Σ
end

@inline @fastmath G_from_Σ(n::Int64, β::Float64, μ::Float64, ϵₖ::T, Σ::Complex{Float64}) where T <: Real =
                    1/((π/β)*(2*n + 1)*1im + μ - ϵₖ - Σ)

@inline G_from_Σ(Σ::Array{Complex{Float64}}, ϵkGrid,
                 range::UnitRange{Int64}, mP::ModelParameters) = [G(ind, Σ, ϵkGrid, mP.β, mP.μ) for ind in range]

@inline @fastmath G_from_Σ(n::Int64, β::Float64, μ::Float64, ϵₖ::T, Σ::Complex{Interval{Float64}}) where T <: Real =
                    1/((π/β)*(2*n + 1)*1im + μ - ϵₖ - Σ)
@inline G_from_Σ(Σ::Array{Complex{Interval{Float64}}}, ϵkGrid,
                 range::UnitRange{Int64}, mP::ModelParameters) = [G(ind, Σ, ϵkGrid, mP.β, mP.μ) for ind in range]

function subtract_tail(inp::AbstractArray{T,1}, c::Float64, iω::Array{Complex{Float64},1}) where T <: Number
    res = Array{eltype(inp),1}(undef, length(inp))
    for n in 1:length(inp)
        if iω[n] != 0
            res[n] = inp[n] - (c/(iω[n]^2))
        else
            res[n] = inp[n]
        end
    end
    return res
end


text:
using Documenter
using ConstituencyTrees

DocMeta.setdocmeta!(ConstituencyTrees,
                    :DocTestSetup, :(using ConstituencyTrees); recursive=true)

makedocs(
    sitename = "ConstituencyTrees.jl",
    format = Documenter.HTML(),
    modules = [ConstituencyTrees],
    pages = ["Home" => "index.md"],
    doctest = true)

deploydocs(repo = "github.com/dellison/ConstituencyTrees.jl.git")


text:
#! format: off

@testset "124.binary-tree-maximum-path-sum.jl" begin
    t = TreeNode(
        -10,
        TreeNode(9),
        TreeNode(
            20,
            TreeNode(15),
            TreeNode(7)
        )
    )

    @test max_path_sum(t) == 42
end


text:
## Gather data back from RDA files
R"""
load(file = "generation_of_data_for_econ_analysis/waning_imm_scenario_1/kenya_inc_sev_no_vac_w_vac.rda")
"""
kenya_inc_sev_sc_1 = @rget kenya_inc_sev
kenya_inc_sev_sc_1 = sum(kenya_inc_sev_sc_1, dims = 2)[:, 1, :]
kenya_inc_sev = 0
R"""
kenya_inc_sev = 0 #Free memory
"""
R"""
load(file = "generation_of_data_for_econ_analysis/waning_imm_scenario_2/kenya_inc_sev_30_perc_w_vac.rda")
"""
kenya_inc_sev_sc_2 = @rget kenya_inc_sev
kenya_inc_sev_sc_2 = sum(kenya_inc_sev_sc_2, dims = 2)[:, 1, :]
kenya_inc_sev = 0
R"""
kenya_inc_sev = 0 #Free memory
"""
R"""
load(file = "generation_of_data_for_econ_analysis/waning_imm_scenario_3/kenya_inc_sev_50_perc_w_vac.rda")
"""
kenya_inc_sev_sc_3 = @rget kenya_inc_sev
kenya_inc_sev_sc_3 = sum(kenya_inc_sev_sc_3, dims = 2)[:, 1, :]
kenya_inc_sev = 0
R"""
kenya_inc_sev = 0 #Free memory
"""
R"""
load(file = "generation_of_data_for_econ_analysis/waning_imm_scenario_4/kenya_inc_sev_70_perc_w_vac.rda")
"""
kenya_inc_sev_sc_4 = @rget kenya_inc_sev
kenya_inc_sev_sc_4 = sum(kenya_inc_sev_sc_4, dims = 2)[:, 1, :]
kenya_inc_sev = 0
R"""
kenya_inc_sev = 0 #Free memory
"""
R"""
load(file = "generation_of_data_for_econ_analysis/waning_imm_scenario_5/kenya_inc_sev_30_perc_rapid_w_vac.rda")
"""
kenya_inc_sev_sc_5 = @rget kenya_inc_sev
kenya_inc_sev_sc_5 = sum(kenya_inc_sev_sc_5, dims = 2)[:, 1, :]
kenya_inc_sev = 0
R"""
kenya_inc_sev = 0 #Free memory
"""
R"""
load(file = "generation_of_data_for_econ_analysis/waning_imm_scenario_6/kenya_inc_sev_50_perc_rapid_w_vac.rda")
"""
kenya_inc_sev_sc_6 = @rget kenya_inc_sev
kenya_inc_sev_sc_6 = sum(kenya_inc_sev_sc_6, dims = 2)[:, 1, :]
kenya_inc_sev = 0
R"""
kenya_inc_sev = 0 #Free memory
"""
R"""
load(file = "generation_of_data_for_econ_analysis/waning_imm_scenario_7/kenya_inc_sev_70_perc_rapid_w_vac.rda")
"""
kenya_inc_sev_sc_7 = @rget kenya_inc_sev
kenya_inc_sev_sc_7 = sum(kenya_inc_sev_sc_7, dims = 2)[:, 1, :]
kenya_inc_sev = 0
R"""
kenya_inc_sev = 0 #Free memory
"""


text:
module MOSInterface

import HTTP
import JSON

include("utils.jl")
include("interface.jl")
include("model.jl")
include("export.jl")

end

max_stars_repo_name: Fuinn/mos-interface-jl

max_issues_repo_name: Fuinn/mos-interface-jl

max_forks_repo_name: Fuinn/mos-interface-jl


text:
# using TBComponents
using Printf
using Test
using IterableTables
using TableTraits
using IteratorInterfaceExtensions
using MiniTB

include( "../src/common_types.jl" )
include( "../src/taxcalcs.jl" )
include( "../src/reweighter.jl" )
include( "../src/poverty_inequality.jl" )

#
# comment this one out if you don't have HBAI from the UKDS
#
include( "test_hbai.jl")

include( "poverty_inequality_tests.jl" )
include( "reweighter_tests.jl" )
include( "taxcalcs_tests.jl" )
include( "piecewise_linear_generator_tests.jl" )


text:
###############################################################################
#
#   arb_poly.jl : Polynomials over arb
#
###############################################################################

export ArbPolyRing, arb_poly, derivative, integral, evaluate, evaluate2,
       compose, from_roots, evaluate_iter, evaluate_fast, evaluate,
       interpolate, interpolate_newton, interpolate_barycentric,
       interpolate_fast, roots_upper_bound

###############################################################################
#
#   Basic manipulation
#
###############################################################################

parent_type(::Type{arb_poly}) = ArbPolyRing

elem_type(::Type{ArbPolyRing}) = arb_poly

length(x::arb_poly) = ccall((:arb_poly_length, :libarb), Int,
                                   (Ref{arb_poly},), x)

set_length!(x::arb_poly, n::Int) = ccall((:_arb_poly_set_length, :libarb), Void,
                                   (Ref{arb_poly}, Int), x, n)

degree(x::arb_poly) = length(x) - 1

function coeff(a::arb_poly, n::Int)
  n < 0 && throw(DomainError())
  t = parent(a).base_ring()
  ccall((:arb_poly_get_coeff_arb, :libarb), Void,
              (Ref{arb}, Ref{arb_poly}, Int), t, a, n)
  return t
end

zero(a::ArbPolyRing) = a(0)

one(a::ArbPolyRing) = a(1)

function gen(a::ArbPolyRing)
   z = arb_poly()
   ccall((:arb_poly_set_coeff_si, :libarb), Void,
        (Ref{arb_poly}, Int, Int), z, 1, 1)
   z.parent = a
   return z
end

# todo: write a C function for this
function isgen(a::arb_poly)
   return isequal(a, gen(parent(a)))
end

#function iszero(a::arb_poly)
#   return length(a) == 0
#end

#function isone(a::arb_poly)
#   return strongequal(a, one(parent(a)))
#end

function deepcopy_internal(a::arb_poly, dict::ObjectIdDict)
   z = arb_poly(a)
   z.parent = parent(a)
   return z
end

###############################################################################
#
#   AbstractString I/O
#
###############################################################################

function show(io::IO, x::ArbPolyRing)
  print(io, "Univariate Polynomial Ring in ")
  print(io, string(var(x)))
  print(io, " over ")
  show(io, x.base_ring)
end

function show(io::IO, f::arb_poly)
  if length(f) == 0
    print(io, "0")
  else
    print(io, "[ ")
    for i in 0:degree(f)-1
      print(io, coeff(f,i))
      print(io, ", ")
    end
    print(io, coeff(f,degree(f)))
    print(io, " ]")
  end
end

###############################################################################
#
#   Comparisons
#
###############################################################################

function isequal(x::arb_poly, y::arb_poly)
   return ccall((:arb_poly_equal, :libarb), Bool,
                                      (Ref{arb_poly}, Ref{arb_poly}), x, y)
end

doc"""
    overlaps(x::arb_poly, y::arb_poly)
> Return `true` if the coefficient balls of $x$ overlap the coefficient balls
> of $y$, otherwise return `false`.
"""
function overlaps(x::arb_poly, y::arb_poly)
   return ccall((:arb_poly_overlaps, :libarb), Bool,
                                      (Ref{arb_poly}, Ref{arb_poly}), x, y)
end

doc"""
    contains(x::arb_poly, y::arb_poly)
> Return `true` if the coefficient balls of $x$ contain the corresponding
> coefficient balls of $y$, otherwise return `false`.
"""
function contains(x::arb_poly, y::arb_poly)
   return ccall((:arb_poly_contains, :libarb), Bool,
                                      (Ref{arb_poly}, Ref{arb_poly}), x, y)
end

doc"""
    contains(x::arb_poly, y::fmpz_poly)
> Return `true` if the coefficient balls of $x$ contain the corresponding
> exact coefficients of $y$, otherwise return `false`.
"""
function contains(x::arb_poly, y::fmpz_poly)
   return ccall((:arb_poly_contains_fmpz_poly, :libarb), Bool,
                                      (Ref{arb_poly}, Ref{fmpz_poly}), x, y)
end

doc"""
    contains(x::arb_poly, y::fmpq_poly)
> Return `true` if the coefficient balls of $x$ contain the corresponding
> exact coefficients of $y$, otherwise return `false`.
"""
function contains(x::arb_poly, y::fmpq_poly)
   return ccall((:arb_poly_contains_fmpq_poly, :libarb), Bool,
                                      (Ref{arb_poly}, Ref{fmpq_poly}), x, y)
end

function ==(x::arb_poly, y::arb_poly)
    if length(x) != length(y)
        return false
    end
    for i = 0:degree(x)
        if !(coeff(x, i) == coeff(y, i))
            return false
        end
    end
    return true
end

function !=(x::arb_poly, y::arb_poly)
    for i = 0:max(degree(x), degree(y))
        if coeff(x, i) != coeff(y, i)
            return true
        end
    end
    return false
end

doc"""
    unique_integer(x::arb_poly)
> Return a tuple `(t, z)` where $t$ is `true` if there is a unique integer
> contained in each of the coefficients of $x$, otherwise sets $t$ to `false`.
> In the former case, $z$ is set to the integer polynomial.
"""
function unique_integer(x::arb_poly)
  z = FmpzPolyRing(var(parent(x)))()
  unique = ccall((:arb_poly_get_unique_fmpz_poly, :libarb), Int,
    (Ref{fmpz_poly}, Ref{arb_poly}), z, x)
  return (unique != 0, z)
end

###############################################################################
#
#   Shifting
#
###############################################################################

function shift_left(x::arb_poly, len::Int)
   len < 0 && throw(DomainError())
   z = parent(x)()
   ccall((:arb_poly_shift_left, :libarb), Void,
      (Ref{arb_poly}, Ref{arb_poly}, Int), z, x, len)
   return z
end

function shift_right(x::arb_poly, len::Int)
   len < 0 && throw(DomainError())
   z = parent(x)()
   ccall((:arb_poly_shift_right, :libarb), Void,
       (Ref{arb_poly}, Ref{arb_poly}, Int), z, x, len)
   return z
end

################################################################################
#
#  Unary operations
#
################################################################################

function -(x::arb_poly)
  z = parent(x)()
  ccall((:arb_poly_neg, :libarb), Void, (Ref{arb_poly}, Ref{arb_poly}), z, x)
  return z
end

################################################################################
#
#  Binary operations
#
################################################################################

function +(x::arb_poly, y::arb_poly)
  z = parent(x)()
  ccall((:arb_poly_add, :libarb), Void,
              (Ref{arb_poly}, Ref{arb_poly}, Ref{arb_poly}, Int),
              z, x, y, prec(parent(x)))
  return z
end

function *(x::arb_poly, y::arb_poly)
  z = parent(x)()
  ccall((:arb_poly_mul, :libarb), Void,
              (Ref{arb_poly}, Ref{arb_poly}, Ref{arb_poly}, Int),
              z, x, y, prec(parent(x)))
  return z
end

function -(x::arb_poly, y::arb_poly)
  z = parent(x)()
  ccall((:arb_poly_sub, :libarb), Void,
              (Ref{arb_poly}, Ref{arb_poly}, Ref{arb_poly}, Int),
              z, x, y, prec(parent(x)))
  return z
end

function ^(x::arb_poly, y::Int)
  y < 0 && throw(DomainError())
  z = parent(x)()
  ccall((:arb_poly_pow_ui, :libarb), Void,
              (Ref{arb_poly}, Ref{arb_poly}, UInt, Int),
              z, x, y, prec(parent(x)))
  return z
end

###############################################################################
#
#   Ad hoc binary operators
#
###############################################################################

for T in [Integer, fmpz, fmpq, Float64, BigFloat, arb, fmpz_poly, fmpq_poly]
   @eval begin
      +(x::arb_poly, y::$T) = x + parent(x)(y)

      +(x::$T, y::arb_poly) = y + x

      -(x::arb_poly, y::$T) = x - parent(x)(y)

      -(x::$T, y::arb_poly) = parent(y)(x) - y

      *(x::arb_poly, y::$T) = x * parent(x)(y)

      *(x::$T, y::arb_poly) = y * x
   end
end

+(x::arb_poly, y::Rational{T}) where T <: Union{Int, BigInt} = x + parent(x)(y)

+(x::Rational{T}, y::arb_poly) where T <: Union{Int, BigInt} = y + x

-(x::arb_poly, y::Rational{T}) where T <: Union{Int, BigInt} = x - parent(x)(y)

-(x::Rational{T}, y::arb_poly) where T <: Union{Int, BigInt} = parent(y)(x) - y

*(x::arb_poly, y::Rational{T}) where T <: Union{Int, BigInt} = x * parent(x)(y)

*(x::Rational{T}, y::arb_poly) where T <: Union{Int, BigInt} = y * x

###############################################################################
#
#   Scalar division
#
###############################################################################

for T in [Integer, fmpz, fmpq, Float64, BigFloat, arb]
   @eval begin
      divexact(x::arb_poly, y::$T) = x * inv(base_ring(parent(x))(y))

      //(x::arb_poly, y::$T) = divexact(x, y)
   end
end

divexact(x::arb_poly, y::Rational{T}) where {T <: Integer} = x * inv(base_ring(parent(x))(y))

//(x::arb_poly, y::Rational{T}) where {T <: Integer} = divexact(x, y)

###############################################################################
#
#   Euclidean division
#
###############################################################################

function divrem(x::arb_poly, y::arb_poly)
   iszero(y) && throw(DivideError())
   q = parent(x)()
   r = parent(x)()
   if (ccall((:arb_poly_divrem, :libarb), Int,
         (Ref{arb_poly}, Ref{arb_poly}, Ref{arb_poly}, Ref{arb_poly}, Int),
               q, r, x, y, prec(parent(x))) == 1)
      return (q, r)
   else
      throw(DivideError())
   end
end

function mod(x::arb_poly, y::arb_poly)
   return divrem(x, y)[2]
end

function divexact(x::arb_poly, y::arb_poly)
   return divrem(x, y)[1]
end

###############################################################################
#
#   Truncation
#
###############################################################################

function truncate(a::arb_poly, n::Int)
   n < 0 && throw(DomainError())
   if length(a) <= n
      return a
   end
   # todo: implement set_trunc in arb
   z = deepcopy(a)
   ccall((:arb_poly_truncate, :libarb), Void,
                (Ref{arb_poly}, Int), z, n)
   return z
end

function mullow(x::arb_poly, y::arb_poly, n::Int)
   n < 0 && throw(DomainError())
   z = parent(x)()
   ccall((:arb_poly_mullow, :libarb), Void,
         (Ref{arb_poly}, Ref{arb_poly}, Ref{arb_poly}, Int, Int),
            z, x, y, n, prec(parent(x)))
   return z
end

###############################################################################
#
#   Reversal
#
###############################################################################

#function reverse(x::arb_poly, len::Int)
#   len < 0 && throw(DomainError())
#   z = parent(x)()
#   ccall((:arb_poly_reverse, :libarb), Void,
#                (Ref{arb_poly}, Ref{arb_poly}, Int), z, x, len)
#   return z
#end

###############################################################################
#
#   Evaluation
#
###############################################################################

function evaluate(x::arb_poly, y::arb)
   z = parent(y)()
   ccall((:arb_poly_evaluate, :libarb), Void,
                (Ref{arb}, Ref{arb_poly}, Ref{arb}, Int),
                z, x, y, prec(parent(y)))
   return z
end

doc"""
    evaluate2(x::arb_poly, y::arb)
> Return a tuple $p, q$ consisting of the polynomial $x$ evaluated at $y$ and
> its derivative evaluated at $y$.
"""
function evaluate2(x::arb_poly, y::arb)
   z = parent(y)()
   w = parent(y)()
   ccall((:arb_poly_evaluate2, :libarb), Void,
                (Ref{arb}, Ref{arb}, Ref{arb_poly}, Ref{arb}, Int),
                z, w, x, y, prec(parent(y)))
   return z, w
end

function evaluate(x::arb_poly, y::acb)
   z = parent(y)()
   ccall((:arb_poly_evaluate_acb, :libarb), Void,
                (Ref{acb}, Ref{arb_poly}, Ref{acb}, Int),
                z, x, y, prec(parent(y)))
   return z
end

doc"""
    evaluate2(x::arb_poly, y::acb)
> Return a tuple $p, q$ consisting of the polynomial $x$ evaluated at $y$ and
> its derivative evaluated at $y$.
"""
function evaluate2(x::arb_poly, y::acb)
   z = parent(y)()
   w = parent(y)()
   ccall((:arb_poly_evaluate2_acb, :libarb), Void,
                (Ref{acb}, Ref{acb}, Ref{arb_poly}, Ref{acb}, Int),
                z, w, x, y, prec(parent(y)))
   return z, w
end

function evaluate(x::arb_poly, y::Union{Int,Float64,fmpq})
    return evaluate(x, base_ring(parent(x))(y))
end

function evaluate(x::arb_poly, y::fmpz)
    return evaluate(x, base_ring(parent(x))(y))
end

doc"""
    evaluate2(x::arb_poly, y::Integer)
> Return a tuple $p, q$ consisting of the polynomial $x$ evaluated at $y$ and
> its derivative evaluated at $y$.
"""
function evaluate2(x::arb_poly, y::Integer)
    return evaluate2(x, base_ring(parent(x))(y))
end

doc"""
    evaluate2(x::arb_poly, y::Float64)
> Return a tuple $p, q$ consisting of the polynomial $x$ evaluated at $y$ and
> its derivative evaluated at $y$.
"""
function evaluate2(x::arb_poly, y::Float64)
    return evaluate2(x, base_ring(parent(x))(y))
end

doc"""
    evaluate2(x::arb_poly, y::fmpz)
> Return a tuple $p, q$ consisting of the polynomial $x$ evaluated at $y$ and
> its derivative evaluated at $y$.
"""
function evaluate2(x::arb_poly, y::fmpz)
    return evaluate2(x, base_ring(parent(x))(y))
end

doc"""
    evaluate2(x::arb_poly, y::fmpq)
> Return a tuple $p, q$ consisting of the polynomial $x$ evaluated at $y$ and
> its derivative evaluated at $y$.
"""
function evaluate2(x::arb_poly, y::fmpq)
    return evaluate2(x, base_ring(parent(x))(y))
end

###############################################################################
#
#   Composition
#
###############################################################################

function compose(x::arb_poly, y::arb_poly)
   z = parent(x)()
   ccall((:arb_poly_compose, :libarb), Void,
                (Ref{arb_poly}, Ref{arb_poly}, Ref{arb_poly}, Int),
                z, x, y, prec(parent(x)))
   return z
end

###############################################################################
#
#   Derivative and integral
#
###############################################################################

function derivative(x::arb_poly)
   z = parent(x)()
   ccall((:arb_poly_derivative, :libarb), Void,
                (Ref{arb_poly}, Ref{arb_poly}, Int), z, x, prec(parent(x)))
   return z
end

function integral(x::arb_poly)
   z = parent(x)()
   ccall((:arb_poly_integral, :libarb), Void,
                (Ref{arb_poly}, Ref{arb_poly}, Int), z, x, prec(parent(x)))
   return z
end

###############################################################################
#
#   Multipoint evaluation and interpolation
#
###############################################################################

function arb_vec(n::Int)
   return ccall((:_arb_vec_init, :libarb), Ref{arb_struct}, (Int,), n)
end

function arb_vec(b::Array{arb, 1})
   v = ccall((:_arb_vec_init, :libarb), Ref{arb_struct}, (Int,), length(b))
   for i=1:length(b)
       ccall((:arb_set, :libarb), Void, (Ref{arb_struct}, Ref{arb}),
           v + (i-1)*sizeof(arb_struct), b[i])
   end
   return v
end

function array(R::ArbField, v::Ref{arb_struct}, n::Int)
   r = Array{arb}(n)
   for i=1:n
       r[i] = R()
       ccall((:arb_set, :libarb), Void, (Ref{arb}, Ref{arb_struct}),
           r[i], v + (i-1)*sizeof(arb_struct))
   end
   return r
end

function arb_vec_clear(v::Ref{arb_struct}, n::Int)
   ccall((:_arb_vec_clear, :libarb), Void, (Ref{arb_struct}, Int), v, n)
end

doc"""
    from_roots(R::ArbPolyRing, b::Array{arb, 1})
> Construct a polynomial in the given polynomial ring from a list of its roots.
"""
function from_roots(R::ArbPolyRing, b::Array{arb, 1})
   z = R()
   tmp = arb_vec(b)
   ccall((:arb_poly_product_roots, :libarb), Void,
                (Ref{arb_poly}, Ref{arb_struct}, Int, Int), z, tmp, length(b), prec(R))
   arb_vec_clear(tmp, length(b))
   return z
end

function evaluate_iter(x::arb_poly, b::Array{arb, 1})
   return arb[evaluate(x, b[i]) for i=1:length(b)]
end

function evaluate_fast(x::arb_poly, b::Array{arb, 1})
   tmp = arb_vec(b)
   ccall((:arb_poly_evaluate_vec_fast, :libarb), Void,
                (Ref{arb_struct}, Ref{arb_poly}, Ref{arb_struct}, Int, Int),
            tmp, x, tmp, length(b), prec(parent(x)))
   res = array(base_ring(parent(x)), tmp, length(b))
   arb_vec_clear(tmp, length(b))
   return res
end

function interpolate_newton(R::ArbPolyRing, xs::Array{arb, 1}, ys::Array{arb, 1})
   length(xs) != length(ys) && error()
   z = R()
   xsv = arb_vec(xs)
   ysv = arb_vec(ys)
   ccall((:arb_poly_interpolate_newton, :libarb), Void,
                (Ref{arb_poly}, Ref{arb_struct}, Ref{arb_struct}, Int, Int),
            z, xsv, ysv, length(xs), prec(R))
   arb_vec_clear(xsv, length(xs))
   arb_vec_clear(ysv, length(ys))
   return z
end

function interpolate_barycentric(R::ArbPolyRing, xs::Array{arb, 1}, ys::Array{arb, 1})
   length(xs) != length(ys) && error()
   z = R()
   xsv = arb_vec(xs)
   ysv = arb_vec(ys)
   ccall((:arb_poly_interpolate_barycentric, :libarb), Void,
                (Ref{arb_poly}, Ref{arb_struct}, Ref{arb_struct}, Int, Int),
            z, xsv, ysv, length(xs), prec(R))
   arb_vec_clear(xsv, length(xs))
   arb_vec_clear(ysv, length(ys))
   return z
end

function interpolate_fast(R::ArbPolyRing, xs::Array{arb, 1}, ys::Array{arb, 1})
   length(xs) != length(ys) && error()
   z = R()
   xsv = arb_vec(xs)
   ysv = arb_vec(ys)
   ccall((:arb_poly_interpolate_fast, :libarb), Void,
                (Ref{arb_poly}, Ref{arb_struct}, Ref{arb_struct}, Int, Int),
            z, xsv, ysv, length(xs), prec(R))
   arb_vec_clear(xsv, length(xs))
   arb_vec_clear(ysv, length(ys))
   return z
end

# todo: cutoffs for fast algorithm
function interpolate(R::ArbPolyRing, xs::Array{arb, 1}, ys::Array{arb, 1})
   return interpolate_newton(R, xs, ys)
end

# todo: cutoffs for fast algorithm
function evaluate(x::arb_poly, b::Array{arb, 1})
   return evaluate_iter(x, b)
end

###############################################################################
#
#   Root bounds
#
###############################################################################

doc"""
    roots_upper_bound(f::arb_poly) -> arb

> Returns an upper bound for the absolute value of all complex roots of $f$.
"""
function roots_upper_bound(x::arb_poly)
   z = base_ring(x)()
   p = prec(base_ring(x))
   t = ccall((:arb_rad_ptr, :libarb), Ref{mag_struct}, (Ref{arb}, ), z)
   ccall((:arb_poly_root_bound_fujiwara, :libarb), Void,
         (Ref{mag_struct}, Ref{arb_poly}), t, x)
   s = ccall((:arb_mid_ptr, :libarb), Ref{arf_struct}, (Ref{arb}, ), z)
   ccall((:arf_set_mag, :libarb), Void, (Ref{arf_struct}, Ref{mag_struct}), s, t)
   ccall((:arf_set_round, :libarb), Void,
         (Ref{arf_struct}, Ref{arf_struct}, Int, Cint), s, s, p, ARB_RND_CEIL)
   ccall((:mag_zero, :libarb), Void, (Ref{mag_struct},), t)
   return z
end

###############################################################################
#
#   Unsafe functions
#
###############################################################################

function zero!(z::arb_poly)
   ccall((:arb_poly_zero, :libarb), Void,
                    (Ref{arb_poly}, ), z)
   return z
end

function fit!(z::arb_poly, n::Int)
   ccall((:arb_poly_fit_length, :libarb), Void,
                    (Ref{arb_poly}, Int), z, n)
   return nothing
end

function setcoeff!(z::arb_poly, n::Int, x::fmpz)
   ccall((:arb_poly_set_coeff_fmpz, :libarb), Void,
                    (Ref{arb_poly}, Int, Ref{fmpz}), z, n, x)
   return z
end

function setcoeff!(z::arb_poly, n::Int, x::arb)
   ccall((:arb_poly_set_coeff_arb, :libarb), Void,
                    (Ref{arb_poly}, Int, Ref{arb}), z, n, x)
   return z
end

function mul!(z::arb_poly, x::arb_poly, y::arb_poly)
   ccall((:arb_poly_mul, :libarb), Void,
                (Ref{arb_poly}, Ref{arb_poly}, Ref{arb_poly}, Int),
                    z, x, y, prec(parent(z)))
   return z
end

function addeq!(z::arb_poly, x::arb_poly)
   ccall((:arb_poly_add, :libarb), Void,
                (Ref{arb_poly}, Ref{arb_poly}, Ref{arb_poly}, Int),
                    z, z, x, prec(parent(z)))
   return z
end

function add!(z::arb_poly, x::arb_poly, y::arb_poly)
   ccall((:arb_poly_add, :libarb), Void,
                (Ref{arb_poly}, Ref{arb_poly}, Ref{arb_poly}, Int),
                    z, x, y, prec(parent(z)))
   return z
end

###############################################################################
#
#   Promotions
#
###############################################################################

promote_rule(::Type{arb_poly}, ::Type{Float64}) = arb_poly

promote_rule(::Type{arb_poly}, ::Type{BigFloat}) = arb_poly

promote_rule(::Type{arb_poly}, ::Type{fmpz}) = arb_poly

promote_rule(::Type{arb_poly}, ::Type{fmpq}) = arb_poly

promote_rule(::Type{arb_poly}, ::Type{arb}) = arb_poly

promote_rule(::Type{arb_poly}, ::Type{fmpz_poly}) = arb_poly

promote_rule(::Type{arb_poly}, ::Type{fmpq_poly}) = arb_poly

promote_rule(::Type{arb_poly}, ::Type{T}) where {T <: Integer} = arb_poly

promote_rule(::Type{arb_poly}, ::Type{Rational{T}}) where T <: Union{Int, BigInt} = arb_poly

################################################################################
#
#  Parent object call overloads
#
################################################################################

function (a::ArbPolyRing)()
   z = arb_poly()
   z.parent = a
   return z
end

for T in [Integer, fmpz, fmpq, Float64, arb, BigFloat]
   @eval begin
      function (a::ArbPolyRing)(b::$T)
         z = arb_poly(base_ring(a)(b), a.base_ring.prec)
         z.parent = a
         return z
      end
   end
end

function (a::ArbPolyRing)(b::Rational{T}) where {T <: Integer}
   z = arb_poly(base_ring(a)(b), a.base_ring.prec)
   z.parent = a
   return z
end

function (a::ArbPolyRing)(b::Array{arb, 1})
   z = arb_poly(b, a.base_ring.prec)
   z.parent = a
   return z
end

for T in [fmpz, fmpq, Float64, BigFloat]
   @eval begin
      (a::ArbPolyRing)(b::Array{$T, 1}) = a(map(base_ring(a), b))
   end
end

(a::ArbPolyRing)(b::Array{T, 1}) where {T <: Integer} = a(map(base_ring(a), b))

(a::ArbPolyRing)(b::Array{Rational{T}, 1}) where {T <: Integer} = a(map(base_ring(a), b))

function (a::ArbPolyRing)(b::fmpz_poly)
   z = arb_poly(b, a.base_ring.prec)
   z.parent = a
   return z
end

function (a::ArbPolyRing)(b::fmpq_poly)
   z = arb_poly(b, a.base_ring.prec)
   z.parent = a
   return z
end

function (a::ArbPolyRing)(b::arb_poly)
   z = arb_poly(b, a.base_ring.prec)
   z.parent = a
   return z
end

################################################################################
#
#  PolynomialRing constructor
#
################################################################################

function PolynomialRing(R::ArbField, s::AbstractString; cached = true)
  S = Symbol(s)
  parent_obj = ArbPolyRing(R, S, cached)
  return parent_obj, parent_obj(fmpz_poly([fmpz(0), fmpz(1)]))
end


text:
function readinput(filename)
    groups = map(x -> eachmatch(r"(e|se|sw|w|nw|ne)", x), readlines(filename))
end

function sumtuple(a, b, dims)
    return ntuple(i -> a[i] + b[i], dims)
end

function blacktiles(lines)
    blacks = Set()
    for line in lines
        point = (0,0,0)
        for d in line
            point = sumtuple(point, hd[d[1]], 3)
        end
        if point in blacks
            pop!(blacks, point)
        else
            push!(blacks, point)
        end
    end
    return blacks
end

function changetiles(blacks)
    newblacks = Set()
    check = Set()
    for b in blacks
        push!(check,b)
        for d in values(hd)
            push!(check,sumtuple(b,d,3))
        end
    end
    for c in check
        n = 0
        for d in values(hd)
            if sumtuple(c,d,3) in blacks
                n += 1
            end
        end
        if c in blacks && (n == 1 || n == 2)
            push!(newblacks,c)
        end
        if !(c in blacks) && n == 2
            push!(newblacks,c)
        end
    end
    return newblacks
end

function looptiles(blacks, cycles)
    for i in 1:cycles
        blacks = changetiles(blacks)
    end
    return blacks
end

hd = Dict("e"=>(1,-1,0),"se"=>(0,-1,1),"sw"=>(-1,0,1),"w"=>(-1,1,0),"nw"=>(0,1,-1),"ne"=>(1,0,-1))

lines = readinput("d24.in")
blacks1 = blacktiles(lines)
blacks2 = looptiles(blacks1, 100)

println("P1: ", length(blacks1))
println("P2: ", length(blacks2))

max_stars_repo_name: eduellery/adventofcode

max_issues_repo_name: eduellery/adventofcode

max_forks_repo_name: eduellery/adventofcode