text:
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
# Description
#
#   Tests related to the text backend.
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

data = Any[1    false      1.0     0x01 ;
           2     true      2.0     0x02 ;
           3    false      3.0     0x03 ;
           4     true      4.0     0x04 ;
           5    false      5.0     0x05 ;
           6     true      6.0     0x06 ;]

@testset "Default tests" begin
    include("text_backend/default.jl")
end

@testset "Alignments" begin
    include("text_backend/alignments.jl")
end

@testset "Column width" begin
    include("text_backend/column_width.jl")
end

@testset "Colors" begin
    # Those tests are failing in Windows for Julia 1.0.
    if (VERSION > v"1.1") || !Sys.iswindows()
        include("text_backend/colors.jl")
    end
end

@testset "Cropping" begin
    include("text_backend/cropping.jl")
end

@testset "Filters" begin
    include("text_backend/filters.jl")
end

@testset "Formatters" begin
    include("text_backend/formatters.jl")
end

@testset "Headers" begin
    include("text_backend/headers.jl")
end

@testset "Helpers" begin
    include("text_backend/helpers.jl")
end

@testset "Line breaks" begin
    include("text_backend/line_breaks.jl")
end

@testset "Markdown" begin
    include("text_backend/markdown.jl")
end

@testset "Renderers" begin
    include("text_backend/renderers.jl")
end

@testset "Row names" begin
    include("text_backend/row_names.jl")
end

@testset "Row numbers" begin
    include("text_backend/row_numbers.jl")
end

@testset "Table lines" begin
    include("text_backend/table_lines.jl")
end

@testset "Table.jl compatibility" begin
    include("text_backend/tables.jl")
end

@testset "Titles" begin
    include("text_backend/titles.jl")
end

@testset "UTF-8" begin
    include("text_backend/utf8.jl")
end

@testset "Issues" begin
    include("text_backend/issues.jl")
end


text:
"""

$(TYPEDEF)

Structure to contain PDB trajectories. Frames must be separated by "END", and with periodic cell sizes
in the "CRYST1" field.

This structure and functions can be used as a template to implement the reading of other
trajectory formats.

$(TYPEDFIELDS)

"""
struct PDBTraj{T<:AbstractVector} <: Trajectory

    #
    # Mandatory data for things to work
    #
    filename::String
    stream::IOStream
    nframes::Int64

    # This vector must be filled up with the size vectors of the periodic cell
    sides::Vector{T}

    # Solute and solvent data
    solute::Selection
    solvent::Selection

    # Coordinates of the solute and solvent atoms in a frame (natoms,3) for each array:
    x_solute::Vector{T}  # solute.natoms vectors of length 3
    x_solvent::Vector{T} # solvent.natoms vectors of length 3

    #
    # Additional data required for input/output functions
    #
    natoms::Int64

    # Auxiliary vectors to contain all coordinates of a frame on reading
    x_read::Array{Float64,2}

end

"""

```
PDBTraj(pdbfile::String, solute::Selection, solvent::Selection;T::Type = SVector{3,Float64})
```

Function open will set up the IO stream of the trajectory, fill up the
number of frames field and additional parameters if required

The IO stream must be returned in a position such that the "nextframe!" function
will be able to read the first frame of the trajectory

"""
function PDBTraj(
    pdbfile::String,
    solute::Selection,
    solvent::Selection;
    T::Type = SVector{3,Float64},
)

    stream = open(pdbfile, "r")

    # Get the number of frames and number of atoms, check for adequacy of the format
    nframes = 0
    natoms = 0
    for line in eachline(stream)
        if line[1:3] == "END"
            nframes = nframes + 1
        elseif nframes == 0 && (line[1:4] == "ATOM" || line[1:6] == "HETATM")
            natoms = natoms + 1
        end
    end
    close(stream)

    # Fill-up the sides vector of the trajectory. We assume here
    # that the sides are stored for each frame in the "CRYST1" field, for each frame.
    # Here, we exemplify the option to read all sides at once and store them in a
    # vector. Alternatively, the sides could be read for each frame
    # independently within the "nextframe!" function, and saved as a sides(3) vector.
    # The function "getsides", below, must be adapted accordingly to return the correct
    # sides of the periodic box in each frame.

    sides = zeros(T, nframes)
    stream = open(pdbfile, "r")
    iframe = 0
    for line in eachline(stream)
        s = split(line)
        if s[1] == "CRYST1"
            iframe = iframe + 1
            sides[iframe] =
                T(parse(Float64, s[2]), parse(Float64, s[3]), parse(Float64, s[4]))
        end
    end
    close(stream)

    # Open again the stream, so that nextrame can read the first frame
    stream = open(pdbfile, "r")

    return PDBTraj(
        pdbfile, # trajectory file name
        stream,
        nframes,
        sides, # array containing box sides
        solute,
        solvent,
        zeros(T, solute.natoms),
        zeros(T, solvent.natoms),
        natoms, # Total number of atoms
        Array{Float64}(undef, 3, natoms), # Auxiliary array for reading
    )
end

function Base.show(io::IO, trajectory::PDBTraj)
    println(" Trajectory in PDB format with: ")
    println("    $(trajectory.nframes) frames.")
    println("    $(trajectory.natoms) atoms.")
end

#
# Function that reads the coordinates of the solute and solvent atoms from
# the next frame of the trajectory file
#
# The function modifies sides, x_solute and x_solvent within the trajectory structure.
# Having these vectors inside the trajectory structure avoids having to allocate
# them everytime a new frame is read
#

function nextframe!(trajectory::PDBTraj{T}) where {T}

    iatom = 0
    record = readline(trajectory.stream)
    while ((0 < length(record) < 3) || record[1:3] != "END")
        if length(record) >= 6
            if record[1:4] == "ATOM" || record[1:6] == "HETATM"
                iatom = iatom + 1
                trajectory.x_read[1, iatom] = parse(Float64, record[31:38])
                trajectory.x_read[2, iatom] = parse(Float64, record[39:46])
                trajectory.x_read[3, iatom] = parse(Float64, record[47:54])
            end
        end
        record = readline(trajectory.stream)
    end

    # Save coordinates of solute and solvent in trajectory arrays
    for i = 1:trajectory.solute.natoms
        trajectory.x_solute[i] = T(
            trajectory.x_read[1, trajectory.solute.index[i]],
            trajectory.x_read[2, trajectory.solute.index[i]],
            trajectory.x_read[3, trajectory.solute.index[i]],
        )
    end
    for i = 1:trajectory.solvent.natoms
        trajectory.x_solvent[i] = T(
            trajectory.x_read[1, trajectory.solvent.index[i]],
            trajectory.x_read[2, trajectory.solvent.index[i]],
            trajectory.x_read[3, trajectory.solvent.index[i]],
        )
    end

end

# Function that returns the sides of the periodic box given the data structure. In this
# case, returns the 3-element vector corresponding to the box sides of the given frame

function getsides(trajectory::PDBTraj, iframe)
    # Sides is expected to be an array that contains the sides for each frame, and we return the
    # vector containing the sides of the current fraem
    return trajectory.sides[iframe]
end

#
# Function that closes the IO Stream of the trajectory
#
closetraj(trajectory::PDBTraj) = close(trajectory.stream)

#
# Function that returns the trajectory in position to read the first frame
#
firstframe(trajectory::PDBTraj) = seekstart(trajectory.stream)

ext: jl


text:
##  SCRIPT NAME:   equalityConstraints1.jl
##  DATE:          March 2015
#
#   This script returns the equality constraints subject to which the
#   family maximises its objective function in each period. If a constraint
#   is of the following form:
#   x + y = a
#   then this must be returned by this script as:
#   result[i] = x + y - a
#   which is set to 0 by the optimiser. The family problem is subject to the
#   following constraints:
#   (a) sequential budget constraint
#
#
##  ALEXANDROS THELOUDIS, UCL

##  ---------------------------------------------------------------------------------------------

function equalityConstraints1(choice_var::Vector, grad::Vector, A0, wH0, wW0, p0)

  # Declare choice variables:
  A!    = choice_var[1]
  consH = choice_var[2]
  consW = choice_var[3]
  kons  = choice_var[4]

  # Calculate gradient:
  if length(grad) > 0
    grad[1] = -1/(1+r)
    grad[2] = -p0
    grad[3] = -p0
    grad[4] = -1
  end

  # Write equality constraints and return results:
  # (a) Sequential budget constraint:
  A0 + wH0*maxAnnWorkingHrsH + wW0*maxAnnWorkingHrsW - p0*(consH + consW) - kons - A!/(1+r)

end

max_stars_repo_name: floswald/ucl-econ-julia

max_issues_repo_name: floswald/ucl-econ-julia

max_forks_repo_name: floswald/ucl-econ-julia


text:
Base.print(io::IO, loss::SupervisedLoss, args...) = print(io, typeof(loss).name.name, args...)
Base.print(io::IO, loss::L1DistLoss, args...) = print(io, "L1DistLoss", args...)
Base.print(io::IO, loss::L2DistLoss, args...) = print(io, "L2DistLoss", args...)
Base.print(io::IO, loss::LPDistLoss{P}, args...) where {P} = print(io, typeof(loss).name.name, " with P = $(P)", args...)
Base.print(io::IO, loss::L1EpsilonInsLoss, args...) = print(io, typeof(loss).name.name, " with \$\\epsilon\$ = $(loss.ε)", args...)
Base.print(io::IO, loss::L2EpsilonInsLoss, args...) = print(io, typeof(loss).name.name, " with \$\\epsilon\$ = $(loss.ε)", args...)
Base.print(io::IO, loss::QuantileLoss, args...) = print(io, typeof(loss).name.name, " with \$\\tau\$ = $(loss.τ)", args...)
Base.print(io::IO, loss::SmoothedL1HingeLoss, args...) = print(io, typeof(loss).name.name, " with \$\\gamma\$ = $(loss.gamma)", args...)
Base.print(io::IO, loss::HuberLoss, args...) = print(io, typeof(loss).name.name, " with \$\\alpha\$ = $(loss.d)", args...)
Base.print(io::IO, loss::DWDMarginLoss, args...) = print(io, typeof(loss).name.name, " with q = $(loss.q)", args...)
Base.print(io::IO, loss::PeriodicLoss, args...) = print(io, typeof(loss).name.name, " with c = $(round(2π / loss.k, digits=1))", args...)
Base.print(io::IO, loss::ScaledLoss{T,K}, args...) where {T,K} = print(io, "$(K) * ($(loss.loss))", args...)

# Pretty print weighted loss
_round(num) = round(num) == round(num, digits=1) ? round(Int, num) : round(num, digits=1)
function _relation(num)
    if num <= 0
        "negative only"
    elseif num >= 1
        "positive only"
    elseif num < 0.5
        "1:$(_round((1-num)/num)) weighted"
    else
        "$(_round(num/(1-num))):1 weighted"
    end
end

Base.print(io::IO, loss::WeightedBinaryLoss{T,W}, args...) where {T,W} = print(io, "$(_relation(W)) $(loss.loss)", args...)

# -------------------------------------------------------------
# Plot Recipes

_loss_xguide(loss::MarginLoss) = "y * h(x)"
_loss_xguide(loss::DistanceLoss) = "h(x) - y"
_loss_yguide(loss::SupervisedLoss) = "L("*_loss_xguide(loss)*")"

@recipe function plot(loss::SupervisedLoss, range=-2:0.05:2; fun=value)
    xguide --> _loss_xguide(loss)
    yguide --> _loss_yguide(loss)
    label  --> string(loss)
    l(a) = fun(loss, a)
    l, range
end


text:
export Transform
module Transform

# ---------------------
# Elementwise transform
# ---------------------

export Elementwise

"""
    Elementwise{F}

A simple transformation that applies a function elementwise.

# Example
```julia
double_elements = Elementwise(x -> x * 2)
```
"""
struct Elementwise{F}
    func::F
end

@inline Elementwise() = Elementwise(identity)

@inline (transf::Elementwise)(x, tile) = transf.func.(x)

end


text:
abstract type WilsonFermion_4D{NC} <: AbstractFermionfields_4D{NC}
end

function Wx!(xout::T,U::Array{G,1},x::T,A)  where  {T <: WilsonFermion_4D,G <: AbstractGaugefields}
    Wx!(xout,U,x,A,4)
    return
end

function Dx!(xout::T1,U::Array{G,1},x::T2,A) where  {T1 <: WilsonFermion_4D,T2 <: WilsonFermion_4D,G <: AbstractGaugefields}
    Dx!(xout,U,x,A,4)
    return
end

function Ddagx!(xout::T1,U::Array{G,1},x::T2,A) where  {T1 <: WilsonFermion_4D,T2 <: WilsonFermion_4D,G <: AbstractGaugefields}
    Ddagx!(xout,U,x,A,4)
    return
end

function Tx!(xout::T,U::Array{G,1},x::T,A)  where  {T <: WilsonFermion_4D,G <: AbstractGaugefields} # Tx, W = (1 - T)x
    Tx!(xout,U,x,A,4)
    return
end

function Wdagx!(xout::T,U::Array{G,1},
    x::T,A) where  {T <: WilsonFermion_4D,G <: AbstractGaugefields}
    #,temps::Array{T,1},boundarycondition) where  {T <: WilsonFermion_4D,G <: AbstractGaugefields}
    Wdagx!(xout,U,x,A,4)
    return
end

function calc_beff!(xout,U,x,A) #be + K Teo bo
    isodd = false
    temp = A._temporary_fermi[4]#temps[4]
    clear_fermion!(temp,isodd)
    Toex!(temp,U,x,A,isodd)

    iseven = true
    add_fermion!(xout,1,x,1,temp,iseven)

end

function calc_beff_dag!(xout,U,x,A) #be + K Teo bo
    isodd = false
    temp = A._temporary_fermi[4]#temps[4]
    clear_fermion!(temp)
    Tdagoex!(temp,U,x,A,isodd)

    iseven = true
    add_fermion!(xout,1,x,1,temp,iseven)

end

function Toex!(xout::T,U::Array{G,1},x::T,A,iseven)  where  {T <: WilsonFermion_4D,G <: AbstractGaugefields} #T_oe xe
    #temp = A._temporary_fermi[4]#temps[4]
    temp1 = A._temporary_fermi[1] #temps[1]
    temp2 = A._temporary_fermi[2] #temps[2]

    #temp = temps[4]
    #temp1 = temps[1]
    #temp2 = temps[2]
    if iseven
        isodd = false
    else
        isodd  =true
    end

    #clear_fermion!(temp,isodd)
    clear_fermion!(xout,isodd)
    #set_wing_fermion!(x)
    for ν=1:4

        xplus = shift_fermion(x,ν)
        #println(xplus)

        mul!(temp1,U[ν],xplus,isodd)

        #fermion_shift!(temp1,U,ν,x)

        #... Dirac multiplication

        mul!(temp1,view(A.rminusγ,:,:,ν),isodd)

        xminus = shift_fermion(x,-ν)
        Uminus = shift_U(U[ν],-ν)

        mul!(temp2,Uminus',xminus,isodd)

        #
        #fermion_shift!(temp2,U,-ν,x)
        #mul!(temp2,view(x.rplusγ,:,:,ν),temp2)
        mul!(temp2,view(A.rplusγ,:,:,ν),isodd)

        add_fermion!(xout,A.hopp[ν],temp1,A.hopm[ν],temp2,isodd)

    end

    #clear_fermion!(xout,isodd)
    #add_fermion!(xout,1,x,-1,temp)

    set_wing_fermion!(xout,A.boundarycondition,isodd)

end

function Tdagoex!(xout::T,U::Array{G,1},x::T,A,iseven)  where  {T <: WilsonFermion_4D,G <: AbstractGaugefields} #T_oe xe
    #temp = A._temporary_fermi[4]#temps[4]
    temp1 = A._temporary_fermi[1] #temps[1]
    temp2 = A._temporary_fermi[2] #temps[2]

    #temp = temps[4]
    #temp1 = temps[1]
    #temp2 = temps[2]
    if iseven
        isodd = false
    else
        isodd  =true
    end

    #clear_fermion!(temp,isodd)
    clear_fermion!(xout,isodd)
    #set_wing_fermion!(x)
    for ν=1:4

        xplus = shift_fermion(x,ν)
        #println(xplus)

        mul!(temp1,U[ν],xplus,isodd)

        #fermion_shift!(temp1,U,ν,x)

        #... Dirac multiplication

        mul!(temp1,view(A.rplusγ,:,:,ν),isodd)

        xminus = shift_fermion(x,-ν)
        Uminus = shift_U(U[ν],-ν)

        mul!(temp2,Uminus',xminus,isodd)

        #
        #fermion_shift!(temp2,U,-ν,x)
        #mul!(temp2,view(x.rplusγ,:,:,ν),temp2)
        mul!(temp2,view(A.rminusγ,:,:,ν),isodd)

        add_fermion!(xout,A.hopp[ν],temp1,A.hopm[ν],temp2,isodd)

    end

    #clear_fermion!(xout,isodd)
    #add_fermion!(xout,1,x,-1,temp)

    set_wing_fermion!(xout,A.boundarycondition)

end

function WWx!(xout::T,U::Array{G,1},x::T,A)  where  {T <: WilsonFermion_4D,G <: AbstractGaugefields} #(1 - K^2 Teo Toe) xe
    iseven = true
    isodd = false
    temp = A._temporary_fermi[7]#temps[4]
    temp2 = A._temporary_fermi[6]#temps[4]

    #println("Wx")
    #@time Wx!(xout,U,x,A)
    clear_fermion!(xout,iseven)

    #Tx!(temp,U,x,A)
    Toex!(temp,U,x,A,iseven) #Toe
    #Tx!(temp2,U,temp,A)
    Toex!(temp2,U,temp,A,isodd) #Teo

    #set_wing_fermion!(temp,A.boundarycondition)
    #add_fermion!(xout,1,x,-1,temp2)
    add_fermion!(xout,1,x,-1,temp2,iseven)
    set_wing_fermion!(xout,A.boundarycondition,iseven)

    #Wx!(xout,U,x,A)
    return

    #Tx!(temp2,U,x,A) #Toe

    #Toex!(temp2,U,x,A,iseven) #Toe

    #Toex!(temp,U,temp2,A,isodd) #Teo
    #Tx!(temp,U,temp2,A) #Toe

    Tx!(temp,U,x,A) #Toe

    add_fermion!(xout,1,x,-1,temp)
    #add_fermion!(xout,1,x,-1,temp,iseven)

    iseven = true
    set_wing_fermion!(xout,A.boundarycondition)

    return
end

function WWdagx!(xout::T,U::Array{G,1},x::T,A)  where  {T <: WilsonFermion_4D,G <: AbstractGaugefields} #(1 - K^2 Teo Toe) xe
    iseven = true
    isodd = false
    temp = A._temporary_fermi[7]#temps[4]
    temp2 = A._temporary_fermi[6]#temps[4]

    clear_fermion!(xout)

    #Tx!(temp,U,x,A)
    Tdagoex!(temp,U,x,A,iseven) #Toe
    #Tx!(temp2,U,temp,A)
    Tdagoex!(temp2,U,temp,A,isodd) #Teo

    #set_wing_fermion!(temp,A.boundarycondition)
    #add_fermion!(xout,1,x,-1,temp2)
    add_fermion!(xout,1,x,-1,temp2,iseven)
    set_wing_fermion!(xout,A.boundarycondition)

    return
end


text:
"""
    ex4_1_1(; formulation=1)
``trig'' is an MINLPLib test instance with one variable and power terms
(see http://www.minlplib.org/ex4_1_1.html). The global objective value for
this problem is -7.48731237. This code illustrates the strength of the
relaxation obtained by introducing one artificial variable for each non-linear
term as against one variable for the the entire univariate function.
Variables: -2 <= x <= 11; start = 10
Objective: Minimize 0.1 + x^6 - 2.08 * x^5 + 0.4875 * x^4 + 7.1 * x^3 - 3.95 * x^2 - x

The reformulation using one additional variable is as follows:
Variables:
    -2 <= x <= 11; start = 10
    y
Constraints: y = 0.1 + x^6 - 2.08 * x^5 + 0.4875 * x^4 + 7.1 * x^3 - 3.95 * x^2 - x
Objective: Minimize y

The reformulation using multiple additional variables is as follows:
Variables:
    -2 <= x <= 11; start = 10
    y[1:5]
Constraints:
    y[1] = x^6
    y[2] = -2.08 * x^5
    y[3] = 0.4875 * x^4
    y[4] = 7.1 * x^3
    y[5] = -3.95 * x^2
Objective: Minimize 0.1 + y[1] + y[2] + y[3] + y[4] + y[5] - x
"""

function ex4_1_1(; formulation = 1)
    if formulation == 1
        ex4_1_1_single()
    else
        ex4_1_1_multiple()
    end
end

function ex4_1_1_single()
    best_known_objective = -7.48731237
    cplex_optimizer =
        JuMP.optimizer_with_attributes(CPLEX.Optimizer, "CPX_PARAM_SCRIND" => 0)
    error_tolerances = [NaN64, 1e-1, 1e-2]
    base_partition = [-2.0, -1.7747, 0.1753, 11.0]
    milp_statistics = zeros(length(error_tolerances), 5)
    lp_statistics = zeros(length(error_tolerances), 5)
    func = x -> 0.1 + x^6 - 2.08 * x^5 + 0.4875 * x^4 + 7.1 * x^3 - 3.95 * x^2 - x
    for i = 1:length(error_tolerances)
        error_tolerance = error_tolerances[i]
        # construct MILP relaxations
        milp = Model(cplex_optimizer)
        milp_var, x_index, y_index =
            add_milp_relaxation(func, base_partition, error_tolerance, milp)
        @objective(milp, Min, milp_var[y_index])
        _, solve_time, solve_bytes_alloc, sec_in_gc = @timed optimize!(milp)
        relaxation_objective = objective_value(milp)
        @assert relaxation_objective ≤ best_known_objective
        relative_gap =
            abs(best_known_objective - relaxation_objective) / abs(relaxation_objective)
        milp_statistics[i, :] = [
            error_tolerance,
            best_known_objective,
            relaxation_objective,
            relative_gap,
            round(solve_time, digits = 2),
        ]
    end

    for i = 1:length(error_tolerances)
        error_tolerance = error_tolerances[i]
        # construct LP relaxations
        lp = Model(cplex_optimizer)
        lp_var, x_index, y_index =
            add_lp_relaxation(func, base_partition, error_tolerance, lp)
        @objective(lp, Min, lp_var[y_index])
        _, solve_time, solve_bytes_alloc, sec_in_gc = @timed optimize!(lp)
        relaxation_objective = objective_value(lp)
        @assert relaxation_objective ≤ best_known_objective
        relative_gap =
            abs(best_known_objective - relaxation_objective) / abs(relaxation_objective)
        lp_statistics[i, :] = [
            error_tolerance,
            best_known_objective,
            relaxation_objective,
            relative_gap,
            round(solve_time, digits = 2),
        ]
    end

    open("csv/single_ex4_1_1_milp.csv", "w") do io
        writedlm(io, ["error_tol" "g_opt" "relaxation" "relative_gap" "time"], ',')
        writedlm(io, milp_statistics, ",")
    end

    open("csv/single_ex4_1_1_lp.csv", "w") do io
        writedlm(io, ["error_tol" "g_opt" "relaxation" "relative_gap" "time"], ',')
        writedlm(io, lp_statistics, ",")
    end
end

function ex4_1_1_multiple()
    best_known_objective = -7.48731237
    cplex_optimizer =
        JuMP.optimizer_with_attributes(CPLEX.Optimizer, "CPX_PARAM_SCRIND" => 0)
    error_tolerances = [NaN64, 1e-1, 1e-2]
    base_partition = [-2.0, 0.0, 11.0]
    milp_statistics = zeros(length(error_tolerances), 5)
    lp_statistics = zeros(length(error_tolerances), 5)
    functions = Dict{Int,Function}()
    functions[1] = x -> x^6
    functions[2] = x -> -2.08 * x^5
    functions[3] = x -> 0.4875 * x^4
    functions[4] = x -> 7.1 * x^3
    functions[5] = x -> -3.95 * x^2
    for i = 1:length(error_tolerances)
        error_tolerance = error_tolerances[i]
        milp = Model(cplex_optimizer)
        milp_var = Dict{Int,Any}()
        x_indexes = Dict{Int,Int}()
        y_indexes = Dict{Int,Int}()
        # construct MILP relaxations
        for j = 1:5
            var, x_index, y_index = add_milp_relaxation(
                functions[j],
                base_partition,
                error_tolerance,
                milp,
                name = string(j),
            )
            milp_var[j] = var
            x_indexes[j] = x_index
            y_indexes[j] = y_index
            (j == 1) && (continue)
            @constraint(milp, var[x_index] == milp_var[1][x_indexes[1]])
        end
        @objective(
            milp,
            Min,
            0.1 + sum(milp_var[j][y_indexes[j]] for j = 1:5) - milp_var[1][x_indexes[1]]
        )
        _, solve_time, solve_bytes_alloc, sec_in_gc = @timed optimize!(milp)
        relaxation_objective = objective_value(milp)
        @assert relaxation_objective ≤ best_known_objective
        relative_gap =
            abs(best_known_objective - relaxation_objective) / abs(relaxation_objective)
        milp_statistics[i, :] = [
            error_tolerance,
            best_known_objective,
            relaxation_objective,
            relative_gap,
            round(solve_time, digits = 2),
        ]
    end

    for i = 1:length(error_tolerances)
        error_tolerance = error_tolerances[i]
        lp = Model(cplex_optimizer)
        lp_var = Dict{Int,Any}()
        x_indexes = Dict{Int,Int}()
        y_indexes = Dict{Int,Int}()
        # construct LP relaxations
        for j = 1:5
            var, x_index, y_index = add_lp_relaxation(
                functions[j],
                base_partition,
                error_tolerance,
                lp,
                name = string(j),
            )
            lp_var[j] = var
            x_indexes[j] = x_index
            y_indexes[j] = y_index
            (j == 1) && (continue)
            @constraint(lp, var[x_index] == lp_var[1][x_indexes[1]])
        end
        @objective(
            lp,
            Min,
            0.1 + sum(lp_var[j][y_indexes[j]] for j = 1:5) - lp_var[1][x_indexes[1]]
        )
        _, solve_time, solve_bytes_alloc, sec_in_gc = @timed optimize!(lp)
        relaxation_objective = objective_value(lp)
        @assert relaxation_objective ≤ best_known_objective
        relative_gap =
            abs(best_known_objective - relaxation_objective) / abs(relaxation_objective)
        lp_statistics[i, :] = [
            error_tolerance,
            best_known_objective,
            relaxation_objective,
            relative_gap,
            round(solve_time, digits = 2),
        ]
    end

    open("csv/multiple_ex4_1_1_milp.csv", "w") do io
        writedlm(io, ["error_tol" "g_opt" "relaxation" "relative_gap" "time"], ',')
        writedlm(io, milp_statistics, ",")
    end

    open("csv/multiple_ex4_1_1_lp.csv", "w") do io
        writedlm(io, ["error_tol" "g_opt" "relaxation" "relative_gap" "time"], ',')
        writedlm(io, lp_statistics, ",")
    end
end

max_stars_repo_name: sujeevraja/univariate-experiments

max_issues_repo_name: sujeevraja/univariate-experiments

max_forks_repo_name: sujeevraja/univariate-experiments


text:
export lerp, linear

# Lerp returns a the value between min and max given t = 0->1
function lerp(min::T, max::T, t::T) where {T <: AbstractFloat}
    min * (1.0 - t) + max * t
end

# As per:
# https://gamedev.stackexchange.com/questions/18615/how-do-i-linearly-interpolate-between-two-vectors
function lerp(min::Math.Vector2D{T}, max::Math.Vector2D{T}, t::T, out::Math.Vector2D{T}) where {T <: AbstractFloat}
    Math.scale!(min, (1.0 - t), v1)
    Math.scale!(max, t, v2)
    Math.add!(v1, v2, out)
end

# TODO new to review for negative ranges.
# `linear` returns 0->1 for a "value" between min and max.
# Generally used to map from view-space to unit-space
function linear(min::T, max::T, value::T) where {T <: AbstractFloat}
    if min < 0.0
        (value - max) / (min - max)
    else
        (value - min) / (max - min)
    end
end

max_stars_repo_name: wdevore/Ranger-Julia-SDL

max_issues_repo_name: wdevore/Ranger-Julia-SDL

max_forks_repo_name: wdevore/Ranger-Julia-SDL


text:
using FinancePlus
using Test

@testset "FinancePlus.jl" begin
    # Write your tests here.
    @test FinancePlus.simple_interest(100.00 , 0.1 ,2) == 20.0
    @test FinancePlus.compound_interest(100.00 , 0.1 ,2) == 21.000000000000014
    @test FinancePlus.future_value(100.00 , 0.1 ,2) == 121.00000000000001
    @test FinancePlus.present_value(121.00000000000001 , 0.1 ,2) == 100.00
    @test FinancePlus.future_value(100.00 , 0.1 ,2, 1) == 121.00000000000001
    @test FinancePlus.future_value(100.00 , 0.1 ,2, 2) == 121.55062500000003
    @test FinancePlus.present_value(121.00000000000001 , 0.1 ,2, 2) == 99.54699944981772
    @test FinancePlus.present_value(121.00000000000001 , 0.1 ,2, 1) == 100.00
    @test FinancePlus.present_annuity(50000.00 , 0.06 ,25) == 639167.8079134206
    @test FinancePlus.present_annuity_due(50000.00 , 0.06 ,25) == 677517.8763882258
    @test FinancePlus.present_value_interest_factor(0.05 ,5) == 0.7835261664684589
    @test FinancePlus.future_value_interest_factor(0.05 ,5) == 1.2762815625000004

end


text:
module Why

# Driving sim.  Why did he crash?
# That block game.
# Labour coercion model.  Why did labour coercion increase?

greet() = print("Hello World!")

end # module


text:
module SimplifyEquationModule

import ..CoreModule: CONST_TYPE, Node, copy_node, Options
import ..CheckConstraintsModule: check_constraints
import ..UtilsModule: isbad, isgood

# Simplify tree
function combine_operators(tree::Node, options::Options)::Node
    # NOTE: (const (+*-) const) already accounted for. Call simplify_tree before.
    # ((const + var) + const) => (const + var)
    # ((const * var) * const) => (const * var)
    # ((const - var) - const) => (const - var)
    # (want to add anything commutative!)
    # TODO - need to combine plus/sub if they are both there.
    if tree.degree == 0
        return tree
    elseif tree.degree == 1
        tree.l = combine_operators(tree.l, options)
    elseif tree.degree == 2
        tree.l = combine_operators(tree.l, options)
        tree.r = combine_operators(tree.r, options)
    end

    top_level_constant = tree.degree == 2 && (tree.l.constant || tree.r.constant)
    if tree.degree == 2 &&
        (options.binops[tree.op] == (*) || options.binops[tree.op] == (+)) &&
        top_level_constant
        op = tree.op
        # Put the constant in r. Need to assume var in left for simplification assumption.
        if tree.l.constant
            tmp = tree.r
            tree.r = tree.l
            tree.l = tmp
        end
        topconstant = tree.r.val
        # Simplify down first
        below = tree.l
        if below.degree == 2 && below.op == op
            if below.l.constant
                tree = below
                tree.l.val = options.binops[op](tree.l.val, topconstant)
            elseif below.r.constant
                tree = below
                tree.r.val = options.binops[op](tree.r.val, topconstant)
            end
        end
    end

    if tree.degree == 2 && options.binops[tree.op] == (-) && top_level_constant
        # Currently just simplifies subtraction. (can't assume both plus and sub are operators)
        # Not commutative, so use different op.
        if tree.l.constant
            if tree.r.degree == 2 && options.binops[tree.r.op] == (-)
                if tree.r.l.constant
                    #(const - (const - var)) => (var - const)
                    l = tree.l
                    r = tree.r
                    simplified_const = -(l.val - r.l.val) #neg(sub(l.val, r.l.val))
                    tree.l = tree.r.r
                    tree.r = l
                    tree.r.val = simplified_const
                elseif tree.r.r.constant
                    #(const - (var - const)) => (const - var)
                    l = tree.l
                    r = tree.r
                    simplified_const = l.val + r.r.val #plus(l.val, r.r.val)
                    tree.r = tree.r.l
                    tree.l.val = simplified_const
                end
            end
        else #tree.r.constant is true
            if tree.l.degree == 2 && options.binops[tree.l.op] == (-)
                if tree.l.l.constant
                    #((const - var) - const) => (const - var)
                    l = tree.l
                    r = tree.r
                    simplified_const = l.l.val - r.val#sub(l.l.val, r.val)
                    tree.r = tree.l.r
                    tree.l = r
                    tree.l.val = simplified_const
                elseif tree.l.r.constant
                    #((var - const) - const) => (var - const)
                    l = tree.l
                    r = tree.r
                    simplified_const = r.val + l.r.val #plus(r.val, l.r.val)
                    tree.l = tree.l.l
                    tree.r.val = simplified_const
                end
            end
        end
    end
    return tree
end

# Simplify tree
function simplify_tree(tree::Node, options::Options)::Node
    if tree.degree == 1
        tree.l = simplify_tree(tree.l, options)
        l = tree.l.val
        if tree.l.degree == 0 && tree.l.constant && isgood(l)
            out = options.unaops[tree.op](l)
            if isbad(out)
                return tree
            end
            return Node(convert(CONST_TYPE, out))
        end
    elseif tree.degree == 2
        tree.l = simplify_tree(tree.l, options)
        tree.r = simplify_tree(tree.r, options)
        constantsBelow = (
            tree.l.degree == 0 && tree.l.constant && tree.r.degree == 0 && tree.r.constant
        )
        if constantsBelow
            # NaN checks:
            l = tree.l.val
            r = tree.r.val
            if isbad(l) || isbad(r)
                return tree
            end

            # Actually compute:
            out = options.binops[tree.op](l, r)
            if isbad(out)
                return tree
            end
            return Node(convert(CONST_TYPE, out))
        end
    end
    return tree
end

end


text:
Base.map(k::Kernel, a::AbstractArray...) =
    map!(k, similar(first(a), eltype(k, a...), size(k, first(a))), a...)

@inline function _map_checkargs(k::Kernel, b::AbstractArray, a::AbstractArray...)
    allequal(axes.(Ref(k), a)) ||
        throw(DimensionMismatch("trimmed input axes don't agree: $(join(axes.(Ref(k), a), " vs "))"))

    size(b) == size(k, first(a)) ||
        throw(DimensionMismatch("output size doesn't match: $(size(b)) vs $(join(size.(Ref(k), a), " vs "))"))
end

function Base.map!(k::Kernel, b::AbstractArray, a::AbstractArray...)
    _map_checkargs(k, b, a...)
    # these offsets may constant propagate to 0
    offset = CartesianIndex(first.(axes(b))) - CartesianIndex(first.(axes(k, first(a))))

    @inline f(w...) = @inbounds b[first(w).position + offset] = k(w...)
    windowloop(f, k, nothing, (_,_)->nothing, a...)

    return b
end

function Base.mapreduce(k::Kernel, op, a::AbstractArray...;
        dims=:, init=Base.reduce_empty(op, eltype(k, a...)))
    dims == Colon() ||
        throw(ArgumentError("dimension-wise reduction currently unsupported"))

    return mapfoldl(k, op, a...; init=init)
end

Base.mapfoldl(k::Kernel, op, a::AbstractArray...;
        init=Base.reduce_empty(op, eltype(k, a...))) = windowloop(k.f, k, init, op, a...)


text:
x = LinRange(0,2π,50)
plt1= plot(x, sin.(x), st = :scatter, label = "sin(x)",
    m = (3, :black, stroke(0)), leg =:bottomleft,
    fg_legend = :black, bg_legend = nothing)
plt2= plot(x, sin.(x), c = :black, m = (3, :d, :black, stroke(0)),
    label = ["sin(x)"], leg =:bottomleft, fg_legend = :black,
    bg_legend = nothing)
plt3= plot(x, [sin.(x), cos.(x)], c = :black, leg =:topright,
    m = (3, [:d :o], [:black :orangered], stroke(0)),
    label = ["sin(x)", "cos(x)"], fg_legend = nothing,
    bg_legend = :white, xlab =L"x")
plt4= plot(x, [sin.(x), cos.(x), -sin.(x), -cos.(x)], lw = 1.5,
    c = [:viridis :plasma :magma :inferno], linez = x,
    colorbar = false, legend =:false, xlab =L"x")
plot(plt1, plt2, plt3, plt4, layout = (2,2), legendfont=(8,))
savefig("figScatter.pdf")

max_stars_repo_name: lazarusA/helpfulJulia

max_issues_repo_name: lazarusA/helpfulJulia

max_forks_repo_name: lazarusA/helpfulJulia


text:
# Create confusion matrix for any number of classes
function confusion_matrix(y_cond::Vector{Int}, y_pred::Vector{Int})

    # Generate empty confusion matrix
    classes = sort(unique([y_cond; y_pred]))
    conf_matrix = zeros(Int64, length(classes), length(classes))

    # Add counts
    for i in 1:length(y_cond)
        # translate label to index
        cond_class_index = findfirst(classes, y_cond[i])
        pred_class_index = findfirst(classes, y_pred[i])
        # predicted class is the row, condition class is the column
        conf_matrix[pred_class_index, cond_class_index] += 1
  end

  return conf_matrix
end

# plot confusion matrix
function plot_confusion_matrix(y_cond::Vector{Int},
                               y_pred::Vector{Int},
                               ylabel::String = "Var1",
                               xlabel::String = "Var2",
                               classes::Vector{String} = string.(sort(unique([y_cond; y_pred]))))
    # Number of classes
    num = length(classes)

    # Create DataFrame with data from confusion matrix
    axes = vcat([[classes[i] classes[j]] for i in 1:num, j in 1:num]...)
    df = DataFrame([axes confusion_matrix(y_cond, y_pred)[:]])

    # Colormap
    cmap = vcat(RGB(1,1,1), sequential_palette(255, 99, c=0.88, s=0.6, b=0.75, w=0.3, d=0.25,
                            wcolor=RGB(1,1,1), dcolor=RGB(0,0,1), logscale=false))

    # Plot
    plot(df, x="x2", y="x1", color="x3", Geom.rectbin,
         Coord.cartesian(yflip=true, xflip=false, fixed=true),
         Guide.YLabel(ylabel), Guide.XLabel(xlabel), Guide.colorkey("Count"),
         Scale.color_continuous(colormap = p->cmap[round(Int, p*99+1)], minvalue=0))
end

# Print accuracy stats
# Optional to print short, medium or long version
function print_binary_accuracy(y_cond::Vector{Int}, y_pred::Vector{Int}; size="short")

    # Check only 2 classes
    length(unique([y_cond; y_pred])) > 2 && throw("function is only for 2 classes")

    # Create confusion matrix
    CM = confusion_matrix(y_cond, y_pred)

    # Calculate metrics

    # 1st level metrics
    Population = sum(CM)          # Total number in population

    TP = CM[1, 1]                 # "True Positive" / "Hit"
    TN = CM[2, 2]                 # "True Negative" / "Correct Reject"
    FP = CM[1, 2]                 # "False Positive" / "False Alarm" / Type I Error
    FN = CM[2, 1]                 # "False Negative" / "Miss" / Type II Error

    CondPos = TP + FN             # Sum of Condition = Positive
    CondNeg = FP + TN             # Sum of Condition = Negative
    PredPos = TP + FP             # Sum of Prediction = Positive
    PredNeg = FN + TN             # Sum of Prediction = Negative

    # 2nd level metrics

    TPR = TP / CondPos            # True Positive Rate / Sensitivity / Hit Rate / Recall
    TNR = TN / CondNeg            # True Negative Rate / Specificity
    PPV = TP / PredPos            # Positive Predictive Value / Precision
    NPV = TN / PredNeg            # Negative Predictive Value
    FPR = FP / CondNeg            # False Positive Rate / Fall-out
    FDR = FP / PredNeg            # False Discovery Rate
    FNR = FN / CondNeg            # False Negative Rate
    FOR = FN / PredNeg            # False Omission Rate

    # 3rd level metrics

    Accuracy = (TP + TN) / Population                  # Accuracy Rate
    PosLR = TPR / FPR                                  # Positive Likelihood Ratio
    NegLR = FNR / TNR                                  # Negative Likelihood Ratio
    DiagOR = PosLR / NegLR                             # Diagnostic Odds Ratio

    # F Scores i.e. F_β = ((1 + β^2) * PPV * TPR)/ (β^2 * PPV + TPR)
    F_1 = (2 * PPV * TPR) / (PPV + TPR)                # F1 Score / Harmonic Mean of Precision and Recall
    F_2 = (5 * PPV * TPR) / (4 * PPV + TPR)            # F2 Score - weights recall higher than precision
    F_05 = (1.25 * PPV * TPR) / (0.25 * PPV + TPR)     # F0.5 Score - weights precision higher than recall

    # Matthews's Correlation Coefficient
    # Guideline:
    # +1 = perfect prediction, 0 = no better than random, -1 = total disagreement
    MCC = (TP*TN - FP*FN) / sqrt((TP+FP)*(TP+FN)*(TN+FP)*(TN+FN))

    # Kappa Coefficient - compares Observed Accuracy with Expected Accuracy (random chance)
    # Guidelines:
    # L&K: <0 = no agreement, 0-0.20 = slight, 0.21-0.40 = fair, 0.41-0.60 = moderate, 0.61-0.80 = substantial, 0.81-1 = almost perfect
    # Fleiss: <0.4 = poor, 0.40-0.75 = fair to good, >0.75 = excellent
    ObsAcc = (TP + TN) / Population                                    # Observed Accuracy
    ExpAcc = (CondPos * PredPos + CondNeg * PredNeg) / Population^2    # Expected Accuracy
    Kappa = (ObsAcc - ExpAcc) / (1 - ExpAcc)                           # Kappa

    # Display metrics
    if size == "short"
        @printf "Accuracy:    %f\n" Accuracy
        @printf "F_1:         %f\n" F_1
    elseif size == "medium"
        @printf "Accuracy:    %f\n" Accuracy
        @printf "F_1:         %f\n" F_1
        @printf "F_2:         %f\n" F_2
        @printf "F_05:        %f\n" F_05
        @printf "MCC:         %f\n" MCC
        @printf "Kappa:       %f\n" Kappa
    elseif size == "long"
        @printf "Accuracy:    %f\n" Accuracy
        @printf "F_1:         %f\n" F_1
        @printf "F_2:         %f\n" F_2
        @printf "F_05:        %f\n" F_05
        @printf "MCC:         %f\n" MCC
        @printf "Kappa:       %f\n" Kappa
        @printf "Precision:   %f\n" PPV
        @printf "Recall:      %f\n" TPR
        @printf "Specificity: %f\n" TNR
    end
end

# ROC Curve


text:
function test_fitness(fitness::Function, cont_f::Function;
                      maxfit::Float64=1.0, minfit::Float64=0.0)
    fit = fitness(cont_f; seed=0)
    @test fit <= maxfit
    @test fit >= minfit
    fit2, t, bytes, gctime, memallocs = @timed fitness(cont_f; seed=1234)
    println("Fitness of $fit2 in $t s, $bytes bytes")
    @test fit2 <= maxfit
    @test fit2 >= minfit
end

rand_cont(x::Array{Float64}) = rand(1:4)

@testset "Coverage fitness" begin
    test_fitness(RoboGrid.coverage_fitness, rand_cont)
end

@testset "Water search fitness" begin
    test_fitness(RoboGrid.water_search_fitness, rand_cont)
end

@testset "Water memorize fitness" begin
    test_fitness(RoboGrid.water_memorize_fitness, rand_cont; minfit=-7.0)
end

@testset "Cross search fitness" begin
    test_fitness(RoboGrid.cross_search_fitness, rand_cont)
end

@testset "Cross memorize fitness" begin
    test_fitness(RoboGrid.cross_memorize_fitness, rand_cont; minfit=-7.0)
end

@testset "Cross strategy fitness" begin
    test_fitness(RoboGrid.cross_strategy_fitness, rand_cont; minfit=-7.0)
end


text:
	#Pkg.add("Dates")
 	#using Dates

    centuries = ("I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X", "XI", "XII", "XIII", "XIV", "XV", "XVI","XVII", "XVIII", "XIX", "XX", "XXI")

    timeszon = (Dict("timezones"=> ["Europe/Andorra"], "code"=> "AD", "continent"=> "Europe", "name"=> "Andorra", "capital"=> "Andorra la Vella"),Dict("timezones"=> ["Asia/Kabul"], "code"=> "AF", "continent"=> "Asia", "name"=> "Afghanistan", "capital"=> "Kabul"),Dict("timezones"=> ["America/Antigua"], "code"=> "AG", "continent"=> "North America", "name"=> "Antigua and Barbuda", "capital"=> "St. John's"),Dict("timezones"=> ["Europe/Tirane"], "code"=> "AL", "continent"=> "Europe", "name"=> "Albania", "capital"=> "Tirana"),Dict("timezones"=> ["Asia/Yerevan"], "code"=> "AM", "continent"=> "Asia", "name"=> "Armenia", "capital"=> "Yerevan"),Dict("timezones"=> ["Africa/Luanda"], "code"=> "AO", "continent"=> "Africa", "name"=> "Angola", "capital"=> "Luanda"),Dict("timezones"=> ["America/Argentina/Buenos_Aires", "America/Argentina/Cordoba", "America/Argentina/Jujuy", "America/Argentina/Tucuman", "America/Argentina/Catamarca", "America/Argentina/La_Rioja", "America/Argentina/San_Juan", "America/Argentina/Mendoza", "America/Argentina/Rio_Gallegos", "America/Argentina/Ushuaia"], "code"=> "AR", "continent"=> "South America", "name"=> "Argentina", "capital"=> "Buenos Aires"),Dict("timezones"=> ["Europe/Vienna"], "code"=> "AT", "continent"=> "Europe", "name"=> "Austria", "capital"=> "Vienna"),Dict("timezones"=> ["Australia/Lord_Howe", "Australia/Hobart", "Australia/Currie", "Australia/Melbourne", "Australia/Sydney", "Australia/Broken_Hill", "Australia/Brisbane", "Australia/Lindeman", "Australia/Adelaide", "Australia/Darwin", "Australia/Perth"], "code"=> "AU", "continent"=> "Oceania", "name"=> "Australia", "capital"=> "Canberra"),Dict("timezones"=> ["Asia/Baku"], "code"=> "AZ", "continent"=> "Asia", "name"=> "Azerbaijan", "capital"=> "Baku"),Dict("timezones"=> ["America/Barbados"], "code"=> "BB", "continent"=> "North America", "name"=> "Barbados", "capital"=> "Bridgetown"),Dict("timezones"=> ["Asia/Dhaka"], "code"=> "BD", "continent"=> "Asia", "name"=> "Bangladesh", "capital"=> "Dhaka"),Dict("timezones"=> ["Europe/Brussels"], "code"=> "BE", "continent"=> "Europe", "name"=> "Belgium", "capital"=> "Brussels"),Dict("timezones"=> ["Africa/Ouagadougou"], "code"=> "BF", "continent"=> "Africa", "name"=> "Burkina Faso", "capital"=> "Ouagadougou"),Dict("timezones"=> ["Europe/Sofia"], "code"=> "BG", "continent"=> "Europe", "name"=> "Bulgaria", "capital"=> "Sofia"),Dict("timezones"=> ["Asia/Bahrain"], "code"=> "BH", "continent"=> "Asia", "name"=> "Bahrain", "capital"=> "Manama"),Dict("timezones"=> ["Africa/Bujumbura"], "code"=> "BI", "continent"=> "Africa", "name"=> "Burundi", "capital"=> "Bujumbura"),Dict("timezones"=> ["Africa/Porto-Novo"], "code"=> "BJ", "continent"=> "Africa", "name"=> "Benin", "capital"=> "Porto-Novo"),Dict("timezones"=> ["Asia/Brunei"], "code"=> "BN", "continent"=> "Asia", "name"=> "Brunei Darussalam", "capital"=> "Bandar Seri Begawan"),Dict("timezones"=> ["America/La_Paz"], "code"=> "BO", "continent"=> "South America", "name"=> "Bolivia", "capital"=> "Sucre"),Dict("timezones"=> ["America/Noronha", "America/Belem", "America/Fortaleza", "America/Recife", "America/Araguaina", "America/Maceio", "America/Bahia", "America/Sao_Paulo", "America/Campo_Grande", "America/Cuiaba", "America/Porto_Velho", "America/Boa_Vista", "America/Manaus", "America/Eirunepe", "America/Rio_Branco"], "code"=> "BR", "continent"=> "South America", "name"=> "Brazil", "capital"=> "Brasília"),Dict("timezones"=> ["America/Nassau"], "code"=> "BS", "continent"=> "North America", "name"=> "Bahamas", "capital"=> "Nassau"),Dict("timezones"=> ["Asia/Thimphu"], "code"=> "BT", "continent"=> "Asia", "name"=> "Bhutan", "capital"=> "Thimphu"),Dict("timezones"=> ["Africa/Gaborone"], "code"=> "BW", "continent"=> "Africa", "name"=> "Botswana", "capital"=> "Gaborone"),Dict("timezones"=> ["Europe/Minsk"], "code"=> "BY", "continent"=> "Europe", "name"=> "Belarus", "capital"=> "Minsk"),Dict("timezones"=> ["America/Belize"], "code"=> "BZ", "continent"=> "North America", "name"=> "Belize", "capital"=> "Belmopan"),Dict("timezones"=> ["America/St_Johns", "America/Halifax", "America/Glace_Bay", "America/Moncton", "America/Goose_Bay", "America/Blanc-Sablon", "America/Montreal", "America/Toronto", "America/Nipigon", "America/Thunder_Bay", "America/Pangnirtung", "America/Iqaluit", "America/Atikokan", "America/Rankin_Inlet", "America/Winnipeg", "America/Rainy_River", "America/Cambridge_Bay", "America/Regina", "America/Swift_Current", "America/Edmonton", "America/Yellowknife", "America/Inuvik", "America/Dawson_Creek", "America/Vancouver", "America/Whitehorse", "America/Dawson"], "code"=> "CA", "continent"=> "North America", "name"=> "Canada", "capital"=> "Ottawa"),Dict("timezones"=> ["Africa/Kinshasa", "Africa/Lubumbashi"], "code"=> "CD", "continent"=> "Africa", "name"=> "Democratic Republic of the Congo", "capital"=> "Kinshasa"),Dict("timezones"=> ["Africa/Brazzaville"], "code"=> "CG", "continent"=> "Africa", "name"=> "Republic of the Congo", "capital"=> "Brazzaville"),Dict("timezones"=> ["Africa/Abidjan"], "code"=> "CI", "continent"=> "Africa", "name"=> "Cöte d´Ivoire", "capital"=> "Yamoussoukro"),Dict("timezones"=> ["America/Santiago", "Pacific/Easter"], "code"=> "CL", "continent"=> "South America", "name"=> "Chile", "capital"=> "Santiago"),Dict("timezones"=> ["Africa/Douala"], "code"=> "CM", "continent"=> "Africa", "name"=> "Cameroon", "capital"=> "Yaound\xc3\xa9"),Dict("timezones"=> ["Asia/Shanghai", "Asia/Harbin", "Asia/Chongqing", "Asia/Urumqi", "Asia/Kashgar"], "code"=> "CN", "continent"=> "Asia", "name"=> "People´s Republic of China", "capital"=> "Beijing"),Dict("timezones"=> ["America/Bogota"], "code"=> "CO", "continent"=> "South America", "name"=> "Colombia", "capital"=> "Bogot\xc3\xa1"),Dict("timezones"=> ["America/Costa_Rica"], "code"=> "CR", "continent"=> "North America", "name"=> "Costa Rica", "capital"=> "San Jos\xc3\xa9"),Dict("timezones"=> ["America/Havana"], "code"=> "CU", "continent"=> "North America", "name"=> "Cuba", "capital"=> "Havana"),Dict("timezones"=> ["Atlantic/Cape_Verde"], "code"=> "CV", "continent"=> "Africa", "name"=> "Cape Verde", "capital"=> "Praia"),Dict("timezones"=> ["Asia/Nicosia"], "code"=> "CY", "continent"=> "Asia", "name"=> "Cyprus", "capital"=> "Nicosia"),Dict("timezones"=> ["Europe/Prague"], "code"=> "CZ", "continent"=> "Europe", "name"=> "Czech Republic", "capital"=> "Prague"),Dict("timezones"=> ["Europe/Berlin"], "code"=> "DE", "continent"=> "Europe", "name"=> "Germany", "capital"=> "Berlin"),Dict("timezones"=> ["Africa/Djibouti"], "code"=> "DJ", "continent"=> "Africa", "name"=> "Djibouti", "capital"=> "Djibouti City"),Dict("timezones"=> ["Europe/Copenhagen"], "code"=> "DK", "continent"=> "Europe", "name"=> "Denmark", "capital"=> "Copenhagen"),Dict("timezones"=> ["America/Dominica"], "code"=> "DM", "continent"=> "North America", "name"=> "Dominica", "capital"=> "Roseau"),Dict("timezones"=> ["America/Santo_Domingo"], "code"=> "DO", "continent"=> "North America", "name"=> "Dominican Republic", "capital"=> "Santo Domingo"),Dict("timezones"=> ["America/Guayaquil", "Pacific/Galapagos"], "code"=> "EC", "continent"=> "South America", "name"=> "Ecuador", "capital"=> "Quito"),Dict("timezones"=> ["Europe/Tallinn"], "code"=> "EE", "continent"=> "Europe", "name"=> "Estonia", "capital"=> "Tallinn"),Dict("timezones"=> ["Africa/Cairo"], "code"=> "EG", "continent"=> "Africa", "name"=> "Egypt", "capital"=> "Cairo"),Dict("timezones"=> ["Africa/Asmera"], "code"=> "ER", "continent"=> "Africa", "name"=> "Eritrea", "capital"=> "Asmara"),Dict("timezones"=> ["Africa/Addis_Ababa"], "code"=> "ET", "continent"=> "Africa", "name"=> "Ethiopia", "capital"=> "Addis Ababa"),Dict("timezones"=> ["Europe/Helsinki"], "code"=> "FI", "continent"=> "Europe", "name"=> "Finland", "capital"=> "Helsinki"),Dict("timezones"=> ["Pacific/Fiji"], "code"=> "FJ", "continent"=> "Oceania", "name"=> "Fiji", "capital"=> "Suva"),Dict("timezones"=> ["Europe/Paris"], "code"=> "FR", "continent"=> "Europe", "name"=> "France", "capital"=> "Paris"),Dict("timezones"=> ["Africa/Libreville"], "code"=> "GA", "continent"=> "Africa", "name"=> "Gabon", "capital"=> "Libreville"),Dict("timezones"=> ["Asia/Tbilisi"], "code"=> "GE", "continent"=> "Asia", "name"=> "Georgia", "capital"=> "Tbilisi"),Dict("timezones"=> ["Africa/Accra"], "code"=> "GH", "continent"=> "Africa", "name"=> "Ghana", "capital"=> "Accra"),Dict("timezones"=> ["Africa/Banjul"], "code"=> "GM", "continent"=> "Africa", "name"=> "The Gambia", "capital"=> "Banjul"),Dict("timezones"=> ["Africa/Conakry"], "code"=> "GN", "continent"=> "Africa", "name"=> "Guinea", "capital"=> "Conakry"),Dict("timezones"=> ["Europe/Athens"], "code"=> "GR", "continent"=> "Europe", "name"=> "Greece", "capital"=> "Athens"),Dict("timezones"=> ["America/Guatemala"], "code"=> "GT", "continent"=> "North America", "name"=> "Guatemala", "capital"=> "Guatemala City"),Dict("timezones"=> ["America/Guatemala"], "code"=> "GT", "continent"=> "North America", "name"=> "Haiti", "capital"=> "Port-au-Prince"),Dict("timezones"=> ["Africa/Bissau"], "code"=> "GW", "continent"=> "Africa", "name"=> "Guinea-Bissau", "capital"=> "Bissau"),Dict("timezones"=> ["America/Guyana"], "code"=> "GY", "continent"=> "South America", "name"=> "Guyana", "capital"=> "Georgetown"),Dict("timezones"=> ["America/Tegucigalpa"], "code"=> "HN", "continent"=> "North America", "name"=> "Honduras", "capital"=> "Tegucigalpa"),Dict("timezones"=> ["Europe/Budapest"], "code"=> "HU", "continent"=> "Europe", "name"=> "Hungary", "capital"=> "Budapest"),Dict("timezones"=> ["Asia/Jakarta", "Asia/Pontianak", "Asia/Makassar", "Asia/Jayapura"], "code"=> "ID", "continent"=> "Asia", "name"=> "Indonesia", "capital"=> "Jakarta"),Dict("timezones"=> ["Europe/Dublin"], "code"=> "IE", "continent"=> "Europe", "name"=> "Republic of Ireland", "capital"=> "Dublin"),Dict("timezones"=> ["Asia/Jerusalem"], "code"=> "IL", "continent"=> "Asia", "name"=> "Israel", "capital"=> "Jerusalem"),Dict("timezones"=> ["Asia/Calcutta"], "code"=> "IN", "continent"=> "Asia", "name"=> "India", "capital"=> "New Delhi"),Dict("timezones"=> ["Asia/Baghdad"], "code"=> "IQ", "continent"=> "Asia", "name"=> "Iraq", "capital"=> "Baghdad"),Dict("timezones"=> ["Asia/Tehran"], "code"=> "IR", "continent"=> "Asia", "name"=> "Iran", "capital"=> "Tehran"),Dict("timezones"=> ["Atlantic/Reykjavik"], "code"=> "IS", "continent"=> "Europe", "name"=> "Iceland", "capital"=> "Reykjav\xc3\xadk"),Dict("timezones"=> ["Europe/Rome"], "code"=> "IT", "continent"=> "Europe", "name"=> "Italy", "capital"=> "Rome"),Dict("timezones"=> ["America/Jamaica"], "code"=> "JM", "continent"=> "North America", "name"=> "Jamaica", "capital"=> "Kingston"),Dict("timezones"=> ["Asia/Amman"], "code"=> "JO", "continent"=> "Asia", "name"=> "Jordan", "capital"=> "Amman"),Dict("timezones"=> ["Asia/Tokyo"], "code"=> "JP", "continent"=> "Asia", "name"=> "Japan", "capital"=> "Tokyo"),Dict("timezones"=> ["Africa/Nairobi"], "code"=> "KE", "continent"=> "Africa", "name"=> "Kenya", "capital"=> "Nairobi"),Dict("timezones"=> ["Asia/Bishkek"], "code"=> "KG", "continent"=> "Asia", "name"=> "Kyrgyzstan", "capital"=> "Bishkek"),Dict("timezones"=> ["Pacific/Tarawa", "Pacific/Enderbury", "Pacific/Kiritimati"], "code"=> "KI", "continent"=> "Oceania", "name"=> "Kiribati", "capital"=> "Tarawa"),Dict("timezones"=> ["Asia/Pyongyang"], "code"=> "KP", "continent"=> "Asia", "name"=> "North Korea", "capital"=> "Pyongyang"),Dict("timezones"=> ["Asia/Seoul"], "code"=> "KR", "continent"=> "Asia", "name"=> "South Korea", "capital"=> "Seoul"),Dict("timezones"=> ["Asia/Kuwait"], "code"=> "KW", "continent"=> "Asia", "name"=> "Kuwait", "capital"=> "Kuwait City"),Dict("timezones"=> ["Asia/Beirut"], "code"=> "LB", "continent"=> "Asia", "name"=> "Lebanon", "capital"=> "Beirut"),Dict("timezones"=> ["Europe/Vaduz"], "code"=> "LI", "continent"=> "Europe", "name"=> "Liechtenstein", "capital"=> "Vaduz"),Dict("timezones"=> ["Africa/Monrovia"], "code"=> "LR", "continent"=> "Africa", "name"=> "Liberia", "capital"=> "Monrovia"),Dict("timezones"=> ["Africa/Maseru"], "code"=> "LS", "continent"=> "Africa", "name"=> "Lesotho", "capital"=> "Maseru"),Dict("timezones"=> ["Europe/Vilnius"], "code"=> "LT", "continent"=> "Europe", "name"=> "Lithuania", "capital"=> "Vilnius"),Dict("timezones"=> ["Europe/Luxembourg"], "code"=> "LU", "continent"=> "Europe", "name"=> "Luxembourg", "capital"=> "Luxembourg City"),Dict("timezones"=> ["Europe/Riga"], "code"=> "LV", "continent"=> "Europe", "name"=> "Latvia", "capital"=> "Riga"),Dict("timezones"=> ["Africa/Tripoli"], "code"=> "LY", "continent"=> "Africa", "name"=> "Libya", "capital"=> "Tripoli"),Dict("timezones"=> ["Indian/Antananarivo"], "code"=> "MG", "continent"=> "Africa", "name"=> "Madagascar", "capital"=> "Antananarivo"),Dict("timezones"=> ["Pacific/Majuro", "Pacific/Kwajalein"], "code"=> "MH", "continent"=> "Oceania", "name"=> "Marshall Islands", "capital"=> "Majuro"),Dict("timezones"=> ["Europe/Skopje"], "code"=> "MK", "continent"=> "Europe", "name"=> "Macedonia", "capital"=> "Skopje"),Dict("timezones"=> ["Africa/Bamako"], "code"=> "ML", "continent"=> "Africa", "name"=> "Mali", "capital"=> "Bamako"),Dict("timezones"=> ["Asia/Rangoon"], "code"=> "MM", "continent"=> "Asia", "name"=> "Myanmar", "capital"=> "Naypyidaw"),Dict("timezones"=> ["Asia/Ulaanbaatar", "Asia/Hovd", "Asia/Choibalsan"], "code"=> "MN", "continent"=> "Asia", "name"=> "Mongolia", "capital"=> "Ulaanbaatar"),Dict("timezones"=> ["Africa/Nouakchott"], "code"=> "MR", "continent"=> "Africa", "name"=> "Mauritania", "capital"=> "Nouakchott"),Dict("timezones"=> ["Europe/Malta"], "code"=> "MT", "continent"=> "Europe", "name"=> "Malta", "capital"=> "Valletta"),Dict("timezones"=> ["Indian/Mauritius"], "code"=> "MU", "continent"=> "Africa", "name"=> "Mauritius", "capital"=> "Port Louis"),Dict("timezones"=> ["Indian/Maldives"], "code"=> "MV", "continent"=> "Asia", "name"=> "Maldives", "capital"=> "Mal\xc3\xa9"),Dict("timezones"=> ["Africa/Blantyre"], "code"=> "MW", "continent"=> "Africa", "name"=> "Malawi", "capital"=> "Lilongwe"),Dict("timezones"=> ["America/Mexico_City", "America/Cancun", "America/Merida", "America/Monterrey", "America/Mazatlan", "America/Chihuahua", "America/Hermosillo", "America/Tijuana"], "code"=> "MX", "continent"=> "North America", "name"=> "Mexico", "capital"=> "Mexico City"),Dict("timezones"=> ["Asia/Kuala_Lumpur", "Asia/Kuching"], "code"=> "MY", "continent"=> "Asia", "name"=> "Malaysia", "capital"=> "Kuala Lumpur"),Dict("timezones"=> ["Africa/Maputo"], "code"=> "MZ", "continent"=> "Africa", "name"=> "Mozambique", "capital"=> "Maputo"),Dict("timezones"=> ["Africa/Windhoek"], "code"=> "NA", "continent"=> "Africa", "name"=> "Namibia", "capital"=> "Windhoek"),Dict("timezones"=> ["Africa/Niamey"], "code"=> "NE", "continent"=> "Africa", "name"=> "Niger", "capital"=> "Niamey"),Dict("timezones"=> ["Africa/Lagos"], "code"=> "NG", "continent"=> "Africa", "name"=> "Nigeria", "capital"=> "Abuja"),Dict("timezones"=> ["America/Managua"], "code"=> "NI", "continent"=> "North America", "name"=> "Nicaragua", "capital"=> "Managua"),Dict("timezones"=> ["Europe/Amsterdam"], "code"=> "NL", "continent"=> "Europe", "name"=> "Kingdom of the Netherlands", "capital"=> "Amsterdam"),Dict("timezones"=> ["Europe/Oslo"], "code"=> "NO", "continent"=> "Europe", "name"=> "Norway", "capital"=> "Oslo"),Dict("timezones"=> ["Asia/Katmandu"], "code"=> "NP", "continent"=> "Asia", "name"=> "Nepal", "capital"=> "Kathmandu"),Dict("timezones"=> ["Pacific/Nauru"], "code"=> "NR", "continent"=> "Oceania", "name"=> "Nauru", "capital"=> "Yaren"),Dict("timezones"=> ["Pacific/Auckland", "Pacific/Chatham"], "code"=> "NZ", "continent"=> "Oceania", "name"=> "New Zealand", "capital"=> "Wellington"),Dict("timezones"=> ["Asia/Muscat"], "code"=> "OM", "continent"=> "Asia", "name"=> "Oman", "capital"=> "Muscat"),Dict("timezones"=> ["America/Panama"], "code"=> "PA", "continent"=> "North America", "name"=> "Panama", "capital"=> "Panama City"),Dict("timezones"=> ["America/Lima"], "code"=> "PE", "continent"=> "South America", "name"=> "Peru", "capital"=> "Lima"),Dict("timezones"=> ["Pacific/Port_Moresby"], "code"=> "PG", "continent"=> "Oceania", "name"=> "Papua New Guinea", "capital"=> "Port Moresby"),Dict("timezones"=> ["Asia/Manila"], "code"=> "PH", "continent"=> "Asia", "name"=> "Philippines", "capital"=> "Manila"),Dict("timezones"=> ["Asia/Karachi"], "code"=> "PK", "continent"=> "Asia", "name"=> "Pakistan", "capital"=> "Islamabad"),Dict("timezones"=> ["Europe/Warsaw"], "code"=> "PL", "continent"=> "Europe", "name"=> "Poland", "capital"=> "Warsaw"),Dict("timezones"=> ["Europe/Lisbon", "Atlantic/Madeira", "Atlantic/Azores"], "code"=> "PT", "continent"=> "Europe", "name"=> "Portugal", "capital"=> "Lisbon"),Dict("timezones"=> ["Pacific/Palau"], "code"=> "PW", "continent"=> "Oceania", "name"=> "Palau", "capital"=> "Ngerulmud"),Dict("timezones"=> ["America/Asuncion"], "code"=> "PY", "continent"=> "South America", "name"=> "Paraguay", "capital"=> "Asunci\xc3\xb3n"),Dict("timezones"=> ["Asia/Qatar"], "code"=> "QA", "continent"=> "Asia", "name"=> "Qatar", "capital"=> "Doha"),Dict("timezones"=> ["Europe/Bucharest"], "code"=> "RO", "continent"=> "Europe", "name"=> "Romania", "capital"=> "Bucharest"),Dict("timezones"=> ["Europe/Kaliningrad", "Europe/Moscow", "Europe/Volgograd", "Europe/Samara", "Asia/Yekaterinburg", "Asia/Omsk", "Asia/Novosibirsk", "Asia/Krasnoyarsk", "Asia/Irkutsk", "Asia/Yakutsk", "Asia/Vladivostok", "Asia/Sakhalin", "Asia/Magadan", "Asia/Kamchatka", "Asia/Anadyr"], "code"=> "RU", "continent"=> "Europe", "name"=> "Russia", "capital"=> "Moscow"),Dict("timezones"=> ["Africa/Kigali"], "code"=> "RW", "continent"=> "Africa", "name"=> "Rwanda", "capital"=> "Kigali"),Dict("timezones"=> ["Asia/Riyadh"], "code"=> "SA", "continent"=> "Asia", "name"=> "Saudi Arabia", "capital"=> "Riyadh"),Dict("timezones"=> ["Pacific/Guadalcanal"], "code"=> "SB", "continent"=> "Oceania", "name"=> "Solomon Islands", "capital"=> "Honiara"),Dict("timezones"=> ["Indian/Mahe"], "code"=> "SC", "continent"=> "Africa", "name"=> "Seychelles", "capital"=> "Victoria"),Dict("timezones"=> ["Africa/Khartoum"], "code"=> "SD", "continent"=> "Africa", "name"=> "Sudan", "capital"=> "Khartoum"),Dict("timezones"=> ["Europe/Stockholm"], "code"=> "SE", "continent"=> "Europe", "name"=> "Sweden", "capital"=> "Stockholm"),Dict("timezones"=> ["Asia/Singapore"], "code"=> "SG", "continent"=> "Asia", "name"=> "Singapore", "capital"=> "Singapore"),Dict("timezones"=> ["Europe/Ljubljana"], "code"=> "SI", "continent"=> "Europe", "name"=> "Slovenia", "capital"=> "Ljubljana"),Dict("timezones"=> ["Europe/Bratislava"], "code"=> "SK", "continent"=> "Europe", "name"=> "Slovakia", "capital"=> "Bratislava"),Dict("timezones"=> ["Africa/Freetown"], "code"=> "SL", "continent"=> "Africa", "name"=> "Sierra Leone", "capital"=> "Freetown"),Dict("timezones"=> ["Europe/San_Marino"], "code"=> "SM", "continent"=> "Europe", "name"=> "San Marino", "capital"=> "San Marino"),Dict("timezones"=> ["Africa/Dakar"], "code"=> "SN", "continent"=> "Africa", "name"=> "Senegal", "capital"=> "Dakar"),Dict("timezones"=> ["Africa/Mogadishu"], "code"=> "SO", "continent"=> "Africa", "name"=> "Somalia", "capital"=> "Mogadishu"),Dict("timezones"=> ["America/Paramaribo"], "code"=> "SR", "continent"=> "South America", "name"=> "Suriname", "capital"=> "Paramaribo"),Dict("timezones"=> ["Africa/Sao_Tome"], "code"=> "ST", "continent"=> "Africa", "name"=> "S\xc3\xa3o Tom\xc3\xa9 and Pr\xc3\xadncipe", "capital"=> "S\xc3\xa3o Tom\xc3\xa9"),Dict("timezones"=> ["Asia/Damascus"], "code"=> "SY", "continent"=> "Asia", "name"=> "Syria", "capital"=> "Damascus"),Dict("timezones"=> ["Africa/Lome"], "code"=> "TG", "continent"=> "Africa", "name"=> "Togo", "capital"=> "Lom\xc3\xa9"),Dict("timezones"=> ["Asia/Bangkok"], "code"=> "TH", "continent"=> "Asia", "name"=> "Thailand", "capital"=> "Bangkok"),Dict("timezones"=> ["Asia/Dushanbe"], "code"=> "TJ", "continent"=> "Asia", "name"=> "Tajikistan", "capital"=> "Dushanbe"),Dict("timezones"=> ["Asia/Ashgabat"], "code"=> "TM", "continent"=> "Asia", "name"=> "Turkmenistan", "capital"=> "Ashgabat"),Dict("timezones"=> ["Africa/Tunis"], "code"=> "TN", "continent"=> "Africa", "name"=> "Tunisia", "capital"=> "Tunis"),Dict("timezones"=> ["Pacific/Tongatapu"], "code"=> "TO", "continent"=> "Oceania", "name"=> "Tonga", "capital"=> "Nuku\xca\xbbalofa"),Dict("timezones"=> ["Europe/Istanbul"], "code"=> "TR", "continent"=> "Asia", "name"=> "Turkey", "capital"=> "Ankara"),Dict("timezones"=> ["America/Port_of_Spain"], "code"=> "TT", "continent"=> "North America", "name"=> "Trinidad and Tobago", "capital"=> "Port of Spain"),Dict("timezones"=> ["Pacific/Funafuti"], "code"=> "TV", "continent"=> "Oceania", "name"=> "Tuvalu", "capital"=> "Funafuti"),Dict("timezones"=> ["Africa/Dar_es_Salaam"], "code"=> "TZ", "continent"=> "Africa", "name"=> "Tanzania", "capital"=> "Dodoma"),Dict("timezones"=> ["Europe/Kiev", "Europe/Uzhgorod", "Europe/Zaporozhye", "Europe/Simferopol"], "code"=> "UA", "continent"=> "Europe", "name"=> "Ukraine", "capital"=> "Kiev"),Dict("timezones"=> ["Africa/Kampala"], "code"=> "UG", "continent"=> "Africa", "name"=> "Uganda", "capital"=> "Kampala"),Dict("timezones"=> ["America/New_York", "America/Detroit", "America/Kentucky/Louisville", "America/Kentucky/Monticello", "America/Indiana/Indianapolis", "America/Indiana/Marengo", "America/Indiana/Knox", "America/Indiana/Vevay", "America/Chicago", "America/Indiana/Vincennes", "America/Indiana/Petersburg", "America/Menominee", "America/North_Dakota/Center", "America/North_Dakota/New_Salem", "America/Denver", "America/Boise", "America/Shiprock", "America/Phoenix", "America/Los_Angeles", "America/Anchorage", "America/Juneau", "America/Yakutat", "America/Nome", "America/Adak", "Pacific/Honolulu"], "code"=> "US", "continent"=> "North America", "name"=> "United States", "capital"=> "Washington, D.C."),Dict("timezones"=> ["America/Montevideo"], "code"=> "UY", "continent"=> "South America", "name"=> "Uruguay", "capital"=> "Montevideo"),Dict("timezones"=> ["Asia/Samarkand", "Asia/Tashkent"], "code"=> "UZ", "continent"=> "Asia", "name"=> "Uzbekistan", "capital"=> "Tashkent"),Dict("timezones"=> ["Europe/Vatican"], "code"=> "VA", "continent"=> "Europe", "name"=> "Vatican City", "capital"=> "Vatican City"),Dict("timezones"=> ["America/Caracas"], "code"=> "VE", "continent"=> "South America", "name"=> "Venezuela", "capital"=> "Caracas"),Dict("timezones"=> ["Asia/Saigon"], "code"=> "VN", "continent"=> "Asia", "name"=> "Vietnam", "capital"=> "Hanoi"),Dict("timezones"=> ["Pacific/Efate"], "code"=> "VU", "continent"=> "Oceania", "name"=> "Vanuatu", "capital"=> "Port Vila"),Dict("timezones"=> ["Asia/Aden"], "code"=> "YE", "continent"=> "Asia", "name"=> "Yemen", "capital"=> "Sanaa"),Dict("timezones"=> ["Africa/Lusaka"], "code"=> "ZM", "continent"=> "Africa", "name"=> "Zambia", "capital"=> "Lusaka"),Dict("timezones"=> ["Africa/Harare"], "code"=> "ZW", "continent"=> "Africa", "name"=> "Zimbabwe", "capital"=> "Harare"),Dict("timezones"=> ["Africa/Algiers"], "code"=> "DZ", "continent"=> "Africa", "name"=> "Algeria", "capital"=> "Algiers"),Dict("timezones"=> ["Europe/Sarajevo"], "code"=> "BA", "continent"=> "Europe", "name"=> "Bosnia and Herzegovina", "capital"=> "Sarajevo"),Dict("timezones"=> ["Asia/Phnom_Penh"], "code"=> "KH", "continent"=> "Asia", "name"=> "Cambodia", "capital"=> "Phnom Penh"),Dict("timezones"=> ["Africa/Bangui"], "code"=> "CF", "continent"=> "Africa", "name"=> "Central African Republic", "capital"=> "Bangui"),Dict("timezones"=> ["Africa/Ndjamena"], "code"=> "TD", "continent"=> "Africa", "name"=> "Chad", "capital"=> "N´Djamena"),Dict("timezones"=> ["Indian/Comoro"], "code"=> "KM", "continent"=> "Africa", "name"=> "Comoros", "capital"=> "Moroni"),Dict("timezones"=> ["Europe/Zagreb"], "code"=> "HR", "continent"=> "Europe", "name"=> "Croatia", "capital"=> "Zagreb"),Dict("timezones"=> ["Asia/Dili"], "code"=> "TL", "continent"=> "Asia", "name"=> "East Timor", "capital"=> "Dili"),Dict("timezones"=> ["America/El_Salvador"], "code"=> "SV", "continent"=> "North America", "name"=> "El Salvador", "capital"=> "San Salvador"),Dict("timezones"=> ["Africa/Malabo"], "code"=> "GQ", "continent"=> "Africa", "name"=> "Equatorial Guinea", "capital"=> "Malabo"),Dict("timezones"=> ["America/Grenada"], "code"=> "GD", "continent"=> "North America", "name"=> "Grenada", "capital"=> "St. George´s"),Dict("timezones"=> ["Asia/Almaty", "Asia/Qyzylorda", "Asia/Aqtobe", "Asia/Aqtau", "Asia/Oral"], "code"=> "KZ", "continent"=> "Asia", "name"=> "Kazakhstan", "capital"=> "Astana"),Dict("timezones"=> ["Asia/Vientiane"], "code"=> "LA", "continent"=> "Asia", "name"=> "Laos", "capital"=> "Vientiane"),Dict("timezones"=> ["Pacific/Truk", "Pacific/Ponape", "Pacific/Kosrae"], "code"=> "FM", "continent"=> "Oceania", "name"=> "Federated States of Micronesia", "capital"=> "Palikir"),Dict("timezones"=> ["Europe/Chisinau"], "code"=> "MD", "continent"=> "Europe", "name"=> "Moldova", "capital"=> "Chi\xc5\x9fin\xc4\x83u"),Dict("timezones"=> ["Europe/Monaco"], "code"=> "MC", "continent"=> "Europe", "name"=> "Monaco", "capital"=> "Monaco"),Dict("timezones"=> ["Europe/Podgorica"], "code"=> "ME", "continent"=> "Europe", "name"=> "Montenegro", "capital"=> "Podgorica"),Dict("timezones"=> ["Africa/Casablanca"], "code"=> "MA", "continent"=> "Africa", "name"=> "Morocco", "capital"=> "Rabat"),Dict("timezones"=> ["America/St_Kitts"], "code"=> "KN", "continent"=> "North America", "name"=> "Saint Kitts and Nevis", "capital"=> "Basseterre"),Dict("timezones"=> ["America/St_Lucia"], "code"=> "LC", "continent"=> "North America", "name"=> "Saint Lucia", "capital"=> "Castries"),Dict("timezones"=> ["America/St_Vincent"], "code"=> "VC", "continent"=> "North America", "name"=> "Saint Vincent and the Grenadines", "capital"=> "Kingstown"),Dict("timezones"=> ["Pacific/Apia"], "code"=> "WS", "continent"=> "Oceania", "name"=> "Samoa", "capital"=> "Apia"),Dict("timezones"=> ["Europe/Belgrade"], "code"=> "RS", "continent"=> "Europe", "name"=> "Serbia", "capital"=> "Belgrade"),Dict("timezones"=> ["Africa/Johannesburg"], "code"=> "ZA", "continent"=> "Africa", "name"=> "South Africa", "capital"=> "Pretoria"),Dict("timezones"=> ["Europe/Madrid", "Africa/Ceuta", "Atlantic/Canary"], "code"=> "ES", "continent"=> "Europe", "name"=> "Spain", "capital"=> "Madrid"),Dict("timezones"=> ["Asia/Colombo"], "code"=> "LK", "continent"=> "Asia", "name"=> "Sri Lanka", "capital"=> "Sri Jayewardenepura Kotte"),Dict("timezones"=> ["Africa/Mbabane"], "code"=> "SZ", "continent"=> "Africa", "name"=> "Swaziland", "capital"=> "Mbabane"),Dict("timezones"=> ["Europe/Zurich"], "code"=> "CH", "continent"=> "Europe", "name"=> "Switzerland", "capital"=> "Bern"),Dict("timezones"=> ["Asia/Dubai"], "code"=> "AE", "continent"=> "Asia", "name"=> "United Arab Emirates", "capital"=> "Abu Dhabi"),Dict("timezones"=> ["Europe/London"], "code"=> "GB", "continent"=> "Europe", "name"=> "United Kingdom", "capital"=> "London" ))

  	ap = ("AM","PM")

    unix_time()= rand(0: (Int((DateTime(now())) - (DateTime(1970,1,1)))))

    function date_time()
    fec = DateTime(rand(1970:2020),1,1,rand(01:23),rand(00:59),rand(00:59)) + Dates.Day(rand(01:31)) + Dates.Month(rand(01:12))
    sar=replace("$(fec)","T"," ")
    return sar
	end

    date_time_ad()= replace("$(iso8601())","T"," ")

    iso8601()=
    DateTime(rand(1970:2020),1,1,rand(01:23),rand(00:59),rand(00:59)) + Dates.Day(rand(01:31)) + Dates.Month(rand(01:12))

   function date(pattern="%Y-%m-%d")

    x = (Date(rand(1970:2020),1,1)+Dates.Day(rand(01:31))) + Dates.Month(rand(01:12))

    sal= replace(pattern,"%Y","$(Dates.year(x))")
    sal= replace(sal,"%m","$(Dates.month(x))")

    sal= replace(sal,"%d","$(Dates.day(x))")

	return sal

   end

   function time(pattern="%H:%M:%S")

        x= DateTime(1,1,1,rand(01:23),rand(00:59),rand(00:59))

    	sal= replace(pattern,"%H","$(Dates.hour(x))")
    	sal= replace(sal,"%M","$(Dates.minute(x))")

    	sal= replace(sal,"%S","$(Dates.second(x))")

		return sal
	end

    function date_time_between(start_date="-30y", end_date="now")

        if end_date == "now"
        	end_date = replace(end_date,"now","0y" )
		end

		if start_date == "now"
        	start_date = replace(start_date,"now","0y" )
		end

        start_date = DateTime(now()) + Dates.Year(parse(Int,replace(start_date,"y","")))
        end_date = DateTime(now()) + Dates.Year(parse(Int,replace(end_date,"y","")))

         dr=(start_date : end_date)
        return replace("$(dr[rand(1:(length(dr)))])","T"," ")

    end

    function date_time_this_century(before_now=true, after_now=false)

        r = DateTime(now())

        this_century_start = DateTime((Int(Dates.year(r)) - (Dates.year(r) % 100)), 1, 1)
        next_century_start = DateTime(Dates.year(this_century_start) + 100, 1, 1)

        if before_now && after_now
        	dr=(this_century_start : next_century_start)
      	elseif (before_now==false) && after_now
            dr=(r : next_century_start)
        elseif (after_now==false) && before_now
            dr=(this_century_start : r)
        else
           return  replace("$(r)","T"," ")
        end

        return replace("$(dr[rand(1:(length(dr)))])","T"," ")

    end

    function  date_time_this_decade(before_now=true, after_now=false)

          r = DateTime(now())

        this_decade_start = DateTime((Int(Dates.year(r)) - (Dates.year(r) % 10)), 1, 1)
        next_decade_start = DateTime(Dates.year(this_decade_start) + 10, 1, 1)

        if before_now && after_now
        	dr=(this_decade_start : next_decade_start)
      	elseif (before_now==false) && after_now
            dr=(r : next_decade_start)
        elseif (after_now==false) && before_now
            dr=(this_decade_start : r)
        else
           return  replace("$(r)","T"," ")
        end

        return replace("$(dr[rand(1:(length(dr)))])","T"," ")
    end

   function date_time_this_year( before_now=true, after_now=false)

        r = DateTime(now())

        this_year_start = DateTime(Dates.year(r), 1, 1)
        next_year_start = DateTime(Dates.year(r) + 1, 1, 1)

        if before_now && after_now
        	dr=(this_year_start : next_year_start)
      	elseif (before_now==false) && after_now
            dr=(r : next_year_start)
        elseif (after_now==false) && before_now
            dr=(this_year_start : r)
        else
           return  replace("$(r)","T"," ")
        end

        return replace("$(dr[rand(1:(length(dr)))])","T"," ")
    end

    function date_time_this_month(before_now=true, after_now=false)

        r = DateTime(now())

        this_month_start = DateTime(Dates.year(r), Dates.month(r), 1)
        next_month_start = DateTime(Dates.year(r), (Dates.month(r)+ 1)%12, 1)

        if before_now && after_now
        	dr=(this_month_start : next_month_start)
      	elseif (before_now==false) && after_now
            dr=(r : next_month_start)
        elseif (after_now==false) && before_now
            dr=(this_month_start : r)
        else
           return  replace("$(r)","T"," ")
        end

        return replace("$(dr[rand(1:(length(dr)))])","T"," ")
    end

    am_pm()= ap[rand(1:length(ap))]

    day_of_month()= rand(1:31)

    day_of_week()= Dates.dayname(Date(2015,07,rand(12:18)))

    months()=rand(1:12)

    month_name()= Dates.monthname(Date(2015,rand(1:12),15))

    year()=rand(1920:2020)

    century()= centuries[rand(1:length(centuries))]

    function timezone()

	    resul = timeszon[rand(1:length(timeszon))]["timezones"]
	    resul = resul[rand(1:length(resul))]

	    return resul
	end


text:
#= basic support for sparse matrices, more Magma style than Julia
  a sparse matrix is a collection (Array) of sparse rows (SRow)
  A SRow is two Arrays, one (pos) containing the columns, values
  contains the values.
  A[i,j] = A.rows[i].values[A.rows[i].pos[j]]
  to be formal

  The upper_triangular stuff performs very elementary transformations
  until the matrix becomes dense. At this point, the dense bit is extraced and
  converted to an fmpz_mat which is then hnf'ed.

  Missing:
   full HNF, Howell, modular and not
   better elemination strategy

  TODO: sort out the various upper_triangular implementations.
  One (+one with trafo) is probably enough
=#

import Base.push!, Base.max, Nemo.nbits, Base.Array,
       Base.hcat,
       Base.vcat, Base.max, Base.min

export upper_triangular, vcat!, show, sub, SMat, SRow, random_SMatSLP,
       fmpz_mat, rows, cols, copy, push!, mul, mul!, toNemo, sparse,
       valence_mc, swap_rows!, elementary_divisors,
       rand_row, hcat, hcat!, vcat, vcat!, mod!, mod_sym!

include("Sparse/Matrix.jl")
include("Sparse/Row.jl")
include("Sparse/Module.jl")
include("Sparse/Trafo.jl")
include("Sparse/HNF.jl")
include("Sparse/Solve.jl")
include("Sparse/UpperTriangular.jl")


text:
using EHRAuthentication
using Test

@testset "EHRAuthentication.jl" begin
    include("cerner.jl")
end


text:
projected_positions_ECI2ECEF = [
    [-8.53735973609123e6, -1.2988290225267656e7, 2.1851584427175216e7],
    [7.172861967216288e6, -2.171448849034389e7, 1.3296760809673272e7],
    [2.4019377846893914e7, 1.1645117858204663e7, 214527.98779279838],
    [-5.021601719182211e6, 2.2734837592605237e7, 1.2106460195444101e7],
    [8.067370261443458e6, 1.280420712089501e7, 2.1814190881086327e7]
    ]
@testset "Sat Position ECI2ECEF" begin
    for i in 1:length(satellite_states)
        out = sat_position_ECI_2_ECEF(satellite_states[i])
        @test out ≈ projected_positions_ECI2ECEF[i]
    end

    sv_bad = deepcopy(sv1_struct)
    sv_bad.decoder_state.subframes_decoded = [0,1,1,1,1]

    out = false
    try
        sat_position_ECEF(sv_bad)
    catch e
        if typeof(e) == PositionVelocityTime.BadData
            out = true
        end
    end
    @test out == true
end

projected_positions_ECEF = [
    [-8.537359736091228e6, -1.2988290225267658e7, 2.1851584427175216e7],
    [7.172861967216265e6, -2.1714488490343902e7, 1.3296760809673272e7],
    [2.40193778468939e7, 1.1645117858204681e7, 214527.98779279838],
    [-5.021601719182221e6, 2.2734837592605233e7, 1.2106460195444101e7],
    [8.067370261443453e6, 1.2804207120895013e7, 2.1814190881086327e7]
    ]
@testset "Sat Position ECEF" begin
    for i in 1:length(satellite_states)
        out = sat_position_ECEF(satellite_states[i])
        @test out == projected_positions_ECEF[i]
    end

    sv_bad = deepcopy(sv1_struct)
    sv_bad.decoder_state.subframes_decoded = [0,0,0,0,0]
    out = false
    try
        sat_position_ECEF(sv_bad)
    catch e
        if typeof(e) == PositionVelocityTime.BadData
            out = true
        end
    end
    @test out == true
end


text:
abstract type AbstractRepulsion end
abstract type AbstractRepulsionType end

kernel_dft(r::Int64, W::Float64, N::Int64) = r==0 ? 0.25W : 0.25W*exp(1im*π*(r/N - 0.5))/sin(π*r/N)

kernel_func(τ′, τ′′, W, c) = (0.25W - 0.5*abs(τ′-τ′′) - W*(0.5-τ′/W)*(0.5-τ′′/W))*c

struct GaugeRepulsion <: AbstractRepulsion
    fs::Vector{Float64}
    M::Matrix{Float64}
    N::Int64
    function GaugeRepulsion(params::AbstractParams, ω₀::Float64)
        W, N, u, Δτ = params.W, params.N, params.u, params.Δτ
        c = 2u*ω₀^2*Δτ^2
        fs = zeros(Float64, N)
        M = zeros(Float64, N, N)
        τs = Δτ*collect(0:N-1)
        for j = 1:N
            for i = 1:N
                M[i,j] = kernel_func(τs[i], τs[j], W, c)
            end
        end
        #print(c, "\n")
        new(fs, M, N)
    end
end

struct GaugeRepulsion2 <: AbstractRepulsion
	fs::Vector{Float64}
	ηs::Vector{Float64}
	N::Int64
	c::Float64
	function GaugeRepulsion2(params::AbstractParams, ω₀::Float64)
        W, N, u, Δτ = params.W, params.N, params.u, params.Δτ
        c = 2u*ω₀^2*Δτ^3
        #print(c, "\n")
        fs = zeros(Float64, N)
		ηs = zeros(Float64, N)
		new(fs, ηs, N, c)
	end
end

function compute_repulsion!(grep::GaugeRepulsion, bs::AbstractVector)
    fs, M, N = grep.fs, grep.M, grep.N
    b0 = view(bs, 1:N)
    mul!(fs, M, b0)
    return 0.5*dot(fs,b0), fs
end

function compute_repulsion!(grep::GaugeRepulsion2, bs::AbstractVector)
	fs, ηs, N, c = grep.fs, grep.ηs, grep.N, grep.c
	##
	ηs[1] = N*bs[1]
	@inbounds for i = 1:N-1
		ηs[1] += i*bs[i+1]
	end
	ηs[1] /= N
	for i = 2:N
		ηs[i] = ηs[i-1] + bs[i]
	end
	##
	fs[N] = ηs[N]*c
	for i = N-1:-1:2
		fs[i] = fs[i+1] + c*ηs[i]
	end
	##
	return 0.5*dot(ηs, ηs)*c, fs
end

export GaugeRepulsion, GaugeRepulsion2, compute_repulsion!

full_kernel_dft(r::Int64, α′W::Float64, N::Int64) = sinh(α′W/N)/(cosh(α′W/N) - cos(2π*r/N))

full_kernel_func(τ′, τ′′, α′, W) = cosh(α′*(0.5W - abs(τ′ - τ′′)))/sinh(0.5W*α′)
full_kernel_func2(τ′, τ′′, α′, W) = (exp(-α′*abs(τ′ - τ′′)) + exp(-α′*(W - abs(τ′ - τ′′))))/(1-exp(-α′*W))

struct FullRepulsionFFT{TP1, TP2} <: AbstractRepulsion
    W::Float64
    N::Int64
    Nhalf::Int64
    c::Float64
    ker_dft::Vector{Complex{Float64}}
    rp::TP1
    irp::TP2
    ys::Vector{Complex{Float64}}
    fs::Vector{Float64}
    function FullRepulsionFFT(params::AbstractParams, α₀::Float64, a₂::Float64)
        W, N, u, Δτ = params.W, params.N, params.u, params.Δτ
        α′ = α₀/sqrt(1 + a₂)
        c = u*a₂*α′*Δτ^2
        Nhalf = div(N,2)+1
        ts = 0.5.-collect(0:N-1)*Δτ
        ker_dft = zeros(Complex{Float64}, Nhalf)
        ker_dft .= full_kernel_dft.(collect(0:Nhalf-1), α′*W, N)
        ys = zeros(Complex{Float64}, Nhalf)
        fs = zeros(Float64, N)
        rp = plan_rfft(ts)
        irp = plan_irfft(ker_dft, N)
        new{typeof(rp), typeof(irp)}(W, N, Nhalf, c, ker_dft, rp, irp, ys, fs)
    end
end

function compute_repulsion!(grep::FullRepulsionFFT, bs::AbstractVector)
    N, W, c = grep.N, grep.W, grep.c
    fs = grep.fs
    b0 = view(bs, 1:N)
    mul!(grep.ys, grep.rp, b0)
    grep.ys .*= grep.ker_dft
    mul!(fs, grep.irp, grep.ys)
    #fs .= (fs .- ts.*(W*av)).*2uω₀²*Δτ^2
    fs .= fs.*c
    return 0.5*dot(fs, b0), fs
end
function compute_repulsion(grep::FullRepulsionFFT, bs::AbstractVector)
    N, W, c = grep.N, grep.W, grep.c
    fs = grep.fs
    b0 = view(bs, 1:N)
    mul!(grep.ys, grep.rp, b0)
    grep.ys .*= grep.ker_dft
    mul!(fs, grep.irp, grep.ys)
    #fs .= (fs .- ts.*(W*av)).*2uω₀²*Δτ^2
    fs .= fs.*c
    return 0.5*dot(fs, b0)
end

struct FullRepulsion <: AbstractRepulsion
    fs::Vector{Float64}
    M::Matrix{Float64}
    N::Int64
    function FullRepulsion(params::AbstractParams, α₀::Float64, a₂::Float64)
        W, N, u, Δτ = params.W, params.N, params.u, params.Δτ
        α′ = α₀/sqrt(1 + a₂)
        c = u*a₂*α′*Δτ^2
        fs = zeros(Float64, N)
        M = zeros(Float64, N, N)
        τs = Δτ*collect(0:N-1)
        for j = 1:N
            for i = 1:N
                M[i,j] = full_kernel_func2(τs[i], τs[j], α′, W)*c
            end
        end
        print(c, "\n")
        new(fs, M, N)
    end
end

function compute_repulsion!(grep::FullRepulsion, bs::AbstractVector)
    fs, M, N = grep.fs, grep.M, grep.N
    b0 = view(bs, 1:N)
    mul!(fs, M, b0)
    return 0.5*dot(fs,b0), fs
end

export FullRepulsionFFT, FullRepulsion

struct Gauge <: AbstractRepulsionType
    ω₀::Float64
end
struct Gauge2 <: AbstractRepulsionType
    ω₀::Float64
end
struct FullFFT <: AbstractRepulsionType
    α₀::Float64
    a₂::Float64
end
struct Full <: AbstractRepulsionType
    α₀::Float64
    a₂::Float64
end

construct_repulsion(reptyp::Gauge, params) = GaugeRepulsion(params, reptyp.ω₀)
construct_repulsion(reptyp::Gauge2, params) = GaugeRepulsion2(params, reptyp.ω₀)
construct_repulsion(reptyp::FullFFT, params) = FullRepulsionFFT(params, reptyp.α₀, reptyp.a₂)
construct_repulsion(reptyp::Full, params) = FullRepulsion(params, reptyp.α₀, reptyp.a₂)

export Gauge, Gauge2, FullFFT, Full, construct_repulsion


text:
struct Board
    designation::String
    checker_width_cm::Float64
    dimensions::Tuple{Int, Int}
    description::String

    function Board(designation, checker_width_cm, dimensions, description)
        @assert !isempty(designation) "empty board designation is not allowed"
        @assert checker_width_cm > 0 "checker width must be larger zero"
        w, h = dimensions
        @assert w > 1 "number of checkers must be larger one"
        @assert h > 1 "number of checkers must be larger one"
        @assert !isempty(description) "empty board description is not allowed"
        new(designation, checker_width_cm, dimensions, description)
    end

end

Board() = Board("_", 1.0, (2,2), "_")

struct Calibration{T, S}
    intrinsic::T # Missing or Temporal{Prolonged}
    extrinsic::S # Temporal{Instantaneous}
    board::Board
    comment::String
end

Calibration() = Calibration(missing, Temporal(), Board(), "")
Calibration(c::Calibration, args) = Calibration(get(args, :intrinsic, c.intrinsic), get(args, :extrinsic, c.extrinsic), get(args, :board, c.board), get(args, :comment, c.comment))

filenames(c::Calibration) = first(filenames(c.extrinsic.video))
start(c::Calibration) = start(c.extrinsic.time)


text:
"""
    SinusoidSource(eltype, samplerate, freqs)

SinusoidSource is a single-channel sine-tone signal generator. `freqs` can be an
array of frequencies for a multi-frequency source, or a single frequency for a
single sinusoid source.

Inputs
------
* `samplerate` specifies the sample rate of the signal.
* `freqs` sinusoid frequencies to generate.

Output
------
* SampleSource object

Example
-------
```julia
source_object = SinusoidSource(Float64, 48u"kHz", 200:200:2400)
cn = read(source_object, 50u"ms")     # Generate 50 ms of harmonic stack audio
```
"""
mutable struct SinusoidSource{T} <: SampleSource
    samplerate::Float64
    freqs::Vector{Float64} # in radians/sample
    phases::Vector{Float64}

    function SinusoidSource(eltype, samplerate::Number, freqs::Array)
        # convert frequencies from cycles/sec to rad/sample
        radfreqs = map(f->2pi*f/samplerate, freqs)
        new{eltype}(Float64(samplerate), radfreqs, zeros(length(freqs)))
    end
    SinusoidSource(eltype, samplerate, freq::StepRange) = SinusoidSource(eltype, samplerate, collect(freq))
    SinusoidSource(eltype, samplerate::Number, freq::Real) = SinusoidSource(eltype, samplerate, [freq])
    SinusoidSource(eltype, samplerate::Unitful.Frequency, freq::Real) = SinusoidSource(eltype, samplerate |> u"Hz" |> ustrip, [freq])
    SinusoidSource(eltype, samplerate::Unitful.Frequency, freq::Array) = SinusoidSource(eltype, samplerate |> u"Hz" |> ustrip, freq)
end

Base.eltype(::SinusoidSource{T}) where T = T
nchannels(source::SinusoidSource) = 1
samplerate(source::SinusoidSource) = source.samplerate

function unsafe_read!(source::SinusoidSource, buf::Array, frameoffset, framecount)
    inc = 2pi / samplerate(source)

    for i in 1:framecount
        buf[i+frameoffset, 1] = 0
    end

    for tone_idx in 1:length(source.freqs)
        tone_freq = source.freqs[tone_idx]
        tone_phas = source.phases[tone_idx]

        for i in 1:framecount
            buf[i+frameoffset, 1] += sin.(tone_phas)
            tone_phas += tone_freq
        end
        source.phases[tone_idx] = tone_phas

    end

    framecount
end


text:
__precompile__() # this module is safe to precompile
module Adaptive

using PyPlot
import PyPlot: plot

using PyCall
const adaptive = PyNULL()

function __init__()
    #copy!(adaptive, pyimport_conda("adaptive", "adaptive"))
    copy!(adaptive, pyimport_conda("adaptive", "adaptive", "conda-forge"))
end

import Base.getproperty

import TaskMaster: Learner, ask!, tell!

abstract type AdaptiveLearner <: Learner end
ask!(learner::AdaptiveLearner,input) = learner.learner.ask(1)[1][1] ### Need to make ask! accept a state.
tell!(learner::AdaptiveLearner,(xi,yi)) = learner.learner.tell(xi,yi)

######### 1D #########

struct AdaptiveLearner1D <: AdaptiveLearner
    learner
end
AdaptiveLearner1D(box::Tuple{Number,Number}) = AdaptiveLearner1D(adaptive.Learner1D(x->NaN,box))

function Base.getproperty(l::AdaptiveLearner1D,s::Symbol)
    learner = getfield(l,:learner)

    if s==:x
        d = [(key,value) for (key,value) in learner.data]
        x = Float64[i[1] for i in d]
        sort(x)
    elseif s==:y
        d = [(key,value) for (key,value) in learner.data]
        x = Float64[i[1] for i in d]
        y = Float64[i[2] for i in d]
        y[sortperm(x)]
    elseif s==:data
        learner.data
    elseif s==:pending_points
        Set(p for p in learner.pending_points)
    elseif s==:learner
        learner
    else
        getproperty(learner,s)
    end
end

########## 2D #############

struct AdaptiveLearner2D <: AdaptiveLearner
    learner
    AdaptiveLearner2D(box) = new(adaptive.Learner2D(x->NaN,box))
end

function Base.getproperty(l::AdaptiveLearner2D,s::Symbol)
    learner = getfield(l,:learner)

    if s==:points
        tri = learner.ip().tri
        tri.points
    elseif s==:vertices
        tri = learner.ip().tri
        tri.vertices .+ 1
    elseif s==:pending_points
        Set(p for p in learner.pending_points)
    elseif s==:values
        [v for v in py"$(learner).data.values()"]
    elseif s==:learner
        learner
    else
        getproperty(learner,s)
    end
end

### ToDo
# - Add more options
# - Think of way to make Adaptive independent of Plots. RecipesBase? Or optional dependencies.
function plot(learner2d::AdaptiveLearner2D)
    p,tri,v = learner2d.points, learner2d.vertices, learner2d.values
    tricontourf(p[:,1],p[:,2],tri.-1,v)
    triplot(p[:,1],p[:,2],tri.-1,"k.-")
end

export AdaptiveLearner1D, AdaptiveLearner2D, ask!, tell!, plot

end


text:
module MsgPack2

using Serialization

export pack, unpack

include("types.jl")
include("formats.jl")
include("views.jl")
include("unpack.jl")
include("pack.jl")

end # module


text:
# This file is a part of MGVI.jl, licensed under the MIT License (MIT).

using MGVI

using HypothesisTests
using Random

if :ModelPolyfit ∉ names(Main)
    include("test_models/model_polyfit.jl")
    import .ModelPolyfit
end

Test.@testset "test_cmp_residual_samplers" begin

    model = ModelPolyfit.model
    true_params = ModelPolyfit.true_params
    starting_point = ModelPolyfit.starting_point

    Random.seed!(42)
    num_of_test_samples = 60

    fisher, jac = MGVI.fisher_information_and_jac(model, true_params, FullJacobianFunc)

    full_rs = FullResidualSampler(fisher, jac)
    full_samples_1 = rand(Random.GLOBAL_RNG, full_rs, num_of_test_samples)
    full_samples_2 = rand(Random.GLOBAL_RNG, full_rs, num_of_test_samples)
    B0 = BartlettTest(full_samples_1', full_samples_2')

    Test.@test pvalue(B0) > 5E-2

    implicit_rs = ImplicitResidualSampler(fisher, jac)
    implicit_samples = rand(Random.GLOBAL_RNG, implicit_rs, num_of_test_samples)
    B1 = BartlettTest(full_samples_1', implicit_samples')

    Test.@test B1.L′ > B0.L′/10
    Test.@test B1.L′ < B0.L′*10

end


text:
using MPI

MPI.Init()

comm = MPI.COMM_WORLD
N = 4
root = 0

if MPI.Comm_rank(comm) == root
  v = randn(N)
else
  v = Vector{Float64}(undef, N)
end

MPI.Bcast!(v, root, comm)

M = randn(N, N)

Mv = M * v

@show Mv

Mv_total = MPI.Reduce(Mv, +, root, comm)

@show MPI.Comm_rank(comm), Mv_total

MPI.Finalize()

max_stars_repo_name: mtfishman/ITensorParallel


text:
function equals(obj::UnivariateDerivative2Field, arg0::Object)
    return jcall(obj, "equals", jboolean, (Object,), arg0)
end

function get_instance(::Type{UnivariateDerivative2Field})
    return jcall(UnivariateDerivative2Field, "getInstance", UnivariateDerivative2Field, ())
end

function get_one(obj::UnivariateDerivative2Field)
    return jcall(obj, "getOne", UnivariateDerivative2, ())
end

function get_runtime_class(obj::UnivariateDerivative2Field)
    return jcall(obj, "getRuntimeClass", Class, ())
end

function get_zero(obj::UnivariateDerivative2Field)
    return jcall(obj, "getZero", UnivariateDerivative2, ())
end

function hash_code(obj::UnivariateDerivative2Field)
    return jcall(obj, "hashCode", jint, ())
end


text:
# Output

include("euler_exact.jl")

using PyPlot

"Plot 1D variables along a line."
function plotvar(param::Param, it, state_GV)
   # Now this only works for 1D x!
   (;iMin, iMax, jMin, jMax, kMin, kMax) = param

   plotvar = param.PlotVar
   nG = param.nG

   if plotvar == "rho"
      var = @view state_GV[:,:,:,Rho_]
   elseif plotvar == "ux"
      @views var = state_GV[:,:,:,Ux_]./state_GV[:,:,:,Rho_]
   elseif plotvar == "p"
      var = @view state_GV[:,:,:,P_]
   else
      error("unknown plotting varname!")
   end

   x = param.x[1+nG:end-nG]

   var = @view var[iMin:iMax,jMin:jMax,kMin:kMax] # Remove ghost cells
   var = dropdims(var; dims=(2,3))

   plot(x, var, marker=".")

   title("iStep=$(it)")
   legend(labels=[plotvar])

   return nothing
end

"Plot the analytical solution of shock tube problem."
function plot_Riemann_exact(param::Param)
   # Obtain the initial states
   Rho, U, P, tEnd = setInitRiemann(param.RiemannProblemType)
   # Exact solution
   xe, re, ue, pe, ee, te, Me, se =
      getEulerExactSol(Rho[1], U[1], P[1], Rho[end], U[end], P[end], tEnd, 3)

   # Ee = @. pe/((γ-1)*re) + 0.5*ue^2

   if param.PlotVar == "rho"
      plot(xe, re, "--")
   elseif param.PlotVar == "p"
      plot(xe, pe, "--")
   elseif param.PlotVar == "ux"
      plot(xe, ue, "--")
   end

   return
end


text:
# Note that this script can accept some limited command-line arguments, run
# `julia build_tarballs.jl --help` to see a usage message.
using BinaryBuilder, Pkg

name = "GDAL"
upstream_version = v"3.4.1"
version_offset = v"0.0.0"
version = VersionNumber(upstream_version.major * 100 + version_offset.major,
                        upstream_version.minor * 100 + version_offset.minor,
                        upstream_version.patch * 100 + version_offset.patch)

# Collection of sources required to build GDAL
sources = [
    ArchiveSource("https://github.com/OSGeo/gdal/releases/download/v$upstream_version/gdal-$upstream_version.tar.gz",
        "e360387bc25ec24940f46afbeada48002d72c74aaf9eccf2a40e8d74e711a2e4"),
    DirectorySource("./bundled"),
]

# Bash recipe for building across all platforms
script = raw"""
cd $WORKSPACE/srcdir/gdal-*/

if [[ ${target} == *mingw* ]]; then
    export LDFLAGS="-L${libdir}"
    # Apply patch to customise PROJ library
    atomic_patch -p1 "$WORKSPACE/srcdir/patches/configure_ac_proj_libs.patch"
    autoreconf -vi
    export PROJ_LIBS="proj_8_2"
elif [[ "${target}" == *-linux-* ]]; then
    # Hint to find libstdc++, required to link against C++ libs when using C compiler
    if [[ "${nbits}" == 32 ]]; then
        export CFLAGS="-Wl,-rpath-link,/opt/${target}/${target}/lib"
    else
        export CFLAGS="-Wl,-rpath-link,/opt/${target}/${target}/lib64"
    fi
    # Use same flags also for GEOS
    atomic_patch -p1 "$WORKSPACE/srcdir/patches/geos-m4-extra-cflags.patch"
    export EXTRA_GEOS_CFLAGS="${CFLAGS}"
    if [[ "${target}" == powerpc64le-* ]]; then
        atomic_patch -p1 "$WORKSPACE/srcdir/patches/sqlite3-m4-extra-libs.patch"
        export EXTRA_GEOS_LIBS="${EXTRA_GEOS_LIBS} -lm"
        export EXTRA_SQLITE3_LIBS="-lm"
        # libpthread and libldl are needed for libgdal, so let's always use them
        export LDFLAGS="$LDFLAGS -lpthread -ldl"
    fi
    autoreconf -vi
fi

# same fix as used for PROJ
if [[ "${target}" == x86_64-linux-musl* ]]; then
    export LDFLAGS="$LDFLAGS -lcurl"
fi

# Clear out `.la` files since they're often wrong and screw us up
rm -f ${prefix}/lib/*.la

# Read the options in the log file
./configure --help

./configure --prefix=${prefix} --build=${MACHTYPE} --host=${target} \
    --with-geos=${bindir}/geos-config \
    --with-proj=$prefix \
    --with-tiff=$prefix \
    --with-geotiff=$prefix \
    --with-libz=$prefix \
    --with-expat=$prefix \
    --with-zstd=$prefix \
    --with-sqlite3=$prefix \
    --with-curl=${bindir}/curl-config \
    --with-openjpeg \
    --with-python=no \
    --enable-shared \
    --disable-static

# Make sure that some important libraries are found
grep "HAVE_GEOS='yes'" config.log
grep "HAVE_SQLITE='yes'" config.log
grep "CURL_SETTING='yes'" config.log
grep "ZSTD_SETTING='yes'" config.log
grep "HAVE_EXPAT='yes'" config.log

make -j${nproc}
make install
"""

# These are the platforms we will build for by default, unless further
# platforms are passed in on the command line
platforms = expand_cxxstring_abis(supported_platforms())

# The products that we will ensure are always built
products = [
    LibraryProduct("libgdal", :libgdal),
    ExecutableProduct("gdal_contour", :gdal_contour_path),
    ExecutableProduct("gdal_grid", :gdal_grid_path),
    ExecutableProduct("gdal_rasterize", :gdal_rasterize_path),
    ExecutableProduct("gdal_translate", :gdal_translate_path),
    ExecutableProduct("gdaladdo", :gdaladdo_path),
    ExecutableProduct("gdalbuildvrt", :gdalbuildvrt_path),
    ExecutableProduct("gdaldem", :gdaldem_path),
    ExecutableProduct("gdalinfo", :gdalinfo_path),
    ExecutableProduct("gdallocationinfo", :gdallocationinfo_path),
    ExecutableProduct("gdalmanage", :gdalmanage_path),
    ExecutableProduct("gdalsrsinfo", :gdalsrsinfo_path),
    ExecutableProduct("gdaltindex", :gdaltindex_path),
    ExecutableProduct("gdaltransform", :gdaltransform_path),
    ExecutableProduct("gdalwarp", :gdalwarp_path),
    ExecutableProduct("nearblack", :nearblack_path),
    ExecutableProduct("ogr2ogr", :ogr2ogr_path),
    ExecutableProduct("ogrinfo", :ogrinfo_path),
    ExecutableProduct("ogrlineref", :ogrlineref_path),
    ExecutableProduct("ogrtindex", :ogrtindex_path),
]

# Dependencies that must be installed before this package can be built
dependencies = [
    Dependency("GEOS_jll"; compat="~3.10"),
    Dependency("PROJ_jll"; compat="~800.200"),
    Dependency("Zlib_jll"),
    Dependency("SQLite_jll"),
    Dependency("OpenJpeg_jll"),
    Dependency("Expat_jll"; compat="2.2.10"),
    Dependency("Zstd_jll"),
    Dependency("Libtiff_jll"; compat="4.3"),
    Dependency("libgeotiff_jll"; compat="1.7"),
    Dependency("LibCURL_jll"),
]

# Build the tarballs, and possibly a `build.jl` as well.
build_tarballs(ARGS, name, version, sources, script, platforms, products, dependencies; julia_compat="1.6", preferred_gcc_version=v"6")

max_stars_repo_name: jakebolewski/Yggdrasil

max_issues_repo_name: jakebolewski/Yggdrasil

max_forks_repo_name: jakebolewski/Yggdrasil


text:
using Printf
using Glob
using JLD2
using PyCall

using Oceananigans: Face, Center
using Oceananigans.Utils: prettytime

plt = pyimport("matplotlib.pyplot")
cmocean = pyimport("cmocean")

plot_indices(N, i, ::Center) = (i-1) * N + 1 : i * N
plot_indices(N, i, ::Face)   = (i-1) * (N+1) + 1 : i * (N+1)

function x_plot_indices(Nx, f, loc_x)
    f == 1   && return plot_indices(Nx, 1, loc_x)
    f in 2:3 && return plot_indices(Nx, 2, loc_x)
    f in 4:5 && return plot_indices(Nx, 3, loc_x)
    f == 6   && return plot_indices(Nx, 4, loc_x)
end

function y_plot_indices(Ny, f, loc_y)
    f in 1:2 && return plot_indices(Ny, 1, loc_y)
    f in 3:4 && return plot_indices(Ny, 2, loc_y)
    f in 5:6 && return plot_indices(Ny, 3, loc_y)
end

function animate_faces(filepath, var, loc; filename_pattern, cmap, vmin, vmax, iters=nothing, make_movie=true, delete_pngs=false)

    ## Extract data

    file = jldopen(filepath)

    iterations = parse.(Int, keys(file["timeseries/t"]))

    Nf = file["grid/faces"] |> keys |> length
    Nx = file["grid/faces/1/Nx"]
    Ny = file["grid/faces/1/Ny"]

    ## Plot!

    iterations_to_plot = isnothing(iters) ? iterations : iterations[iters]

    for (n, i) in enumerate(iterations_to_plot)
        @info "Plotting iteration $i/$(iterations_to_plot[end]) (frame $n/$(length(iterations_to_plot)))..."

        fig, ax = plt.subplots(figsize=(16, 9))

        for f in 1:Nf
            data = file["timeseries/$var/$i"][f][:, :, 1]
            is = x_plot_indices(Nx, f, loc[1])
            js = y_plot_indices(Ny, f, loc[2])

            # For pcolormesh we want to specify the cell boundaries
            # so we add an extra grid point at the end. Otherwise
            # we get gaps between the faces.
            is = is.start : is.stop+1
            js = js.start : js.stop+1

            pcm = ax.pcolormesh(is, js, data'; cmap, vmin, vmax)

            f == Nf && fig.colorbar(pcm, ax=ax)
        end

        t = prettytime(file["timeseries/t/$i"])
        ax.set_title("Cubed sphere $var(λ, φ) @ iteration $i ($t)")
        ax.set_aspect("equal")

        filename = @sprintf("%s_%04d.png", filename_pattern, n)
        plt.savefig(filename, dpi=200)
        plt.close(fig)
    end

    close(file)

    if make_movie
        png_filename_pattern = "$(filename_pattern)_%04d.png"
        mp4_filename = "$filename_pattern.mp4"
        run(`ffmpeg -y -i $png_filename_pattern -c:v libx264 -vf fps=30 -pix_fmt yuv420p $mp4_filename`)
    end

    if delete_pngs
        [rm(f) for f in glob("$filename_pattern*.png")]
    end

    return nothing
end

function animate_eddying_aquaplanet_faces()
    filepath = "cubed_sphere_eddying_aquaplanet.jld2"

    animate_faces("cubed_sphere_eddying_aquaplanet.jld2", "u", (Center(), Center()), filename_pattern = "eddying_aquaplanet_u", cmap = cmocean.cm.balance, vmin = -1, vmax = +1, make_movie = true, delete_pngs = true)

    for u in ("u", "v")
        animate_faces(filepath, u, (Center(), Center()),
            filename_pattern = "eddying_aquaplanet_$u",
                        cmap = cmocean.cm.balance,
                        vmin = -1,
                        vmax = +1,
                  make_movie = true,
                 delete_pngs = true
        )
    end

    animate_faces(filepath, "η", (Center(), Center()),
        filename_pattern = "eddying_aquaplanet_eta",
                    cmap = cmocean.cm.balance,
                    vmin = -0.1,
                    vmax = +0.1,
              make_movie = false,
             delete_pngs = false
    )

    # TODO: Fix (Face(), Face()) plotting by saving all (N+1)×(N+1) values.
    animate_faces(filepath, "ζ", (Center(), Center()),
        filename_pattern = "eddying_aquaplanet_vorticity",
                 # iters = 1:6:634,
                    cmap = cmocean.cm.balance,
                    vmin = -2e-7,
                    vmax = +2e-7,
              make_movie = true,
             delete_pngs = false
    )
end