text:
using ProgressMeter

T = 50
N = 50

pomdp = BabyPOMDP()

bds = IndependentBounds(reward(pomdp, true, false)/(1-discount(pomdp)), 0.0)

solver = DESPOTAlphaSolver(epsilon_0=0.1,
                      K=300,
                      max_depth=50,
                      bounds=bds,
                      T_max=Inf,
                      max_trials=5000,
                      rng=MersenneTwister(4)
                     )

rsum = 0.0
fwc_rsum = 0.0
@showprogress for i in 1:N
    planner = solve(solver, pomdp)
    sim = RolloutSimulator(max_steps=T, rng=MersenneTwister(i))
    fwc_sim = deepcopy(sim)
    global rsum += simulate(sim, pomdp, planner)
    global fwc_rsum += simulate(fwc_sim, pomdp, FeedWhenCrying())
end

@show rsum/N
@show fwc_rsum/N


text:
# This script prints out HackBio participant data as a part of stage 0 task.

print("name: Jeff Bezos\nE-MAIL: jeff@lnu.edu.ua\nUSED LANGUAGE: JULIA\nBIOSTACK: Chemoinformatics\nSLACK USERNAME: @jeff\n")

ext: jl

max_stars_repo_name: rajimedbio/team-rosalind-project

max_issues_repo_name: rajimedbio/team-rosalind-project

max_forks_repo_name: rajimedbio/team-rosalind-project


text:
module AbstractGUI

using WindowAbstractions
using XCB
using GeometryExperiments
using MLStyle
using Dictionaries

import WindowAbstractions: execute_callback, run, terminate_window!, get_window, get_window_symbol, callbacks, poll_for_event, wait_for_event
import XCB: set_callbacks!

include("utils.jl")
include("widgets.jl")
include("callbacks.jl")
include("window_manager.jl")
include("gui.jl")
include("events.jl")

export
    # widgets
    Widget,
    zindex,

    # events
    WidgetCallbacks,
    callbacks,
    captures_event,
    find_target,

    # WindowManager
    WindowManager,

    # GUI manager
    GUIManager,
    widgets

end


text:
@with_kw struct ShipData{Tt,Tu,Tv,Tr,Tx,Ty,Tψ,Tδ,Tn_p}
    time::Tt
    u::Tu
    v::Tv
    r::Tr
    x::Tx
    y::Ty
    ψ::Tψ
    δ::Tδ
    n_p::Tn_p
end

function get_KVLCC2_L7_basic_params()
    ρ = 1.025
    L_pp = 7.00  # 船長Lpp[m]
    B = 1.27  # 船幅[m]
    d = 0.46  # 喫水[m]
    nabla = 3.27  # 排水量[m^3]
    x_G = 0.25  # 重心位置[m]
    # C_b = 0.810  # 方形係数[-]
    D_p = 0.216  # プロペラ直径[m]
    H_R = 0.345  # 舵高さ[m]
    A_R = 0.0539  # 舵断面積[m^2]
    t_P = 0.220  # 推力減少率
    w_P0 = 0.40  # 有効伴流率
    m_x_dash = 0.022  # 付加質量x(無次元)
    m_y_dash = 0.223  # 付加質量y(無次元)
    J_z_dash = 0.011  # 付加質量Izz(無次元)
    t_R = 0.387  # 操縦抵抗減少率
    a_H = 0.312  # 舵力増加係数
    x_H_dash = -0.464  # 舵力増分作用位置
    γ_R_minus = 0.395  # 整流係数
    γ_R_plus = 0.640  # 整流係数
    l_r_dash = -0.710  # 船長に対する舵位置
    x_P_dash = -0.690  # 船長に対するプロペラ位置
    ϵ = 1.09  # プロペラ・舵位置伴流係数比
    κ = 0.50  # 修正係数
    f_α = 2.747  # 直圧力勾配係数

    L_pp = L_pp  # 船長Lpp[m]
    B = B  # 船幅[m]
    d = d  # 喫水[m]
    x_G = x_G  # 重心位置[]
    D_p = D_p  # プロペラ直径[m]
    m = ρ * nabla  # 質量(無次元化)[kg]
    I_zG = ρ * nabla * ((0.25 * L_pp)^2)  # 慣性モーメント[-]
    A_R = A_R  # 船の断面に対する舵面積比[-]
    η = D_p / H_R  # プロペラ直径に対する舵高さ(Dp/H)
    m_x = (0.5 * ρ * (L_pp^2) * d) * m_x_dash  # 付加質量x(無次元)
    m_y = (0.5 * ρ * (L_pp^2) * d) * m_y_dash  # 付加質量y(無次元)
    J_z = (0.5 * ρ * (L_pp^4) * d) * J_z_dash  # 付加質量Izz(無次元)
    f_α = f_α # 直圧力勾配係数
    ϵ = ϵ  # プロペラ・舵位置伴流係数比
    t_R = t_R  # 操縦抵抗減少率
    a_H = a_H  # 舵力増加係数
    x_H = x_H_dash * L_pp  # 舵力増分作用位置
    γ_R_minus = γ_R_minus  # 整流係数
    γ_R_plus = γ_R_plus  # 整流係数
    l_R = l_r_dash  # 船長に対する舵位置
    κ = κ  # 修正係数
    t_P = t_P  # 推力減少率
    w_P0 = w_P0  # 有効伴流率
    x_P = x_P_dash  # 船長に対するプロペラ位置
    basic_params = Mmg3DofBasicParams(
        L_pp,
        B,
        d,
        x_G,
        D_p,
        m,
        I_zG,
        A_R,
        η,
        m_x,
        m_y,
        J_z,
        f_α,
        ϵ,
        t_R,
        a_H,
        x_H,
        γ_R_minus,
        γ_R_plus,
        l_R,
        κ,
        t_P,
        w_P0,
        x_P,
    )
    basic_params
end

function get_KVLCC2_L7_maneuvering_params()
    k_0 = 0.2931
    k_1 = -0.2753
    k_2 = -0.1385
    R_0_dash = 0.022
    X_vv_dash = -0.040
    X_vr_dash = 0.002
    X_rr_dash = 0.011
    X_vvvv_dash = 0.771
    Y_v_dash = -0.315
    Y_r_dash = 0.083
    Y_vvv_dash = -1.607
    Y_vvr_dash = 0.379
    Y_vrr_dash = -0.391
    Y_rrr_dash = 0.008
    N_v_dash = -0.137
    N_r_dash = -0.049
    N_vvv_dash = -0.030
    N_vvr_dash = -0.294
    N_vrr_dash = 0.055
    N_rrr_dash = -0.013
    maneuvering_params = Mmg3DofManeuveringParams(
        k_0,
        k_1,
        k_2,
        R_0_dash,
        X_vv_dash,
        X_vr_dash,
        X_rr_dash,
        X_vvvv_dash,
        Y_v_dash,
        Y_r_dash,
        Y_vvv_dash,
        Y_vvr_dash,
        Y_vrr_dash,
        Y_rrr_dash,
        N_v_dash,
        N_r_dash,
        N_vvv_dash,
        N_vvr_dash,
        N_vrr_dash,
        N_rrr_dash,
    )
    maneuvering_params
end

function get_KVLCC2_L7_params()
    basic_params = get_KVLCC2_L7_basic_params()
    maneuvering_params = get_KVLCC2_L7_maneuvering_params()
    basic_params, maneuvering_params
end

function calc_position(time_vec, u_vec, v_vec, r_vec; x0 = 0.0, y0 = 0.0, ψ0 = 0.0)
    dim = length(time_vec)
    x_vec = zeros(Float64, dim)
    y_vec = zeros(Float64, dim)
    ψ_vec = zeros(Float64, dim)
    x_vec[1] = x0
    y_vec[1] = y0
    ψ_vec[1] = ψ0
    for i = 2:dim
        Δt = time_vec[i] - time_vec[i-1]
        ψ_vec[i] = ψ_vec[i-1] + r_vec[i] * Δt
        x_vec[i] = x_vec[i-1] + (u_vec[i] * cos(ψ_vec[i]) - v_vec[i] * sin(ψ_vec[i])) * Δt
        y_vec[i] = y_vec[i-1] + (u_vec[i] * sin(ψ_vec[i]) + v_vec[i] * cos(ψ_vec[i])) * Δt
    end
    x_vec, y_vec, ψ_vec
end

function nuts_sampling_single_thread(
    model,
    n_samples::Int,
    n_chains::Int;
    target_acceptance::Float64 = 0.65,
    progress = true,
)
    sampler = NUTS(target_acceptance)
    mapreduce(
        c -> sample(model, sampler, n_samples, progress = progress),
        chainscat,
        1:n_chains,
    )
end

function nuts_sampling_multi_threads(
    model,
    n_samples::Int,
    n_chains::Int;
    target_acceptance::Float64 = 0.65,
    progress = false,
)
    sampler = NUTS(target_acceptance)
    sample(model, sampler, MCMCThreads(), n_samples, n_chains, progress = progress)
end


text:
# Strange attractors from https://www.dynamicmath.xyz/strange-attractors/ and
# https://en.wikipedia.org/wiki/List_of_chaotic_maps
# Opted for the equations as reported in papers

# Thomas
@parameters t b=0.208186
@variables x(t)=1 y(t)=0 z(t)=0
D = Differential(t)

eqs = [D(x) ~ sin(y) - b*x,
       D(y) ~ sin(z) - b*y,
       D(z) ~ sin(x) - b*z]

@named thomas = ODESystem(eqs)

"""
Thomas' cyclically symmetric attractor equations

```math
$(latexify(thomas))
```

[Reference](https://www.worldscientific.com/doi/abs/10.1142/S0218127499001383)

[Wikipedia](https://en.wikipedia.org/wiki/Thomas%27_cyclically_symmetric_attractor)
"""
prob_ode_thomas= ODEProblem(thomas,[],(0.0,1.0))

# Lorenz
@parameters t σ=10 ρ=28 β=8/3
@variables x(t)=1 y(t)=0 z(t)=0
D = Differential(t)

eqs = [D(x) ~ σ*(y-x),
       D(y) ~ x*(ρ-z)-y,
       D(z) ~ x*y - β*z]

@named lorenz = ODESystem(eqs)

"""
Lorenz equations

```math
$(latexify(lorenz))
```

[Reference](https://journals.ametsoc.org/view/journals/atsc/20/2/1520-0469_1963_020_0130_dnf_2_0_co_2.xml)

[Wikipedia](https://en.wikipedia.org/wiki/Lorenz_system)
"""
prob_ode_lorenz = ODEProblem(lorenz,[],(0.0,1.0))

# Aizawa
@parameters t a=0.95 b=0.7 c=0.6 d=3.5 e=0.25 f=0.1
@variables x(t)=1 y(t)=0 z(t)=0
D = Differential(t)

eqs = [D(x) ~ (z-b)*x-d*y,
       D(y) ~ d*x+(z-b)*y,
       D(z) ~ c+a*z-z^3/3-(x^2+y^2)*(1+e*z)+ f*z*x^3]

@named aizawa = ODESystem(eqs)

"""
Aizawa equations

```math
$(latexify(aizawa))
```

[Reference](https://journals.ametsoc.org/view/journals/atsc/20/2/1520-0469_1963_020_0130_dnf_2_0_co_2.xml)

"""
prob_ode_aizawa = ODEProblem(aizawa,[],(0.0,1.0))

# Dadras
@parameters t a=3 b=2.7 c=1.7 d=2 e=9
@variables x(t)=1 y(t)=0 z(t)=0
D = Differential(t)

eqs = [D(x) ~ y-a*x+b*y*z,
       D(y) ~ c*y-x*z+z,
       D(z) ~ d*x*y-e*z]

@named dadras = ODESystem(eqs)

"""
Dadras equations

```math
$(latexify(dadras))
```

[Reference](https://www.sciencedirect.com/science/article/abs/pii/S0375960109009591)

"""
prob_ode_dadras = ODEProblem(dadras,[],(0.0,1.0))

# chen
@parameters t a=35 b=3 c=28
@variables x(t)=1 y(t)=0 z(t)=0
D = Differential(t)

eqs = [D(x) ~ a*(y-x),
       D(y) ~ (c-a)*x-x*z+c*y,
       D(z) ~ x*y-b*z]

@named chen = ODESystem(eqs)

"""
chen equations

```math
$(latexify(chen))
```

[Reference](https://www.worldscientific.com/doi/abs/10.1142/S0218127499001024)

"""
prob_ode_chen = ODEProblem(chen,[],(0.0,1.0))

# rossler
@parameters t a=0.2 b=0.2 c=5.7
@variables x(t)=1 y(t)=0 z(t)=0
D = Differential(t)

eqs = [D(x) ~ -(y+z),
       D(y) ~ x+a*y,
       D(z) ~ b+z*(x-c)]

@named rossler = ODESystem(eqs)

"""
rossler equations

```math
$(latexify(rossler))
```

[Reference](https://www.sciencedirect.com/science/article/abs/pii/0375960176901018)
[Wikipedia](https://en.wikipedia.org/wiki/R%C3%B6ssler_attractor)

"""
prob_ode_rossler = ODEProblem(rossler,[],(0.0,1.0))

# rabinovich_fabrikant
@parameters t a=0.14 b=0.10
@variables x(t)=1 y(t)=0 z(t)=0
D = Differential(t)

eqs = [D(x) ~ y*(z-1+x^2) + b*x,
       D(y) ~ x*(3*z+1-x^2)+b*y,
       D(z) ~ -2*z*(a+x*y)]

@named rabinovich_fabrikant = ODESystem(eqs)

"""
rabinovich_fabrikant equations

```math
$(latexify(rabinovich_fabrikant))
```

[Reference](https://en.wikipedia.org/wiki/Rabinovich%E2%80%93Fabrikant_equations)

"""
prob_ode_rabinovich_fabrikant = ODEProblem(rabinovich_fabrikant,[],(0.0,1.0))

# sprott
@parameters t a=2.07 b=1.79
@variables x(t)=1 y(t)=0 z(t)=0
D = Differential(t)

eqs = [D(x) ~ y+a*x*y+x*z,
       D(y) ~ 1-b*x^2+y*z,
       D(z) ~ x-x^2-y^2]

@named sprott = ODESystem(eqs)

"""
sprott equations

```math
$(latexify(sprott))
```

[Reference](http://sprott.physics.wisc.edu/pubs/paper423.pdf)

"""
prob_ode_sprott = ODEProblem(sprott,[],(0.0,1.0))

# hindmarsh_rose
@parameters t a=1 b=3 c=1 d=5 r=1e-2 s=4 xr=-8/5 i=5
@variables x(t)=1 y(t)=0 z(t)=0
D = Differential(t)

eqs = [D(x) ~ y-a*x^3+b*x^2-z+i,
       D(y) ~ c-d*x^2-y,
       D(z) ~ r*(s*(x-xr)-z)]

@named hindmarsh_rose = ODESystem(eqs)

"""
hindmarsh_rose equations

```math
$(latexify(hindmarsh_rose))
```

[Reference](https://en.wikipedia.org/wiki/Hindmarsh%E2%80%93Rose_model)

"""
prob_ode_hindmarsh_rose = ODEProblem(hindmarsh_rose,[],(0.0,1.0))


text:
# __precompile__(true)

module Expectations

# Load external dependencies.
using Compat, FastGaussQuadrature
using LinearAlgebra
using SpecialFunctions
using Distributions

# Load internal files.
include("types.jl"),
include("iterable.jl")
include("mixturemodels.jl")

# Export
export expectation, Expectation, IterableExpectation, Gaussian, Trapezoidal, FiniteDiscrete, QuadratureAlgorithm, ExplicitQuadratureAlgorithm, nodes, weights, QuantileRange
export MixtureExpectation, expectations

end # module


text:
"""
All structs without any field are singletons.
"""
struct Singleton end


text:
using BiomolecularStructures.Mafft
using FastaIO
using BioSeq

mafft_expected = [("gi|166158130|ref|NP_001107279.1| interleukin 4 [Xenopus (Silurana) tropicalis]","MSNLGRILCAVLGLFHLLSANPVPSSKLQIAIEEIISELVNNKITHK-----KCFVPTPYDDEEEASVEEISCRAFKSLKHVCASER--------------------KNLRLLNASLITMFSE-----NVECSINNDEQKDLISVIEDLLTFFRAQM-RKLVMNPKH")
 ("gi|55742622|ref|NP_999288.1| interleukin-4 precursor [Sus scrofa]","M-GLTSQLIPTLVCLLACTSNFVHGHKCDITLQEIIKTL--NILTARKNSCMELPVTDVFAAPENTTEKETFCRASTVLRHIYRHHT----CMK-------------SLLSGLDRNLSSMAN-------MTCSVHEAKKSTLKDFLERLKTIMKEKY-SKC------")
 ("gi|55741696|ref|NP_001007080.1| interleukin 4 [Gallus gallus]","MSSSLPTLLALLVLLAGPGAVPTLCLQLSVPLMESIRIV--NDIQGE-VSCVKMNVTDIFADNKTNNKTELLCKASTI---VWESQH----CH--------------KNLQGLFLNMRQLLNASSTSLKAPCPTAAGNTTSMEKFLADLRTFFHQLAKNK-------")
 ("gi|50978886|ref|NP_001003159.1| interleukin-4 precursor [Canis lupus familiaris]","M-GLTSQLIPTLVCLLALTSTFVHGHNFNITIKEIIKML--NILTARNDSCMELTVKDVFTAPKNTSDKEIFCRAATVLRQIYTHN-----CSN-------------RYLRGLYRNLSSMAN-------KTCSMNEIKKSTLKDFLERLKVIMQKKY-YRH------")
 ("gi|42627877|ref|NP_958427.1| interleukin-4 precursor [Rattus norvegicus]","M-GLSPHLAVTLFCFLICTGNGIHGCN-DSPLREIINTL--NQVTEKGTPCTEMFVPDVLTATRNTTENELICRASRVLRKFYFPRDVPP-CLK-------NKSGVLGELRKLCRGVSGLNS------LRSCTVNESTLTTLKDFLESLKSILRGKYLQSCTSM--S")
 ("gi|58743333|ref|NP_001008993.1| interleukin-4 isoform delta2 [Pan troglodytes]","M-GLTSQLLPPLFFLLACAGNFVHGHKCDITLQEIIKTL--NSLTEQ----------------KNTTEKETFCRAATVLRQFYSHHEKDTRCLGATAQQFHRHKQLIRFLKRLDRNLWGLAG------LNSCPVKEANQSTLENFLERLKTIMREKY-SKCSS----")
 ("gi|112807223|ref|NP_001036804.1| interleukin-4 precursor [Felis catus]","M-DLTSQLIPALVCLLAFTSTFVHGQNFNNTLKEIIKTL--NILTARNDSCMELTVMDVLAAPKNTSDKEIFCRATTVLRQIYTHHN----CST-------------KFLKGLDRNLSSMAN-------RTCSVNEVKKCTLKDFLERLKAIMQKKY-SKH------")
 ("2B8U:A|PDBID|CHAIN|SEQUENCE|HOMO SAPIENS","-------------------------HKCDITLQEIIKTL--NSLTEQKTLCTELTVTDIFAASKNTTEKETFCRAATVLRQFYSHHEKDTRCLGATAQQFHRHKQLIRFLKRLDRNLWGLAG------LNSCPVKEANQSTLENFLERLKTIMREKY-SKCSS----")]

@test mafft(joinpath(dirname(@__FILE__),"..","examples/fasta","il4.fasta")) == mafft_expected

fasta_in_string = ">gi|166158130|ref|NP_001107279.1| interleukin 4 [Xenopus (Silurana) tropicalis]
MSNLGRILCAVLGLFHLLSANPVPSSKLQIAIEEIISELVNNKITHKKCFVPTPYDDEEEASVEEISCRA
FKSLKHVCASERKNLRLLNASLITMFSENVECSINNDEQKDLISVIEDLLTFFRAQMRKLVMNPKH

>gi|55742622|ref|NP_999288.1| interleukin-4 precursor [Sus scrofa]
MGLTSQLIPTLVCLLACTSNFVHGHKCDITLQEIIKTLNILTARKNSCMELPVTDVFAAPENTTEKETFC
RASTVLRHIYRHHTCMKSLLSGLDRNLSSMANMTCSVHEAKKSTLKDFLERLKTIMKEKYSKC

>gi|55741696|ref|NP_001007080.1| interleukin 4 [Gallus gallus]
MSSSLPTLLALLVLLAGPGAVPTLCLQLSVPLMESIRIVNDIQGEVSCVKMNVTDIFADNKTNNKTELLC
KASTIVWESQHCHKNLQGLFLNMRQLLNASSTSLKAPCPTAAGNTTSMEKFLADLRTFFHQLAKNK"

mafft_expected_from_string = [("gi|166158130|ref|NP_001107279.1| interleukin 4 [Xenopus (Silurana) tropicalis]","M---SNLGRILCAVLGLFHLLSANPVPSSKLQIAIEEIISEL--VNNKI-THKKCFVPTPYDDEEEASVEEISCRAFKSLKHVCASE--RKN-LRLLNASLITMFSEN-----VECSINNDEQKDLISVIEDLLTFFRAQMRKLVMNPKH")
 ("gi|55742622|ref|NP_999288.1| interleukin-4 precursor [Sus scrofa]","MGLTSQLIPTLVCLLAC----TSNFVHGHKCDITLQEIIKTLNILTARKNSCMELPVTDVFAAPENTTEKETFCRASTVLRHIYRHHTCMKSLLSGLDRNLSSMANMT-------CSVHEAKKSTLKDFLERLKTIMKEKYSK------C")
 ("gi|55741696|ref|NP_001007080.1| interleukin 4 [Gallus gallus]","M---SSSLPTLLALLVLLAGPGAVPTLCLQLSVPLMESIRIVNDIQGEV-SCVKMNVTDIFADNKTNNKTELLCKASTI---VWESQHCHKN-LQGLFLNMRQLLNASSTSLKAPCPTAAGNTTSMEKFLADLRTFFHQLAKN------K")]

@test mafft_from_string(fasta_in_string) == mafft_expected_from_string

@test mafft(joinpath(dirname(@__FILE__),"..","examples/fasta","il4.fasta"), :linsi) == mafft_expected

mafft_ginsi_expected = Any[("gi|166158130|ref|NP_001107279.1| interleukin 4 [Xenopus (Silurana) tropicalis]","MSNLGRILCAVLGLFHLLSANPVPSSKLQIAIEEIISELVNNKITHK-----KCFVPTPYDDEEEASVEEISCRAFKSLKHVCASER--------------------KNLRLLNASLITMFSE-----NVECSINNDEQKDLISVIEDLLTFFRAQMRKLVMNPKH"),("gi|55742622|ref|NP_999288.1| interleukin-4 precursor [Sus scrofa]","MGLTSQLIPTLVCLLACTS-NFVHGHKCDITLQEIIKTL--NILTARKNSCMELPVTDVFAAPENTTEKETFCRASTVLRHIYRHHTCMK-----------------SLLSGLDRNLSSMAN-------MTCSVHEAKKSTLKDFLERLKTIMKEKYSK------C"),("gi|55741696|ref|NP_001007080.1| interleukin 4 [Gallus gallus]","MSSSLPTLLALLVLLAGPGAVPTLCLQLSVPLMESIRIV--NDIQGE-VSCVKMNVTDIFADNKTNNKTELLCKASTI---VWESQHCH------------------KNLQGLFLNMRQLLNASSTSLKAPCPTAAGNTTSMEKFLADLRTFFHQLAKN------K"),("gi|50978886|ref|NP_001003159.1| interleukin-4 precursor [Canis lupus familiaris]","MGLTSQLIPTLVCLLALTS-TFVHGHNFNITIKEIIKML--NILTARNDSCMELTVKDVFTAPKNTSDKEIFCRAATVLRQIYT-HNCSN-----------------RYLRGLYRNLSSMAN-------KTCSMNEIKKSTLKDFLERLKVIMQKKYYR------H"),("gi|42627877|ref|NP_958427.1| interleukin-4 precursor [Rattus norvegicus]","MGLSPHLAVTLFCFLICTG-NGIHGCN-DSPLREIINTL--NQVTEKGTPCTEMFVPDVLTATRNTTENELICRASRVLRKFYFPRD--------VPPCLKNKSGVLGELRKLCRGVSGLNS------LRSCTVNESTLTTLKDFLESLKSILRGKYLQ-SCTSMS"),("gi|58743333|ref|NP_001008993.1| interleukin-4 isoform delta2 [Pan troglodytes]","MGLTSQLLPPLFFLLACAG-NFVHGHKCDITLQEIIKTL--NSLTEQ----------------KNTTEKETFCRAATVLRQFYSHHEKDTRCLGATAQQFHRHKQLIRFLKRLDRNLWGLAG------LNSCPVKEANQSTLENFLERLKTIMREKYSK--CS--S"),("gi|112807223|ref|NP_001036804.1| interleukin-4 precursor [Felis catus]","MDLTSQLIPALVCLLAFTS-TFVHGQNFNNTLKEIIKTL--NILTARNDSCMELTVMDVLAAPKNTSDKEIFCRATTVLRQIYTHHNCST-----------------KFLKGLDRNLSSMAN-------RTCSVNEVKKCTLKDFLERLKAIMQKKYSK------H"),("2B8U:A|PDBID|CHAIN|SEQUENCE|HOMO SAPIENS","-------------------------HKCDITLQEIIKTL--NSLTEQKTLCTELTVTDIFAASKNTTEKETFCRAATVLRQFYSHHEKDTRCLGATAQQFHRHKQLIRFLKRLDRNLWGLAG------LNSCPVKEANQSTLENFLERLKTIMREKYSK--CS--S")]

@test mafft(joinpath(dirname(@__FILE__),"..","examples/fasta","il4.fasta"), :ginsi) == mafft_ginsi_expected
@test mafft(joinpath(dirname(@__FILE__),"..","examples/fasta","il4.fasta"), :einsi) == mafft_expected

mafft_fftnsi_expected = Any[("gi|166158130|ref|NP_001107279.1| interleukin 4 [Xenopus (Silurana) tropicalis]","MSNLGRILCAVLGLFHLLSANPVPSSKLQIAIEEIISELVNNKITHK-----KCFVPTPYDDEEEASVEEISCRAFKSLKHV---------CASER-----------KNLRLLNASLITMFSEN-----VECSINNDEQKDLISVIEDLLTFFRAQMRKLVMNPKH"),("gi|55742622|ref|NP_999288.1| interleukin-4 precursor [Sus scrofa]","MG-LTSQLIPTLVCLLACTSNFVHGHKCDITLQEIIKTL--NILTARKNSCMELPVTDVFAAPENTTEKETFCRASTVLRHIYRHHT----CMK-------------SLLSGLDRNLSSMANM-------TCSVHEAKKSTLKDFLERLKTIMKEKYSKC------"),("gi|55741696|ref|NP_001007080.1| interleukin 4 [Gallus gallus]","MSSSLPTLLALLVLLAGPGAVPTLCLQLSVPLMESIRIV--NDIQGE-VSCVKMNVTDIFADNKTNNKTELLCKASTIVWESQH-------CH--------------KNLQGLFLNMRQLLNASSTSLKAPCPTAAGNTTSMEKFLADLRTFFHQLAKNK------"),("gi|50978886|ref|NP_001003159.1| interleukin-4 precursor [Canis lupus familiaris]","MG-LTSQLIPTLVCLLALTSTFVHGHNFNITIKEIIKML--NILTARNDSCMELTVKDVFTAPKNTSDKEIFCRAATVLRQIYTHN-----CSN-------------RYLRGLYRNLSSMANK-------TCSMNEIKKSTLKDFLERLKVIMQKKYYRH------"),("gi|42627877|ref|NP_958427.1| interleukin-4 precursor [Rattus norvegicus]","MG-LSPHLAVTLFCFLICTGNGIHGCN-DSPLREIINTL--NQVTEKGTPCTEMFVPDVLTATRNTTENELICRASRVLRKFYFPRDVPP-CLKNKSGVL-------GELRKLCRGVSGLNSLR------SCTVNESTLTTLKDFLESLKSILRGKYLQSCTSMS-"),("gi|58743333|ref|NP_001008993.1| interleukin-4 isoform delta2 [Pan troglodytes]","MG-LTSQLLPPLFFLLACAGNFVHGHKCDITLQEIIKTL--NSLTEQ----------------KNTTEKETFCRAATVLRQFYSHHEKDTRCLGATAQQFHRHKQLIRFLKRLDRNLWGLAGLN------SCPVKEANQSTLENFLERLKTIMREKYSKCSS----"),("gi|112807223|ref|NP_001036804.1| interleukin-4 precursor [Felis catus]","MD-LTSQLIPALVCLLAFTSTFVHGQNFNNTLKEIIKTL--NILTARNDSCMELTVMDVLAAPKNTSDKEIFCRATTVLRQIYTHHN----CST-------------KFLKGLDRNLSSMANR-------TCSVNEVKKCTLKDFLERLKAIMQKKYSKH------"),("2B8U:A|PDBID|CHAIN|SEQUENCE|HOMO SAPIENS","-------------------------HKCDITLQEIIKTL--NSLTEQKTLCTELTVTDIFAASKNTTEKETFCRAATVLRQFYSHHEKDTRCLGATAQQFHRHKQLIRFLKRLDRNLWGLAGLN------SCPVKEANQSTLENFLERLKTIMREKYSKCSS----")]

@test mafft(joinpath(dirname(@__FILE__),"..","examples/fasta","il4.fasta"), :fftnsi) == mafft_fftnsi_expected

mafft_fftns_expected = Any[("gi|166158130|ref|NP_001107279.1| interleukin 4 [Xenopus (Silurana) tropicalis]","MSNLGRILCAVLGLFHLLSANPVPS--------SKLQIAIEEIISELVNNKITHK-----KCFVPTPYDDEEEASVEEISCRAFKSLKHV---------CASER-----------KNLRLLNASLITMFSENVECSINNDEQKDLISVIEDLLTFFRAQMRKLVMNPKH--------"),("gi|55742622|ref|NP_999288.1| interleukin-4 precursor [Sus scrofa]","-MGLTSQLIPTLVCLLACTSNFVHG--------HKCDITLQEIIKTL--NILTARKNSCMELPVTDVFAAPENTTEKETFCRASTVLRHIYRHHT----CMK-------------SLLSGLDRNLSSMANM--TCSVHEAKKSTLKDFLERLKT---------IMKEKYSKC-----"),("gi|55741696|ref|NP_001007080.1| interleukin 4 [Gallus gallus]","---MSSSL-PTLLALLVL----LAGPGAVPTLCLQLSVPLMESIRIV--NDIQGE-VSCVKMNVTDIFADNKTNNKTELLCKASTIVWE--SQH-----CHK-------NLQGLFLNMRQL-LNASSTSLKA-PCPTAAGNTTSMEKFLADLRTFFH-----QLAKNK---------"),("gi|50978886|ref|NP_001003159.1| interleukin-4 precursor [Canis lupus familiaris]","-MGLTSQLIPTLVCLLALTSTFVHG--------HNFNITIKEIIKML--NILTARNDSCMELTVKDVFTAPKNTSDKEIFCRAATVLRQIYT-HN----CSN-------------RYLRGLYRNLSSMANK--TCSMNEIKKSTLKDFLERLKV---------IMQKKYYRH-----"),("gi|42627877|ref|NP_958427.1| interleukin-4 precursor [Rattus norvegicus]","-MGLSPHLAVTLFCFLICTGNGIHG--------CN-DSPLREIINTL--NQVTEKGTPCTEMFVPDVLTATRNTTENELICRASRVLRKFYFPRDVPP-CLK-------NKSGVLGELRKLCRGVSGLNSLR-SCTVNESTLTTLKDFLESLKS---------ILRGKYLQSCTSMS"),("gi|58743333|ref|NP_001008993.1| interleukin-4 isoform delta2 [Pan troglodytes]","-MGLTSQLLPPLFFLLACAGNFVHG--------HKCDITLQEIIKTL--NSLTEQ----------------KNTTEKETFCRAATVLRQFYSHHEKDTRCLGATAQQFHRHKQLIRFLKRLDRNLWGLAGLN-SCPVKEANQSTLENFLERLKT---------IMREKYSKCSS---"),("gi|112807223|ref|NP_001036804.1| interleukin-4 precursor [Felis catus]","-MDLTSQLIPALVCLLAFTSTFVHG--------QNFNNTLKEIIKTL--NILTARNDSCMELTVMDVLAAPKNTSDKEIFCRATTVLRQIYTHHN----CST-------------KFLKGLDRNLSSMANR--TCSVNEVKKCTLKDFLERLKA---------IMQKKYSKH-----"),("2B8U:A|PDBID|CHAIN|SEQUENCE|HOMO SAPIENS","---------------------------------HKCDITLQEIIKTL--NSLTEQKTLCTELTVTDIFAASKNTTEKETFCRAATVLRQFYSHHEKDTRCLGATAQQFHRHKQLIRFLKRLDRNLWGLAGLN-SCPVKEANQSTLENFLERLKT---------IMREKYSKCSS---")]

@test mafft(joinpath(dirname(@__FILE__),"..","examples/fasta","il4.fasta"), :fftns) == mafft_fftns_expected

mafft_nwnsi_expected = Any[("gi|166158130|ref|NP_001107279.1| interleukin 4 [Xenopus (Silurana) tropicalis]","MSNLGRILCAVLGLFHLLSANPVPSSKLQIAIEEIISELVNNKITHK-----KCFVPTPYDDEEEASVEEISCRAFKSLKHV---------CASER-----------KNLRLLNASLITMFSEN-----VECSINNDEQKDLISVIEDLLTFFRAQMRKLVMNPKH"),("gi|55742622|ref|NP_999288.1| interleukin-4 precursor [Sus scrofa]","MG-LTSQLIPTLVCLLACTSNFVHGHKCDITLQEIIKTL--NILTARKNSCMELPVTDVFAAPENTTEKETFCRASTVLRHIYRHHT----CMK-------------SLLSGLDRNLSSMANM-------TCSVHEAKKSTLKDFLERLKTIMKEKYSKC------"),("gi|55741696|ref|NP_001007080.1| interleukin 4 [Gallus gallus]","MSSSLPTLLALLVLLAGPGAVPTLCLQLSVPLMESIRIV--NDIQGE-VSCVKMNVTDIFADNKTNNKTELLCKASTIVWESQH-------CH--------------KNLQGLFLNMRQLLNASSTSLKAPCPTAAGNTTSMEKFLADLRTFFHQLAKNK------"),("gi|50978886|ref|NP_001003159.1| interleukin-4 precursor [Canis lupus familiaris]","MG-LTSQLIPTLVCLLALTSTFVHGHNFNITIKEIIKML--NILTARNDSCMELTVKDVFTAPKNTSDKEIFCRAATVLRQIYTHN-----CSN-------------RYLRGLYRNLSSMANK-------TCSMNEIKKSTLKDFLERLKVIMQKKYYRH------"),("gi|42627877|ref|NP_958427.1| interleukin-4 precursor [Rattus norvegicus]","MG-LSPHLAVTLFCFLICTGNGIHGCN-DSPLREIINTL--NQVTEKGTPCTEMFVPDVLTATRNTTENELICRASRVLRKFYFPRDVPP-CLKNKSGVL-------GELRKLCRGVSGLNSLR------SCTVNESTLTTLKDFLESLKSILRGKYLQSCTSMS-"),("gi|58743333|ref|NP_001008993.1| interleukin-4 isoform delta2 [Pan troglodytes]","MG-LTSQLLPPLFFLLACAGNFVHGHKCDITLQEIIKTL--NSLTEQ----------------KNTTEKETFCRAATVLRQFYSHHEKDTRCLGATAQQFHRHKQLIRFLKRLDRNLWGLAGLN------SCPVKEANQSTLENFLERLKTIMREKYSKCSS----"),("gi|112807223|ref|NP_001036804.1| interleukin-4 precursor [Felis catus]","MD-LTSQLIPALVCLLAFTSTFVHGQNFNNTLKEIIKTL--NILTARNDSCMELTVMDVLAAPKNTSDKEIFCRATTVLRQIYTHHN----CST-------------KFLKGLDRNLSSMANR-------TCSVNEVKKCTLKDFLERLKAIMQKKYSKH------"),("2B8U:A|PDBID|CHAIN|SEQUENCE|HOMO SAPIENS","-------------------------HKCDITLQEIIKTL--NSLTEQKTLCTELTVTDIFAASKNTTEKETFCRAATVLRQFYSHHEKDTRCLGATAQQFHRHKQLIRFLKRLDRNLWGLAGLN------SCPVKEANQSTLENFLERLKTIMREKYSKCSS----")]

@test mafft(joinpath(dirname(@__FILE__),"..","examples/fasta","il4.fasta"), :nwnsi) == mafft_nwnsi_expected

mafft_nwns_expected = Any[("gi|166158130|ref|NP_001107279.1| interleukin 4 [Xenopus (Silurana) tropicalis]","MSNLGRILCAVLGLFHLLSANPVPS--------SKLQIAIEEIISELVNNKITHK-----KCFVPTPYDDEEEASVEEISCRAFKSLKHV---------CASER-----------KNLRLLNASLITMFSENVECSINNDEQKDLISVIEDLLTFFRAQMRKLVMNPKH--------"),("gi|55742622|ref|NP_999288.1| interleukin-4 precursor [Sus scrofa]","-MGLTSQLIPTLVCLLACTSNFVHG--------HKCDITLQEIIKTL--NILTARKNSCMELPVTDVFAAPENTTEKETFCRASTVLRHIYRHHT----CMK-------------SLLSGLDRNLSSMANM--TCSVHEAKKSTLKDFLERLKT---------IMKEKYSKC-----"),("gi|55741696|ref|NP_001007080.1| interleukin 4 [Gallus gallus]","---MSSSL-PTLLALLVL----LAGPGAVPTLCLQLSVPLMESIRIV--NDIQGE-VSCVKMNVTDIFADNKTNNKTELLCKASTIVWE--SQH-----CHK-------NLQGLFLNMRQL-LNASSTSLKA-PCPTAAGNTTSMEKFLADLRTFFH-----QLAKNK---------"),("gi|50978886|ref|NP_001003159.1| interleukin-4 precursor [Canis lupus familiaris]","-MGLTSQLIPTLVCLLALTSTFVHG--------HNFNITIKEIIKML--NILTARNDSCMELTVKDVFTAPKNTSDKEIFCRAATVLRQIYT-HN----CSN-------------RYLRGLYRNLSSMANK--TCSMNEIKKSTLKDFLERLKV---------IMQKKYYRH-----"),("gi|42627877|ref|NP_958427.1| interleukin-4 precursor [Rattus norvegicus]","-MGLSPHLAVTLFCFLICTGNGIHG--------CN-DSPLREIINTL--NQVTEKGTPCTEMFVPDVLTATRNTTENELICRASRVLRKFYFPRDVPP-CLK-------NKSGVLGELRKLCRGVSGLNSLR-SCTVNESTLTTLKDFLESLKS---------ILRGKYLQSCTSMS"),("gi|58743333|ref|NP_001008993.1| interleukin-4 isoform delta2 [Pan troglodytes]","-MGLTSQLLPPLFFLLACAGNFVHG--------HKCDITLQEIIKTL--NSLTEQ----------------KNTTEKETFCRAATVLRQFYSHHEKDTRCLGATAQQFHRHKQLIRFLKRLDRNLWGLAGLN-SCPVKEANQSTLENFLERLKT---------IMREKYSKCSS---"),("gi|112807223|ref|NP_001036804.1| interleukin-4 precursor [Felis catus]","-MDLTSQLIPALVCLLAFTSTFVHG--------QNFNNTLKEIIKTL--NILTARNDSCMELTVMDVLAAPKNTSDKEIFCRATTVLRQIYTHHN----CST-------------KFLKGLDRNLSSMANR--TCSVNEVKKCTLKDFLERLKA---------IMQKKYSKH-----"),("2B8U:A|PDBID|CHAIN|SEQUENCE|HOMO SAPIENS","---------------------------------HKCDITLQEIIKTL--NSLTEQKTLCTELTVTDIFAASKNTTEKETFCRAATVLRQFYSHHEKDTRCLGATAQQFHRHKQLIRFLKRLDRNLWGLAGLN-SCPVKEANQSTLENFLERLKT---------IMREKYSKCSS---")]

@test mafft(joinpath(dirname(@__FILE__),"..","examples/fasta","il4.fasta"), :nwns) == mafft_nwns_expected

@test alignment_length(mafft_expected_from_string) == 150

expected_amino_acids = Array{AminoAcid,1}[]
push!(expected_amino_acids, aminoacid("MSNLGRILCAVLGLFHLLSANPVPSSKLQIAIEEIISELVNNKITHKKCFVPTPYDDEEEASVEEISCRAFKSLKHVCASERKNLRLLNASLITMFSENVECSINNDEQKDLISVIEDLLTFFRAQMRKLVMNPKH"))

@test to_aminoacids([readfasta(joinpath(dirname(@__FILE__),"..","examples/fasta","il4.fasta"))[1]]) == expected_amino_acids

@test mafft_from_fasta(readfasta(joinpath(dirname(@__FILE__),"..","examples/fasta","il4.fasta"))) == mafft_expected

#expected_aligned_output = String["MSNLGRILCAVLGLFHLLSANPVPSSKLQIAIEEIISELVNNKITHKKCFVPTPYDDEEEASVEEISCRAFKSLKHVCASERKNLRLLNASLITMFSENVECSINNDEQKDLISVIEDLLTFFRAQMRKLVMNPKH","MGLTSQLIPTLVCLLACTSNFVHGHKCDITLQEIIKTLNILTARKNSCMELPVTDVFAAPENTTEKETFCRASTVLRHIYRHHTCMKSLLSGLDRNLSSMANMTCSVHEAKKSTLKDFLERLKTIMKEKYSKC","MSSSLPTLLALLVLLAGPGAVPTLCLQLSVPLMESIRIVNDIQGEVSCVKMNVTDIFADNKTNNKTELLCKASTIVWESQHCHKNLQGLFLNMRQLLNASSTSLKAPCPTAAGNTTSMEKFLADLRTFFHQLAKNK","MGLTSQLIPTLVCLLALTSTFVHGHNFNITIKEIIKMLNILTARNDSCMELTVKDVFTAPKNTSDKEIFCRAATVLRQIYTHNCSNRYLRGLYRNLSSMANKTCSMNEIKKSTLKDFLERLKVIMQKKYYRH","MGLSPHLAVTLFCFLICTGNGIHGCNDSPLREIINTLNQVTEKGTPCTEMFVPDVLTATRNTTENELICRASRVLRKFYFPRDVPPCLKNKSGVLGELRKLCRGVSGLNSLRSCTVNESTLTTLKDFLESLKSILRGKYLQSCTSMS","MGLTSQLLPPLFFLLACAGNFVHGHKCDITLQEIIKTLNSLTEQKNTTEKETFCRAATVLRQFYSHHEKDTRCLGATAQQFHRHKQLIRFLKRLDRNLWGLAGLNSCPVKEANQSTLENFLERLKTIMREKYSKCSS","MDLTSQLIPALVCLLAFTSTFVHGQNFNNTLKEIIKTLNILTARNDSCMELTVMDVLAAPKNTSDKEIFCRATTVLRQIYTHHNCSTKFLKGLDRNLSSMANRTCSVNEVKKCTLKDFLERLKAIMQKKYSKH","HKCDITLQEIIKTLNSLTEQKTLCTELTVTDIFAASKNTTEKETFCRAATVLRQFYSHHEKDTRCLGATAQQFHRHKQLIRFLKRLDRNLWGLAGLNSCPVKEANQSTLENFLERLKTIMREKYSKCSS"]

#aligned = readfasta(joinpath(dirname(@__FILE__),"..","examples/fasta","il4.fasta"))

#@test print_fasta(aligned) == expected_aligned_output

mafft_profile_expected = Any[("_seed_3UGM:A|PDBID|CHAIN|SEQUENCE","MASSHHHHHHSSGLVPRGSSGSSMAARPPRAKPAPRRRAAQPSDASPAAQVDLRTLGYSQQQQEKIKPKVRSTVAQHHEALVGHGFTHAHIVALSQHPAALGTVAVTYQHIITALPEATHEDIVGVGKQWSGARALEALLTDAGELRGPPLQLDTGQLVKIAKRGGVTAMEAVHASRNALTGA---PLNLTPAQVVAIASNNGGKQALETVQRLLPVLCQAHGLTPAQVVAIASHDGGKQALETMQRLLPVLCQAHGLPPDQVVAIASNIGGKQALETVQRLLPVLCQAHGLTPDQVVAIASHGGGKQALETVQRLLPVLCQAHGLTPDQVVAIASHDGGKQALETVQRLLPVLCQAHGLTPDQVVAIASNGGGKQALETVQRLLPVLCQAHGLTPDQVVAIASNGGKQALETVQRLLPVLCQAHGLTPDQVVAIASHDGGKQALETVQRLLPVLCQTHGLTPAQVVAIASHDGGKQALETVQQLLPVLCQAHGLTPDQVVAIASNIGGKQALATVQRLLPVLCQAHGLTPDQVVAIASNGGGKQALETVQRLLPVLCQAHGLTPDQVVAIASNGGGKQALETVQRLLPVLCQAHGLTQVQVVAIASNIGGKQALETVQRLLPVLCQAHGLTPAQVVAIASHDGGKQALETVQRLLPVLCQAHGLTPDQVVAIASNGGGKQALETVQRLLPVLCQAHGLTQEQVVAIASNNGGKQALETVQRLLPVLCQAHGLTPDQVVAIASNGGGKQALETVQRLLPVLCQAHGLTPAQVVAIASNIGGKQALETVQRLLPVLCQDHGLTLAQVVAIASNIGGKQALETVQRLLPVLCQAHGLTQDQVVAIASNIGGKQALETVQRLLPVLCQDHGLTPDQVVAIASNIGGKQALETVQRLLPVLCQDHGLTLDQVVAIASNGGKQALETVQRLLPVLCQDHGLTPDQVVAIASNSGGKQALETVQRLLPVLCQDHGLTPNQVVAIASNGGKQALESIVAQLSRPDPALAALTNDHLVALACLGGRPAMDAVKKGLPHAPELIRRVN-RRIGERTSHRV"),("_seed_3UGM:B|PDBID|CHAIN|SEQUENCE","T-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------AGATATGCATCTCCCCCTA--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------CTG---TACACCACCAAAAG-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------T"),("_seed_3UGM:C|PDBID|CHAIN|SEQUENCE","TTTT----------------------------------------------------------------------------------------------------------------------------------------------------------------GGT-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------GGTGTACAGTAGGGGGAGATGCATATCTAAC--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------"),("_seed_gi|166158130|ref|NP_001107279.1| interleukin 4 [Xenopus (Silurana) tropicalis]","MSNL------GRILCA----------------------------------------------------------------------VLGLFHLLSANPVPSSKLQIAIEEIISELV------------------------------------------------------------NNKITHK-----KCFVPTPYDDEEEASVEE------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ISCRA-----------------------FKSLKHVCASER----------------------------------------------------------------------------------------------------------------------KNLRLLNASLITMFSE----------------------------NVECSI-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------NNDEQKDLISVIEDLL-------------------------------------TFFRAQM-RKLVMNP--KH"),("_seed_gi|55742622|ref|NP_999288.1| interleukin-4 precursor [Sus scrofa]","M-GL------TSQLIP----------------------------------------------------------------------TLVCLLACTSNFVHGHKCDITLQEIIKTL--------------------------------------------------------------NILTARKNSCMELPVTDVFAAPENTTEKE------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------TFCRA-----------------------STVLRHIYRHHT-----------------------------CMK--------------------------------------------------------------------------------------SLLSGLDRNLSSMAN------------------------------MTCSV-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------HEAKKSTLKDFLERLK-------------------------------------TIMKEKY-SKC--------"),("_seed_gi|55741696|ref|NP_001007080.1| interleukin 4 [Gallus gallus]","MSSS------LPTLLA----------------------------------------------------------------------LLVLLAGPGAVPTLCLQLSVPLMESIRIV--------------------------------------------------------------NDIQGE-VSCVKMNVTDIFADNKTNNKTE------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------LLCKA-----------------------STI---VWESQH-----------------------------CH---------------------------------------------------------------------------------------KNLQGLFLNMRQLLNASSTS-----------------------LKAPCPT-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------AAGNTTSMEKFLADLR-------------------------------------TFFHQLAKNK---------"),("_seed_gi|50978886|ref|NP_001003159.1| interleukin-4 precursor [Canis lupus familiaris]","M-GL------TSQLIP----------------------------------------------------------------------TLVCLLALTSTFVHGHNFNITIKEIIKML--------------------------------------------------------------NILTARNDSCMELTVKDVFTAPKNTSDKE------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------IFCRA-----------------------ATVLRQIYTHN------------------------------CSN--------------------------------------------------------------------------------------RYLRGLYRNLSSMAN------------------------------KTCSM-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------NEIKKSTLKDFLERLK-------------------------------------VIMQKKY-YRH--------"),("_seed_gi|42627877|ref|NP_958427.1| interleukin-4 precursor [Rattus norvegicus]","M-GL------SPHLAV----------------------------------------------------------------------TLFCFLICTGNGIHGCN-DSPLREIINTL--------------------------------------------------------------NQVTEKGTPCTEMFVPDVLTATRNTTENE------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------LICRA-----------------------SRVLRKFYFPRDVPP--------------------------CLK--------------------------------------------------------------------------------NKSGVLGELRKLCRGVSGLNS-----------------------------LRSCTV-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------NESTLTTLKDFLESLK-------------------------------------SILRGKYLQSCTSM----S"),("_seed_gi|58743333|ref|NP_001008993.1| interleukin-4 isoform delta2 [Pan troglodytes]","M-GL------TSQLLP----------------------------------------------------------------------PLFFLLACAGNFVHGHKCDITLQEIIKTL--------------------------------------------------------------NSLTEQ----------------KNTTEKE------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------TFCRA-----------------------ATVLRQFYSHHEKDTR-------------------------CLG-------------------------------------------------------ATAQ-------QFH-----------RHKQLIRFLKRLDRNLWGLAG-----------------------------LNSCPV-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------KEANQSTLENFLERLK-------------------------------------TIMREKY-SKCSS------"),("_seed_gi|112807223|ref|NP_001036804.1| interleukin-4 precursor [Felis catus]","M-DL------TSQLIP----------------------------------------------------------------------ALVCLLAFTSTFVHGQNFNNTLKEIIKTL--------------------------------------------------------------NILTARNDSCMELTVMDVLAAPKNTSDKE------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------IFCRA-----------------------TTVLRQIYTHHN-----------------------------CST--------------------------------------------------------------------------------------KFLKGLDRNLSSMAN------------------------------RTCSV-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------NEVKKCTLKDFLERLK-------------------------------------AIMQKKY-SKH--------"),("_seed_2B8U:A|PDBID|CHAIN|SEQUENCE|HOMO SAPIENS","-----------------------------------------------------------------------------------------------------HKCDITLQEIIKTL--------------------------------------------------------------NSLTEQKTLCTELTVTDIFAASKNTTEKE------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------TFCRA-----------------------ATVLRQFYSHHEKDTR-------------------------CLG-------------------------------------------------------ATAQ-------QFH-----------RHKQLIRFLKRLDRNLWGLAG-----------------------------LNSCPV-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------KEANQSTLENFLERLK-------------------------------------TIMREKY-SKCSS------")]
@test mafft_profile(joinpath(dirname(@__FILE__),"..", "examples", "fasta", "3UGM.ali"),joinpath(dirname(@__FILE__),"..", "examples", "fasta", "il4.ali")) == mafft_profile_expected

group1 = readall(open(joinpath(dirname(@__FILE__),"..", "examples", "fasta", "3UGM.ali")))

group2 = readall(open(joinpath(dirname(@__FILE__),"..", "examples", "fasta", "il4.ali")))

@test mafft_profile_from_string(group1, group2) == mafft_profile_expected

group1 = readfasta(joinpath(dirname(@__FILE__),"..", "examples", "fasta", "3UGM.ali"))

group2 = readfasta(joinpath(dirname(@__FILE__),"..", "examples", "fasta", "il4.ali"))

@test mafft_profile_from_fasta(group1, group2) == mafft_profile_expected


text:
module TimerOutputs

import Base: show, time_ns
export TimerOutput, @timeit, @timeit_debug, reset_timer!, print_timer, timeit,
                    enable_timer!, disable_timer!, @notimeit

# https://github.com/JuliaLang/julia/pull/33717
if VERSION < v"1.4.0-DEV.475"
    gc_bytes() = Base.gc_bytes()
else
    function gc_bytes()
        b = Ref{Int64}(0)
        Base.gc_bytes(b)
        return b[]
    end
end

using Printf

include("TimerOutput.jl")
include("show.jl")
include("utilities.jl")

end # module


text:
module StarStuff
    using Reexport

    # external dependencies
    @reexport using Printf

    @reexport using Unitful
    @reexport using UnitfulAstro
    @reexport using UnitfulAtomic

    @reexport using LinearAlgebra
    @reexport using Random
    @reexport using Distributions
    @reexport using DifferentialEquations
    @reexport using MultiScaleArrays
    @reexport using GeometryBasics
    @reexport using IterTools
    @reexport using Measurements
    @reexport using CSV
    @reexport using Statistics
    @reexport using DataFrames
    @reexport using DataStructures

    @reexport using Makie
    @reexport using AbstractPlotting
    @reexport using AbstractPlotting.MakieLayout

    # @reexport using Interact
    # @reexport using Blink

    include("Particle.jl")
    include("Kinematics.jl")
    include("Generator.jl")
    include("PropUtils.jl")
    include("ParticleTree.jl")
    include("Bfield.jl")
    include("RelativisticIntegrator.jl")
    include("GUI.jl")

    # scripts
    # include("PointNshoot.jl")
end # StarStuff


text:
using MathOptInterface
const MOI = MathOptInterface
const MOIT = MOI.Test
const MOIU = MOI.Utilities
const MOIB = MOI.Bridges

juniper = DefaultTestSolver(log_levels=[:Table])

const optimizer = Juniper.Optimizer(juniper)

@testset "SolverName" begin
    @test MOI.get(optimizer, MOI.SolverName()) == "Juniper"
end

const config = MOIT.TestConfig(atol=1e-4, rtol=1e-4, optimal_status=MOI.LOCALLY_SOLVED)

@testset "Unit" begin
    bridged = MOIB.full_bridge_optimizer(optimizer, Float64)
    # A number of test cases are excluded because loadfromstring! works only
    # if the solver supports variable and constraint names.
    exclude = [
                "delete_nonnegative_variables", # delete and ConstraintFunction not supported
                "delete_soc_variables", # Soc and delete not supported
                "delete_variable", # Deleting not supported.
                "delete_variables", # Deleting not supported.
                "getvariable", # Variable names not supported.
                "solve_zero_one_with_bounds_1", # Variable names not supported.
                "solve_zero_one_with_bounds_2", # Variable names not supported.
                "solve_zero_one_with_bounds_3", # Variable names not supported.
                "getconstraint", # Constraint names not suported.
                "variablenames", # Variable names not supported.
                "solve_with_upperbound", # loadfromstring!
                "solve_with_lowerbound", # loadfromstring!
                "solve_integer_edge_cases", # loadfromstring!
                "solve_affine_lessthan", # loadfromstring!
                "solve_affine_greaterthan", # loadfromstring!
                "solve_affine_equalto", # loadfromstring!
                "solve_affine_interval", # loadfromstring!
                "get_objective_function", # Function getters not supported.
                "solve_constant_obj",  # loadfromstring!
                "solve_blank_obj", # loadfromstring!
                "solve_singlevariable_obj", # loadfromstring!
                "solve_objbound_edge_cases", # ObjectiveBound not supported.
                "solve_affine_deletion_edge_cases", # Deleting not supported.
                "solve_unbounded_model", # `NORM_LIMIT`
                "solve_duplicate_terms_obj", # duplicate terms objective
                "solve_duplicate_terms_vector_affine",
                "solve_duplicate_terms_scalar_affine",
                "solve_single_variable_dual_max", # no support for dual atm
                "solve_single_variable_dual_min", # no support for dual atm
                "solve_result_index", # no support for dual atm
                "update_dimension_nonnegative_variables", # currently no support for ConstraintFunction
               ]
    MOIT.unittest(bridged, config, exclude)
end


text:
#=
TODO: Each graph representation is assumed to be static... so
=#

"""
$(TYPEDEF)

Abstract supertype for generic directed graph structure.
"""
abstract type AbstractDirectedGraph end
abstract type AbstractDirectedAcyclicGraph <: AbstractDirectedGraph end

const AbstractDG = AbstractDirectedGraph
const AbstractDAG = AbstractDirectedAcyclicGraph

@enum Linearity LIN_CONSTANT LIN_LINEAR LIN_PIECEWISE_LINEAR LIN_NONLINEAR
@enum VariableType VT_BIN VT_INT VT_CONT

function _variable_count(g::AbstractDG)::Int
    error("Variable count not defined for graph type = $(typeof(g))")
end

# added id field from JuMP UserOperatorRegistry, expect more extensive changes in future.
struct OperatorRegistry
    multivariate_id::Vector{Symbol}
    multivariate_operator_to_id::Dict{Symbol,Int}
    multivariate_operator_evaluator::Vector{MOI.AbstractNLPEvaluator}
    univariate_operator_id::Vector{Symbol}
    univariate_operator_to_id::Dict{Symbol,Int}
    univariate_operator_f::Vector{Any}
    univariate_operator_fprime::Vector{Any}
    univariate_operator_fprimeprime::Vector{Any}
end
function OperatorRegistry()
    return OperatorRegistry(
        Symbol[],
        Dict{Symbol,Int}(),
        MOI.AbstractNLPEvaluator[],
        Symbol[],
        Dict{Symbol,Int}(),
        [],
        [],
        [],
    )
end

include(joinpath(@__DIR__, "expressions.jl"))
include(joinpath(@__DIR__, "node.jl"))
include(joinpath(@__DIR__, "utilities.jl"))
include(joinpath(@__DIR__, "graphs", "directed_tree.jl"))

max_stars_repo_name: MatthewStuber/EAGO

max_issues_repo_name: MatthewStuber/EAGO

max_forks_repo_name: MatthewStuber/EAGO


text:
"""
    linearshooting(F1,F2,a,b,alpha,beta,M)
berisi program untuk mencari solusi persamaan differensial
`x''=f(t,x,x')` dengan masalah nilai batas `x(a)=alpha` dan `x(b)=beta` pada interval `[a,b]`.
Program ini secara default berisi 5 masukan, yaitu fungsi `F1` dan `F2` (sistem persamaan
differensial hasil transformasi dari `x''`), titik ujung interval `[a,b]`, nilai batas `[alpha,beta]`, dan
jumlah sub-interval `M`.
# Example
```jl
julia> F1(t,z) = [ z[2], 2*t/(1+t^2)*z[2]-2/(1+t^2)*z[1]+1 ];

julia> F2(t,z) = [ z[2], 2*t/(1+t^2)*z[2]-2/(1+t^2)*z[1] ];

julia> solusi = linearshooting(F1,F2,0,4,1.25,-0.95,40)
41×2 Array{Float64,2}:
 0.0   1.25
 0.1   1.29112
 0.2   1.31735
 0.3   1.32899
 ⋮
 3.7  -1.03334
 3.8  -1.01809
 3.9  -0.990472
 4.0  -0.95
```
return solusi masalah nilai batas `sol`.
"""
function linearshooting(F1,F2,a,b,alpha,beta,M)
  M = Int(M)
  Za = [alpha,0];
  sol = rungekuttasistem(F1,a,b,Za,M);
  U = sol[:,2];

  Za = [0,1];
  sol = rungekuttasistem(F2,a,b,Za,M);
  V = sol[:,2];

  T = sol[:,1];
  X = U + (beta-U[M+1])*V/V[M+1];
  solusi = [T X];
end


text:
@testset "CIEDE2000" begin
    @info "test: CIEDE2000"
    dist = CIEDE2000()

    sz_img = (3,3)
    sz_img_3 = (3, 3, 3)
    m, n = 3, 5

    type_list = generate_test_types([Bool, Float32, N0f8], [Gray])
    A = [0 0 0; 1 1 1; 0 0 0]
    B = [1 1 1; 0 0 0; 1 1 1]
    for T in type_list
        @testset "$T" begin
            test_SemiMetric(dist, sz_img, T)
            test_ndarray(dist, sz_img_3, T)
            test_colwise(dist, n, sz_img, T)
            test_pairwise(dist, m, n, sz_img, T)

            a = A .|> T
            b = B .|> T
            test_numeric(dist, a, b, T; filename="references/CIEDE2000_2d_$(_base_colorant_type(T))")
            test_numeric(dist, channelview(a), channelview(b), T; filename="references/CIEDE2000_2d_$(_base_colorant_type(T))")
        end
    end
    test_cross_type(dist, A, B, type_list)

    type_list = generate_test_types([N0f8, Float32], [Lab, RGB])
    A = [RGB(0.0, 0.0, 0.0) RGB(0.0, 1.0, 0.0) RGB(0.0, 1.0, 1.0)
        RGB(0.0, 0.0, 1.0) RGB(1.0, 0.0, 0.0) RGB(1.0, 1.0, 0.0)
        RGB(1.0, 1.0, 1.0) RGB(1.0, 0.0, 1.0) RGB(0.0, 0.0, 0.0)]
    B = [RGB(0.0, 0.0, 0.0) RGB(0.0, 0.0, 1.0) RGB(1.0, 1.0, 1.0)
        RGB(0.0, 1.0, 0.0) RGB(1.0, 0.0, 0.0) RGB(1.0, 0.0, 1.0)
        RGB(0.0, 1.0, 1.0) RGB(1.0, 1.0, 0.0) RGB(0.0, 0.0, 0.0)]
    for T in type_list
        a = A .|> T
        b = B .|> T
        test_ndarray(dist, sz_img_3, T)
        test_numeric(dist, a, b, T; filename="references/CIEDE2000_2d_Color3")
    end
    test_cross_type(dist, A, B, type_list)
end


text:
using Test
using YaoBlocks.AD, YaoBlocks
using YaoArrayRegister
using Random

using SparseArrays, LuxurySparse, LinearAlgebra

@testset "mat rot/shift/phase" begin
    Random.seed!(5)
    for G in [X, Y, Z, ConstGate.SWAP, ConstGate.CZ, ConstGate.CNOT]
        @test test_mat_back(ComplexF64, rot(G, 0.0), 0.5; δ = 1e-5)
    end

    for G in [ShiftGate, PhaseGate]
        @test test_mat_back(ComplexF64, G(0.0), 0.5; δ = 1e-5)
    end

    G = time_evolve(put(3, 2 => X), 0.0)
    @test test_mat_back(ComplexF64, G, 0.5; δ = 1e-5)
end

@testset "mat put block, control block" begin
    Random.seed!(5)
    for use_outeradj in [false, true]
        # put block, diagonal
        @test test_mat_back(
            ComplexF64,
            put(3, 1 => chain(Rz(0.5), Ry(0.9), Rz(0.3))),
            [0.5, 0.9, 0.3];
            δ = 1e-5,
            use_outeradj = use_outeradj,
        )
        @test test_mat_back(
            ComplexF64,
            put(3, 1 => Rz(0.5)),
            0.5;
            δ = 1e-5,
            use_outeradj = use_outeradj,
        )
        @test test_mat_back(
            ComplexF64,
            control(3, (2, 3), 1 => Rz(0.5)),
            0.5;
            δ = 1e-5,
            use_outeradj = use_outeradj,
        )
        # dense matrix
        @test test_mat_back(
            ComplexF64,
            put(3, 1 => Rx(0.5)),
            0.5;
            δ = 1e-5,
            use_outeradj = use_outeradj,
        )
        @test test_mat_back(
            ComplexF64,
            control(3, (2, 3), 1 => Rx(0.5)),
            0.5;
            δ = 1e-5,
            use_outeradj = use_outeradj,
        )
        # sparse matrix csc
        @test test_mat_back(
            ComplexF64,
            put(3, (1, 2) => rot(SWAP, 0.5)),
            0.5;
            δ = 1e-5,
            use_outeradj = use_outeradj,
        )
        @test test_mat_back(
            ComplexF64,
            control(3, (3,), (1, 2) => rot(SWAP, 0.5)),
            0.5;
            δ = 1e-5,
            use_outeradj = use_outeradj,
        )
    end

    # is permatrix even possible?
    #@test test_mat_back(ComplexF64, put(3, 1=>matblock(pmrand(2))), [0.5, 0.6]; δ=1e-5)
    # ignore identity matrix.
end

@testset "mat concentrate" begin
    Random.seed!(5)
    @test test_mat_back(
        ComplexF64,
        concentrate(3, control(2, 2, 1 => shift(0.0)), (3, 1)),
        0.5;
        δ = 1e-5,
    )
end

@testset "mat chain" begin
    Random.seed!(5)
    @test test_mat_back(ComplexF64, chain(3, control(3, 2, 1 => shift(0.0))), 0.5; δ = 1e-5)
    @test test_mat_back(
        ComplexF64,
        chain(3, put(3, 2 => X), control(3, 2, 1 => shift(0.0))),
        0.5;
        δ = 1e-5,
    )
    @test test_mat_back(
        ComplexF64,
        chain(3, control(3, 2, 1 => shift(0.0)), put(3, 2 => X)),
        0.5;
        δ = 1e-5,
    )
    @test test_mat_back(
        ComplexF64,
        chain(3, control(3, 2, 1 => shift(0.0)), NoParams(put(3, 1 => Rx(0.0)))),
        0.5;
        δ = 1e-5,
    )
    @test test_mat_back(
        ComplexF64,
        chain(3, control(3, 2, 1 => shift(0.0)), chain(put(3, 1 => Rx(0.0)), put(3, 2 => Ry(0.0)))),
        [0.5, 0.5, 0.5];
        δ = 1e-5,
    )
    @test test_mat_back(
        ComplexF64,
        chain(3, chain(3, put(3, 1 => Rx(0.0)), put(3, 2 => Ry(0.0)))),
        [0.5, 0.5];
        δ = 1e-5,
    )
end

@testset "mat kron" begin
    use_outeradj = false
    @test test_mat_back(
        ComplexF64,
        kron(Rx(0.5), Rz(0.6)),
        [0.5, 0.5];
        δ = 1e-5,
        use_outeradj = use_outeradj,
    )
end


text:
module FunctionalResponse
  using Test
  using BioEnergeticFoodWebs

  foodchain = [0 1 0; 0 0 1; 0 0 0]
  omnivory = [0 1 1; 0 0 1; 0 0 0]
  init_biomass = [0.5, 0.3, 0.8]
  for a in [foodchain, omnivory]
    for i in [1.0, 2.0]
        for j in [0.0, 1.0]
            j = repeat([j], length(init_biomass))
            p = model_parameters(a, h = i, c = j)
            ω = a ./ sum(a, dims = 2)
            ω[isnan.(ω)] .= 0.0
            @test p[:w] == ω
            num = ω .* (init_biomass' .^ i)
            bm = zeros(eltype(init_biomass), (length(init_biomass), length(init_biomass)))
            fr = p[:functional_response]
            ar = p[:ar]
            ht = p[:ht]
            BioEnergeticFoodWebs.fill_bm_matrix!(bm, init_biomass, p[:w], p[:A], p[:h], fr, ar)
            @test num == bm
            hsd = [0.5, 0.5, 0.0] .^ i
            @test p[:Γh] == hsd
            ip = j .* hsd .* init_biomass
            fa = sum(num, dims = 2)
            den = hsd .+ ip .+ fa
            f_calc = num./den
            f_calc[isnan.(f_calc)] .= 0.0
            f = zeros(eltype(init_biomass), (length(init_biomass), length(init_biomass)))
            BioEnergeticFoodWebs.fill_F_matrix!(f, num, init_biomass, hsd, j, ht, fr)
            @test f == f_calc
            p = model_parameters(a, h = i, c = j, vertebrates = [true, false, false])
            x = [0.88, 0.3141, 0.138] #metabolic rates
            y = [4.0, 8.0, 0.0] #max. consumption efficiency
            eff = a == foodchain ? [0.0 0.85 0.0; 0.0 0.0 0.45; 0.0 0.0 0.0] : [0.0 0.85 0.45; 0.0 0.0 0.45; 0.0 0.0 0.0] #max. efficiency
            inflows = x .* y .* init_biomass .* f_calc
            outflows = inflows ./ eff
            outflows[isnan.(outflows)] .= 0.0
            xyb_model = zeros(eltype(init_biomass), length(init_biomass))
            BioEnergeticFoodWebs.fill_xyb_matrix!(xyb_model, init_biomass, p[:x], p[:y], p[:functional_response])
            @test xyb_model == x .* y .* init_biomass
            infl, outfl = BioEnergeticFoodWebs.consumption(p, init_biomass)
            @test infl == vec(sum(inflows, dims = 2))
            @test outfl == vec(sum(outflows, dims = 1))
          end
      end
  end

end

module ClassicalFR
    using BioEnergeticFoodWebs
    using Test

    foodchain = [0 1 0; 0 0 1; 0 0 0]
    omnivory = [0 1 1; 0 0 1; 0 0 0]
    init_biomass = [0.5, 0.3, 0.8]
    for a in [foodchain, omnivory]
      for i in [1.0, 2.0]
          for j in [0.0, 1.0]
              #atype = a == foodchain ? "foodchain" : "omnivory"
              #println("$atype - $i - $j")
              j = repeat([j], length(init_biomass))
              p = model_parameters(a, h = i, c = j, functional_response = :classical)
              fr = p[:functional_response]
              ar = p[:ar] .* a
              ht = p[:ht] .* a
              ht[isnan.(ht)] .= 0.0
              p[:ar] = ar
              p[:ht] = ht
              num = zeros(eltype(init_biomass), (length(init_biomass), length(init_biomass)))
              for l in 1:size(a,1), m in 1:size(a,1)
                num[l,m] = ar[l,m] .* (init_biomass[m] ^ i) * a[l,m]
              end
              bm = zeros(eltype(init_biomass), (length(init_biomass), length(init_biomass)))
              BioEnergeticFoodWebs.fill_bm_matrix!(bm, init_biomass, p[:w], p[:A], p[:h], fr, ar)
              @test num == bm
              fa = zeros(eltype(init_biomass), (length(init_biomass), length(init_biomass)))
              for l in 1:size(a,1), m in 1:size(a,1)
                fa[l,m] = num[l,m] * ht[l,m]
              end
              fa = sum(fa, dims = 2)
              den = zeros(eltype(init_biomass), length(init_biomass))
              for l in 1:size(a,1)
                den[l] = 1 + j[l] + fa[l]
              end
              f_calc = num./den
              f_calc[isnan.(f_calc)] .= 0.0
              f = zeros(eltype(init_biomass), (length(init_biomass), length(init_biomass)))
              hsd = [0.5, 0.5, 0.0] .^ i
              BioEnergeticFoodWebs.fill_F_matrix!(f, num, init_biomass, hsd, j, ht, fr)
              @test f == f_calc
              eff = a == foodchain ? [0.0 0.85 0.0; 0.0 0.0 0.45; 0.0 0.0 0.0] : [0.0 0.85 0.45; 0.0 0.0 0.45; 0.0 0.0 0.0] #max. efficiency
              inflows = init_biomass .* f_calc .* eff
              outflows = init_biomass .* f_calc
              xyb_model = zeros(eltype(init_biomass), length(init_biomass))
              BioEnergeticFoodWebs.fill_xyb_matrix!(xyb_model, init_biomass, p[:x], p[:y], p[:functional_response])
              @test xyb_model == init_biomass
              infl, outfl = BioEnergeticFoodWebs.consumption(p, init_biomass)
              @test infl == vec(sum(inflows, dims = 2))
              @test outfl == vec(sum(outflows, dims = 1))
            end
        end
    end

end


text:
using Test
using Logging
# using Revise
using LarSurf
# Logging.configure(level==Logging.Debug)

# include("../src/LarSurf.jl")
# include("../src/block.jl")

@testset "Block basic function Tests" begin
    data3d = LarSurf.random_image([7, 7, 7], [1,2,2], [3, 4, 5], 2)
    @test maximum(data3d) > 2
    @test minimum(data3d) < 1
end

@testset "Tetris" begin
    segmentation = LarSurf.tetris_brick()
    @test minimum(segmentation) == 0
    @test maximum(segmentation) == 1
end

@testset "data234" begin
    segmentation = LarSurf.data234()
    @test minimum(segmentation) == 0
    @test maximum(segmentation) == 1
end

@testset "half sphere generation" begin
    segmentation = LarSurf.generate_truncated_sphere(10, [20,20,20])
    @test minimum(segmentation) == 0
    @test maximum(segmentation) == 1

    segmentation = LarSurf.generate_truncated_sphere(10)
    @test minimum(segmentation) == 0
    @test maximum(segmentation) == 1
end


text:
module sys
	using System
	using System.CBinding

	export @sys, @c_cmd, @c_str, @pkgconf, @pkgconf_cmd

	macro pkgconf(exprs...) return pkgconf(__module__, __source__, exprs...) end

	function pkgconf(mod::Module, loc::LineNumberNode, expr::Expr)
		exprs = Base.is_expr(expr, :block) ? expr.args : [expr]

		deps    = []
		usings  = []
		cmds    = []
		strs    = []
		extras  = []
		for expr in exprs
			# TODO: handle predicated statements

			if Base.is_expr(expr, :using)
				for e in expr.args
					if Base.is_expr(e, :(:)) && length(e.args) >= 1
						e = e.args[1]
					end

					ind = 1
					while e.args[ind] == :.
						ind += 1
					end

					dep = nothing
					for ind in ind:length(e.args)
						dep = isnothing(dep) ? e.args[ind] : :($(dep).$(e.args[ind]))
						push!(usings, Expr(:import, Expr(:., e.args[1:ind]...)))
					end
					push!(deps, dep)
				end
				push!(usings, expr)
			elseif Base.is_expr(expr, :macrocall) && expr.args[1] == Symbol("@c_cmd")
				push!(cmds, expr)
			elseif Base.is_expr(expr, :macrocall) && expr.args[1] == Symbol("@pkgconf_cmd")
				push!(cmds, @eval @macroexpand1 $(expr))
			elseif Base.is_expr(expr, :macrocall) && expr.args[1] == Symbol("@c_str")
				push!(strs, expr)
			else
				push!(extras, esc(expr))
			end
		end

		flags = map(cmds) do cmd
			expr = :(``)
			expr.args[3] = cmd.args[3]
			return :($(esc(expr)).exec...)
		end

		prereqs = []
		ctx = :(``)
		ctx.args[1] = :($(CBinding).var"@c_cmd")
		for dep in deps
			push!(prereqs, :($(Expr(:$, :($(esc(dep))._DEFS...)))))
			ctx.args[3] *= " \$($(dep)._FLAGS)"
		end
		ctx.args[3] *= " \$(_FLAGS)"

		defs = map(strs) do str
			str = copy(str)
			length(str.args) < 4 && push!(str.args, "")
			str.args[4] = "s"
			return QuoteNode(str)
		end

		deps = map(esc, deps)

		return quote
			$(usings...)
			$(extras...)

			const $(esc(:_FLAGS)) = ($(flags...),)
			$(esc(ctx))

			@eval begin
				$(prereqs...)
				$(strs...)
			end
			const $(esc(:_DEFS))  = ($(defs...),)
		end
	end

	macro pkgconf_cmd(exprs...) return pkgconf_cmd(__module__, __source__, exprs...) end

	function pkgconf_cmd(mod::Module, loc::LineNumberNode, str::String, opts::String = "")
		opt = []
		'f' in opts && push!(opt, "--cflags")
		'l' in opts && push!(opt, "--libs")

		# TODO: handle spaces in paths, etc...
		flags = String(read(`pkg-config $(opt) $(str)`))

		expr = :(``)
		expr.args[1] = :($(CBinding).var"@c_cmd")
		expr.args[3] = flags
		return esc(expr)
	end
end


text:
sstr = ScanningStrategy(spinsunang_rad = 0.0,
    borespinang_rad = 0.0,
    spin_rpm = 0.0,
    prec_rpm = 0.0,
    hwp_rpm = 0.0)

dirs = genpointings(sstr, 0.:3600.:86400., Float64[0, 0, 1], 0.0)

# Check the colatitudes
for idx in 1:size(dirs, 1)
    # Check that we're on the Ecliptic plane (colatitude = 90°)
    @test dirs[idx, 1] ≈ π / 2

    # Check that the polarization angle is always the same
    @test dirs[idx, 3] ≈ -π / 2
end

# Check that the longitude increases as expected
@test dirs[end, 2] - dirs[1, 2] ≈ 2π / DAYS_PER_YEAR

#######################################################################

sstr = ScanningStrategy(spinsunang_rad = 0.0,
    borespinang_rad = 0.0,
    spin_rpm = 1.0,
    prec_rpm = 0.0,
    hwp_rpm = 1.0)

dirs = genpointings(sstr, 0.:0.1:120., Float64[0, 0, 1], 0.0)

@test maximum(dirs[:, 3]) ≈ π / 2
@test minimum(dirs[:, 3]) ≈ -π / 2

#######################################################################

sstr = ScanningStrategy(spinsunang_rad = 0.0,
    borespinang_rad = deg2rad(15.),
    spin_rpm = 1.0,
    prec_rpm = 0.0,
    hwp_rpm = 1.0,
    yearly_rpm = 0.0)

dirs = genpointings(sstr, 0.:1.:60., Float64[0, 0, 1], 0.0)

# Colatitudes should depart no more than ±15° from the Ecliptic
@test rad2deg(minimum(dirs[:, 1])) ≈ 90 - 15
@test rad2deg(maximum(dirs[:, 1])) ≈ 90 + 15

@test dirs[1, 2] ≈ 0.0
@test rad2deg(dirs[end, 2]) ≈ 360.0

#######################################################################

sstr = ScanningStrategy(spinsunang_rad = deg2rad(15.),
    borespinang_rad = 0.0,
    spin_rpm = 1.0,
    prec_rpm = 0.0,
    hwp_rpm = 1.0,
    yearly_rpm = 0.0)

dirs = genpointings(sstr, 0.:1.:60., Float64[0, 0, 1], 0.0)

for idx in 1:size(dirs, 1)
    @test rad2deg(dirs[idx, 1]) ≈ 90 - 15
end


text:
##### write model outputs
function write_output!(writer::Union{PlanktonOutputWriter, Nothing}, model::PlanktonModel, diags::PlanktonDiagnostics, ΔT)
    if isa(writer, Nothing)
        return nothing
    else
        if writer.write_log
            write_species_dynamics(model.t, model.individuals.phytos,
                                   writer.filepath, model.mode)
        end

        if writer.save_diags
            if model.t % (diags.time_interval) == 0.0
                if filesize(writer.diags_file) ≥ writer.max_filesize
                    start_next_diags_file(writer)
                end
                write_diags_to_jld2(diags, writer.diags_file, model.t, model.iteration,
                                    diags.time_interval/ΔT, model.grid)
            end
        end

        if writer.save_plankton
            if model.t % (writer.plankton_time_interval) == 0.0
                if filesize(writer.plankton_file) ≥ writer.max_filesize
                    start_next_plankton_file(writer)
                end
                write_individuals_to_jld2(model.individuals.phytos, writer.plankton_file, model.t,
                                          model.iteration, writer.plankton_include)
            end
        end
    end
end

function start_next_diags_file(writer::PlanktonOutputWriter)
    if writer.part_diags == 1
        part1_path = replace(writer.diags_file, r".jld2$" => "_part1.jld2")
        mv(writer.diags_file, part1_path, force=true)
        writer.diags_file = part1_path
    end

    writer.part_diags += 1
    writer.diags_file = replace(writer.diags_file, r"part\d+.jld2$" => "part" * string(writer.part_diags) * ".jld2")
end

function start_next_plankton_file(writer::PlanktonOutputWriter)
    if writer.part_plankton == 1
        part1_path = replace(writer.plankton_file, r".jld2$" => "_part1.jld2")
        mv(writer.plankton_file, part1_path, force=true)
        writer.plankton_file = part1_path
    end

    writer.part_plankton += 1
    writer.plankton_file = replace(writer.plankton_file, r"part\d+.jld2$" => "part" * string(writer.part_plankton) * ".jld2")
end

##### write a brief summary of each species at each time step into a txt file
function write_species_dynamics(t::Int64, phytos, filepath, mode::MacroMolecularMode)
    for i in 1:length(phytos)
        file = joinpath(filepath, "dynamic_species"*lpad(i,3,"0")*".txt")
        pop = dot(phytos[i].data.ac, phytos[i].data.ac)
        gen_ave =  dot(phytos[i].data.gen, phytos[i].data.ac) / pop
        age_ave =  dot(phytos[i].data.age, phytos[i].data.ac) / pop
        PRO_ave =  dot(phytos[i].data.PRO, phytos[i].data.ac) / pop
        DNA_ave =  dot(phytos[i].data.DNA, phytos[i].data.ac) / pop
        RNA_ave =  dot(phytos[i].data.RNA, phytos[i].data.ac) / pop
        CH_ave  =  dot(phytos[i].data.CH,  phytos[i].data.ac) / pop
        NST_ave =  dot(phytos[i].data.NST, phytos[i].data.ac) / pop
        PST_ave =  dot(phytos[i].data.PST, phytos[i].data.ac) / pop
        Chl_ave =  dot(phytos[i].data.Chl, phytos[i].data.ac) / pop
        day = t÷86400
        hour = t%86400/3600
        io = open(file,"a");
        println(io,@sprintf("%3.0f  %2.2f  %6.0f  %1.2f  %1.2f  %.8E  %.8E  %.8E  %.8E  %.8E  %.8E  %.8E",
                            day,hour,pop,gen_ave,age_ave,PRO_ave,DNA_ave,RNA_ave,CH_ave,NST_ave,PST_ave,Chl_ave))
        close(io);
    end
end
function write_species_dynamics(t::Int64, phytos, filepath, mode::QuotaMode)
    for i in 1:length(phytos)
        file = joinpath(filepath, "dynamic_species"*lpad(i,3,"0")*".txt")
        pop = dot(phytos[i].data.ac, phytos[i].data.ac)
        gen_ave =  dot(phytos[i].data.gen, phytos[i].data.ac) / pop
        age_ave =  dot(phytos[i].data.age, phytos[i].data.ac) / pop
        size_ave=  dot(phytos[i].data.Sz,  phytos[i].data.ac) / pop
        Bm_ave  =  dot(phytos[i].data.Bm,  phytos[i].data.ac) / pop
        Cq_ave  =  dot(phytos[i].data.Cq,  phytos[i].data.ac) / pop
        Nq_ave  =  dot(phytos[i].data.Nq,  phytos[i].data.ac) / pop
        Pq_ave  =  dot(phytos[i].data.Pq,  phytos[i].data.ac) / pop
        Chl_ave =  dot(phytos[i].data.Chl, phytos[i].data.ac) / pop
        day = t÷86400
        hour = t%86400/3600
        io = open(file,"a");
        println(io,@sprintf("%3.0f  %2.2f  %6.0f  %1.2f  %1.2f  %1.2f  %.8E  %.8E  %.8E  %.8E  %.8E",
                            day,hour,pop,gen_ave,age_ave,size_ave,Bm_ave,Cq_ave,Nq_ave,Pq_ave,Chl_ave))
        close(io);
    end
end
function write_species_dynamics(t::Int64, phytos, filepath, mode::CarbonMode)
    for i in 1:length(phytos)
        file = joinpath(filepath, "dynamic_species"*lpad(i,3,"0")*".txt")
        pop = dot(phytos[i].data.ac, phytos[i].data.ac)
        gen_ave =  dot(phytos[i].data.gen, phytos[i].data.ac) / pop
        age_ave =  dot(phytos[i].data.age, phytos[i].data.ac) / pop
        size_ave=  dot(phytos[i].data.Sz,  phytos[i].data.ac) / pop
        Bm_ave  =  dot(phytos[i].data.Bm,  phytos[i].data.ac) / pop
        day = t÷86400
        hour = t%86400/3600
        io = open(file,"a");
        println(io,@sprintf("%3.0f  %2.2f  %6.0f  %1.2f  %1.2f  %1.2f  %.8E",
                            day,hour,pop,gen_ave,age_ave,size_ave,Bm_ave))
        close(io);
    end
end

function write_individuals_to_jld2(phytos::NamedTuple, filepath, t, iter, atts)
    jldopen(filepath, "a+") do file
        file["timeseries/t/$iter"] = t
        for sp in keys(phytos)
            spi = NamedTuple{atts}([getproperty(phytos[sp].data, att) for att in atts])
            for att in atts
                file["timeseries/$sp/$att/$iter"] = Array(spi[att])
            end
        end
    end
end

function write_diags_to_jld2(diags, filepath, t, iter, ncounts, grid)
    jldopen(filepath, "a+") do file
        file["timeseries/t/$iter"] = t
        for key in keys(diags.tracer)
            file["timeseries/$key/$iter"] = Array(interior(diags.tracer[key], grid)) ./ ncounts
        end
        for sp in keys(diags.plankton)
            for proc in keys(diags.plankton[sp])
                file["timeseries/$sp/$proc/$iter"] = Array(interior(diags.plankton[sp][proc],grid)) ./ ncounts
            end
        end
    end
    ##### zeros diags
    for tr in diags.tracer
        tr .= 0.0
    end
    for sp in diags.plankton
        for proc in sp
            proc .= 0.0
        end
    end
end


text:
using Test
using ForestBiometrics

@test limiting_distance(10,12.4,34.0) == "The tree is in"


text:
using DelimitedFiles

content = readdlm("input.txt", ' ')

mutable struct MyPoint
    x::Int
    y::Int
end

p = MyPoint(0, 0)

function modifyPoint(instruction)
    command, value = instruction
    if command == "forward"
        p.x += value
    elseif command == "down"
        p.y += value
    else
        p.y -= value
    end
end

for i in 1:length(content[:, 1])
    modifyPoint(content[i, :])
end

p.x * p.y

max_stars_repo_path: Day 2/part1.jl

max_issues_repo_path: Day 2/part1.jl

max_forks_repo_path: Day 2/part1.jl


text:
# using Compat

type MongoClient
    uri::AbstractString
    _wrap_::Ptr{Void}

    MongoClient(uri::AbstractString) = begin
        uriCStr = String(uri)
        client = new(
            uri,
            ccall(
                (:mongoc_client_new, libmongoc),
                Ptr{Void}, (Ptr{UInt8}, ),
                uriCStr
                )
            )
        finalizer(client, destroy)
        return client
    end

MongoClient(host::AbstractString, port::Int) = MongoClient("mongodb://$host:$port/")
MongoClient(host::AbstractString, port::Int, user::AbstractString, password::AbstractString) = MongoClient("mongodb://$user:$password@$host:$port/")
MongoClient(host::AbstractString, user::AbstractString, password::AbstractString) = MongoClient("mongodb://$user:$password@$host/")
MongoClient(host::AbstractString, user::AbstractString, password::AbstractString, db::AbstractString) = MongoClient("mongodb://$user:$password@$host/$db")
    MongoClient() = MongoClient("localhost", 27017)
end
export MongoClient

show(io::IO, client::MongoClient) = print(io, "MongoClient($(client.uri))")
export show

"""
Issues a command to MongoDB client through `mongoc_client_command_simple`.

Possible commands: https://docs.mongodb.org/manual/reference/command/
"""
command_simple(
    client::MongoClient, # mongoc_client_t
    db_name::AbstractString, # const char
    command::BSONObject#, # const bson_t
    ) = begin
    dbCStr = String(db_name)
    reply = BSONObject() # bson_t
    bsonError = BSONError() # bson_error_t
    ccall(
        (:mongoc_client_command_simple, libmongoc),
        Bool, (Ptr{Void}, Ptr{UInt8}, Ptr{Void}, Ptr{Void}, Ptr{Void}, Ptr{UInt8}),
        client._wrap_,
        dbCStr,
        command._wrap_,
        C_NULL,
        reply._wrap_,
        bsonError._wrap_
        ) || error("update: $(string(bsonError))")
    return reply
end
command_simple(
    client::MongoClient,
    db_name::AbstractString,
    command::Associative
    ) = command_simple(
        client,
        db_name,
        BSONObject(command)
        )
command_simple(
    client::MongoClient,
    db_name::AbstractString,
    command::NakedDict
    ) = command_simple(
        client,
        db_name,
        BSONObject(command)
        )
export command_simple

# Private

destroy(client::MongoClient) =
    ccall(
        (:mongoc_client_destroy, libmongoc),
        Void, (Ptr{Void},),
        client._wrap_
        )


text:
module MLJModels

import MLJModelInterface
import MLJModelInterface: Model, metadata_pkg, metadata_model, @mlj_model, info,
    nrows, selectcols, transform, inverse_transform, fitted_params
for T in MLJModelInterface.ABSTRACT_MODEL_SUBTYPES
    @eval(import MLJModelInterface.$T)
end
for T in MLJModelInterface.MODEL_TRAITS
    @eval(import MLJModelInterface.$T)
end

using ScientificTypes

const MMI = MLJModelInterface

using Pkg, Pkg.TOML, OrderedCollections, Parameters
using Tables, CategoricalArrays, StatsBase, Statistics, Dates
using InteractiveUtils
import Distributions
import REPL # stdlib, needed for `Term`
import PrettyPrinting
import CategoricalDistributions: UnivariateFinite, UnivariateFiniteArray,
    classes
import StatisticalTraits # for `info`

# from loading.jl:
export load, @load, @iload, @loadcode

# from model_search:
export models, localmodels, matching

# extended in model_search.jl:
export info

# from model/Constant
export ConstantRegressor, ConstantClassifier,
        DeterministicConstantRegressor, DeterministicConstantClassifier

# from model/ThresholdPredictors
export BinaryThresholdPredictor

# from model/Transformers
export FeatureSelector, StaticTransformer, UnivariateDiscretizer,
    UnivariateStandardizer, Standardizer, UnivariateBoxCoxTransformer,
    OneHotEncoder, ContinuousEncoder, FillImputer, UnivariateFillImputer,
    UnivariateTimeTypeToContinuous

const srcdir = dirname(@__FILE__) # the directory containing this file
const MMI = MLJModelInterface

if VERSION < v"1.3"
    const nonmissingtype = ScientificTypes.ScientificTypesBase.nonmissing
end

nonmissing = nonmissingtype

include("utilities.jl")

Handle = NamedTuple{(:name, :pkg), Tuple{String,String}}
(::Type{Handle})(name,string) = NamedTuple{(:name, :pkg)}((name, string))

# load utilities for reading model metadata from file:
include("metadata.jl")

# read in the metadata:
metadata_file = joinpath(srcdir, "registry", "Metadata.toml")
const INFO_GIVEN_HANDLE = info_given_handle(metadata_file)
const PKGS_GIVEN_NAME = pkgs_given_name(INFO_GIVEN_HANDLE)
const AMBIGUOUS_NAMES = ambiguous_names(INFO_GIVEN_HANDLE)
const NAMES = model_names(INFO_GIVEN_HANDLE)
const MODEL_TRAITS_IN_REGISTRY = model_traits_in_registry(INFO_GIVEN_HANDLE)

# model search and registry code:
include("model_search.jl")
include("loading.jl")
include("registry/src/info_dict.jl")
include("registry/src/Registry.jl")
include("registry/src/check_registry.jl")
import .Registry.@update

# load built-in models:
include("builtins/Constant.jl")
include("builtins/Transformers.jl")
include("builtins/ThresholdPredictors.jl")

end # module


text:
using Lazy, JSON, MacroTools

hascommand(c) =
  try readstring(`which $c`); true catch e false end

spawn_rdr(cmd) = spawn(cmd, Base.spawn_opts_inherit()...)

resolve(pkg, path...) =
  joinpath(Base.find_in_path(pkg, nothing), "..","..", path...) |> normpath

# node-inspector

_inspector = nothing

function inspector()
  if hascommand("node-inspector")
    global _inspector
    _inspector != nothing && process_running(_inspector) && return _inspector
    _inspector = spawn_rdr(`node-inspector`)
  end
end

function inspector(port)
  inspector()
  run(`open http://localhost:8080/debug?port=$port`)
end

# atom-shell

import Base: Process, TCPSocket

export Electron

type Electron <: Shell
  proc::Process
  sock::TCPSocket
  handlers::Dict{String, Any}
end

Electron(proc, sock) = Electron(proc, sock, Dict())

@static if is_apple()
  const _electron = resolve("Blink", "deps/Julia.app/Contents/MacOS/Electron")
elseif is_linux()
  const _electron = resolve("Blink", "deps/atom/electron")
elseif is_windows()
  const _electron = resolve("Blink", "deps", "atom", "electron.exe")
end
const mainjs = resolve("Blink", "src", "AtomShell", "main.js")

function electron()
  path = get(ENV, "ELECTRON_PATH", _electron)
  isfile(path) || error("Cannot find Electron. Try `AtomShell.install()`.")
  return path
end

port() = rand(2_000:10_000)

function try_connect(args...; interval = 0.01, attempts = 300)
  for i = 1:attempts
    try
      return connect(args...)
    catch e
      i == attempts && rethrow()
    end
    sleep(interval)
  end
end

function init(; debug = false)
  electron() # Check path exists
  p, dp = port(), port()
  debug && inspector(dp)
  dbg = debug ? "--debug=$dp" : []
  proc = (debug ? spawn_rdr : spawn)(`$(electron()) $dbg $mainjs port $p`)
  conn = try_connect(ip"127.0.0.1", p)
  shell = Electron(proc, conn)
  initcbs(shell)
  return shell
end

# JS Communication

import ..Blink: msg, enable_callbacks!, handlers, handle_message, active

msg(shell::Electron, m) = (JSON.print(shell.sock, m); println(shell.sock))

handlers(shell::Electron) = shell.handlers

function initcbs(shell)
  enable_callbacks!(shell)
  @schedule begin
    while active(shell)
      @errs handle_message(shell, JSON.parse(shell.sock))
    end
  end
end

# utils

import Base: quit

export active

active(shell::Electron) = process_running(shell.proc)

quit(shell::Electron) = close(shell.sock)

# Default process

function shell(; debug = false)
  global _shell
  _shell ≠ nothing && active(_shell) && return _shell
  _shell = init(debug = debug)
end


text:
"""
    Address

The ip address and type (ipv4 or ipv6) or MAC Address
Vendor details may require nmap to be executed as a privileged user
"""
Base.@kwdef mutable struct Address <:Leaf
    addr::String        = ""
    addrtype::String    = ""
    vendor::String      = ""
end

"""
    Distance

Number of hops to an host
"""
Base.@kwdef mutable struct Distance <:Leaf
    value::String   = ""
end

"""
    Uptime

The amount of time the host has been up
"""
Base.@kwdef mutable struct Uptime <:Leaf
    seconds::Int     = 0
    lastboot::String = ""
end

"""
    Times

Wraps the `times` xml element
"""
Base.@kwdef mutable struct Times <:Leaf
    srtt::String    = ""
    rtt::String     = ""
    to::String      = ""
end
StructTypes.names(::Type{Times}) = ((:rtt, :rttvar),)

"""
    Smurf

Responses from smurf attacks
"""
Base.@kwdef mutable struct Smurf <:Marsh
    responses::String  = ""
end

"""
    Hop

Represents a hop in a traceroute
"""
Base.@kwdef mutable struct Hop <:Leaf
    ttl::Float64    = 0.0
	rtt::String     = ""
	ipaddr::String  = ""
	host::String    = ""
end

"""
    Trace

Representes the trace element in nmap scans
"""
Base.@kwdef mutable struct Trace <:Marsh
    proto::String       = ""
    port::Int           = 0
    hops::Vector{Hop}   = Vector{Hop}()
end
StructTypes.names(::Type{Trace}) = ((:hops, :hop),)

"""
    HostStatus

An host's state, e.g. "up" with respective `reason`
"""
Base.@kwdef mutable struct HostStatus <:Leaf
    state::String       = ""
    reason::String      = ""
    reason_ttl::String  = ""
end
Base.string(status::HostStatus) = status.state

"""
    Hostname

Host characterization
"""
Base.@kwdef mutable struct Hostname <:Leaf
    name::String    = ""
    type::String    = ""
end
name(host::Hostname) = host.name
type(host::Hostname) = host.type
Base.string(hname::Hostname) = name(hname)

# Tackle some inconsistency on how <hostnames> <hostname> </hostname> ... </hostnames> is provided
function StructTypes.construct(::Type{Vector{T}}, xml::XMLDict.XMLDictElement) where T<:Hostname
    xml = Dict(xml)
    if haskey(xml, "hostname") xml = xml["hostname"] end
    if !(xml isa Vector) xml = [xml] end
    return [StructTypes.construct(T, hname) for hname in xml]
end

#===================================
    Sequences
===================================#
abstract type AbstractSequence <: Marsh end

"""
    Sequence
"""
Base.@kwdef mutable struct Sequence <:Leaf
    class::String   = ""
    values::String  = ""
end

"""
    TCPSequence
"""
Base.@kwdef mutable struct TCPSequence <:Leaf
    index::String       = ""
    difficulty::String  = ""
    values::String      = ""
end
#= END Sequences =#

"""
    Host

Representation of a scanned host

https://nmap.org/book/nmap-dtd.html
"""
Base.@kwdef mutable struct Host <: Marsh
    comment::String                 = ""
    distance::Distance              = Distance()
    endtime::Timestamp              = Timestamp()
    ipidsequence::Sequence          = Sequence()
    os::OS                          = OS()
    starttime::Timestamp            = Timestamp()
    status::HostStatus              = HostStatus()

    tcpsequence::TCPSequence        = TCPSequence()
    tcptssequence::Sequence         = Sequence()

    times::Times                    = Times()
    trace::Trace                    = Trace()
    uptime::Uptime                  = Uptime()

    addresses::Vector{Address}      = Vector{Address}()
    hostnames::Vector{Hostname}     = Vector{Hostname}()
    hostscripts::Vector{Script}     = Vector{Script}()
    ports::Vector{Ports}            = Vector{Ports}()
    smurfs::Vector{Smurf}           = Vector{Smurf}()
end
StructTypes.names(::Type{Host}) = (
    (:addresses,    :address),
    (:extraports,   :extraport),
    (:hostnames,    :hostname),
    (:ports,        :port),
    (:hostscripts,  :hostscript),
    (:smurfs,       :smurf))

address(host::Host)     = host.address
scripts(host::Host)     = host.hostscripts
hostnames(host::Host)   = host.hostnames
os(host::Host)          = host.os
ports(host::Host)       = host.ports
status(host::Host)      = host.status


text:
using intrico
using egads

mesh   = divido.Mesh3D( "cube", 1, N = 4)
meshf  = MeshF( mesh )

lat = Lattice( 1.0, fill( 0.005, size(meshf.e,1) ), fill( 0.0, size(meshf.e,1) ) )

genCAD( meshf, lat, "test2.stp", eps = 0.0, Δeps = 0.5e-2 )


text:
# order 8
h = [(1498139//5080320),
    (1107307//725760),
    (20761//80640),
    (1304999//725760),
    (299527//725760),
    (103097//80640),
    (670091//725760),
    (5127739//5080320), 1, 1, 1, 1]
e = [1//1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
H = Diagonal(h)

x1 = Int128(663)//950
x2 = Int128(17218045066)//142857142469
x3 = Int128(2883)//3800

q1 = [-1//2,
     -15849163//2257920+10x3+x1+5x2,
     235236677//6773760-45x3-5x1-24x2,
     -3577778591//60963840+75x3+10x1+45x2,
     67906303//1693440-50x3-10x1-40x2,
     -305821//193536+5x1+15x2,
     -13322233//1244160+15x3-x1,
     24839327//6773760-5x3-x2, 0, 0, 0, 0]'
q2 = [-q1[2] 0  0 0 0 0]
q3 = [-q1[3] -q2[3] 0  0 0 0 0]
q4 = [-q1[4] -q2[4] -q3[4] 0  0 0 0 0]
q5 = [-q1[5] -q2[5] -q3[5] -q4[5] 0  0 0 0 0]
q6 = [-q1[6] -q2[6] -q3[6] -q4[6] -q5[6] 0  0 0 0]
q7 = [-q1[7] -q2[7] -q3[7] -q4[7] -q5[7] -q6[7] 0  0 0]
q8 = [-q1[8] -q2[8] -q3[8] -q4[8] -q5[8] -q6[8] -q7[8] 0  0]
q9 = [0 0 0 0 1//280 -4//105 1//5 -4//5 0 4//5 -1//5 4//105]
q10 = [0 0 0 0 0 1//280 -4//105 1//5 -4//5 0 4//5 -1//5]
q11 = [0 0 0 0 0 0 1//280 -4//105 1//5 -4//5 0 4//5]
q12 = [0 0 0 0 0 0 0 1//280 -4//105 1//5 -4//5 0]
Q = vcat(q1, q2, q3, q4, q5, q6, q7, q8, q9, q10, q11, q12)

D1 = H \ (Q - 1//2*e*e')


text:
import Distributions.I

Random.seed!(22)

i, j, k = 3, 60, 200

U = rand(InverseWishart(i + 2, Matrix(1.0I, i, i)))
V = rand(InverseWishart(j + 2, Matrix(1.0I, j, j)))
Q = rand(InverseWishart(k + 2, Matrix(1.0I, k, k)))

m = randn(i)
n = randn(j)
o = randn(k)

σ = 2.0rand()
σ² = σ ^ 2

q = MvNormal(m, σ² * U)
r = MvNormal(n, σ² * V)
s = MvNormal(o, σ² * Q)

qᴰ = DegenerateMvNormal(m, σ² * U)
rᴰ = DegenerateMvNormal(n, σ² * V)
sᴰ = DegenerateMvNormal(o, σ² * Q)

@testset "Test logpdf of DegenerateMvNormal at mean" begin
    @test logpdf(q, q.μ) ≈ logpdf(qᴰ, qᴰ.μ)
    @test logpdf(r, r.μ) ≈ logpdf(rᴰ, rᴰ.μ)
    @test logpdf(s, s.μ) ≈ logpdf(sᴰ, sᴰ.μ)
end

x = rand(i)
y = rand(j)
z = rand(k)

@testset "Test logpdf of DegenerateMvNormal at random location" begin
    @test logpdf(q, x) ≈ logpdf(qᴰ, x)
    @test logpdf(r, y) ≈ logpdf(rᴰ, y)
    @test logpdf(s, z) ≈ logpdf(sᴰ, z)
end

nothing


text:
@doc raw"""
Symmetric quadratic mangetic field in (x,y,z) coordinates with covariant components of
the vector potential given by
```math
A (x,y,z) = \frac{B_0}{4} \big( - y \, (2 + x^2 + y^2) , \, x \, (2 + x^2 + y^2) , \, 0 \big)^T
```
resulting in the magnetic field with covariant components
```math
B(x,y,z) = B_0 \, \begin{pmatrix}
0 \\
0 \\
1 + x^2 + y^2 \\
\end{pmatrix}
```

Parameters: `B₀`
"""
module SymmetricQuadratic

    using RecipesBase
    using LaTeXStrings

    import ..ElectromagneticFields
    import ..ElectromagneticFields: CartesianEquilibrium, code
    import ..ElectromagneticFields: A₁, A₂, A₃
    import ..AnalyticCartesianField: X, Y, Z

    export SymmetricQuadraticEquilibrium

    const DEFAULT_B₀ = 1.0

    struct SymmetricQuadraticEquilibrium{T <: Number} <: CartesianEquilibrium
        name::String
        B₀::T
        SymmetricQuadraticEquilibrium{T}(B₀::T) where T <: Number = new("Symmetric Quadratic Magnetic Field", B₀)
    end

    SymmetricQuadraticEquilibrium(B₀::T=DEFAULT_B₀) where T <: Number = SymmetricQuadraticEquilibrium{T}(B₀)

    function init(B₀=DEFAULT_B₀)
        SymmetricQuadraticEquilibrium(B₀)
    end

    macro code(B₀=DEFAULT_B₀)
        code(init(B₀); escape=true)
    end

    function Base.show(io::IO, equ::SymmetricQuadraticEquilibrium)
        print(io, equ.name)
    end

    r²(x::AbstractVector, equ::SymmetricQuadraticEquilibrium) = X(x,equ)^2 + Y(x,equ)^2
    r(x::AbstractVector, equ::SymmetricQuadraticEquilibrium) = sqrt(r²(x,equ))
    R(x::AbstractVector, equ::SymmetricQuadraticEquilibrium) = r(x,equ)
    θ(x::AbstractVector, equ::SymmetricQuadraticEquilibrium) = atan(Y(x,equ), X(x,equ))
    ϕ(x::AbstractVector, equ::SymmetricQuadraticEquilibrium) = θ(x,equ)

    ElectromagneticFields.A₁(x::AbstractVector, equ::SymmetricQuadraticEquilibrium) = - equ.B₀ * x[2] * (2 + x[1]^2 + x[2]^2) / 4
    ElectromagneticFields.A₂(x::AbstractVector, equ::SymmetricQuadraticEquilibrium) = + equ.B₀ * x[1] * (2 + x[1]^2 + x[2]^2) / 4
    ElectromagneticFields.A₃(x::AbstractVector, equ::SymmetricQuadraticEquilibrium) = zero(eltype(x))
    B(x::AbstractVector, equ::SymmetricQuadraticEquilibrium) = equ.B₀ / (1 + x[1]^2 + x[2]^2)

    ElectromagneticFields.get_functions(::SymmetricQuadraticEquilibrium) = (X=X, Y=Y, Z=Z, R=R, r=r, θ=θ, ϕ=ϕ, r²=r²)

    @recipe function f(equ::SymmetricQuadraticEquilibrium;
                       nx = 100, ny = 100, levels = 20, size = (400,1200),
                       xlims = (-1., +1.),
                       ylims = (-1., +1.))

        xgrid  = LinRange(xlims[1], xlims[2], nx)
        ygrid  = LinRange(ylims[1], ylims[2], ny)
        pot1   = [A₁([xgrid[i], ygrid[j], 0], equ) for i in eachindex(xgrid), j in eachindex(ygrid)]
        pot2   = [A₂([xgrid[i], ygrid[j], 0], equ) for i in eachindex(xgrid), j in eachindex(ygrid)]
        Bfield = [B([xgrid[i], ygrid[j], 0], equ) for i in eachindex(xgrid), j in eachindex(ygrid)]

        seriestype   := :contour
        aspect_ratio := :equal
        layout := (3,1)
        size   := size
        xlims  := xlims
        ylims  := ylims
        levels := levels
        legend := :none

        @series begin
            subplot := 1
            title  := L"A_x (x,y)"
            xguide := L"x"
            yguide := L"y"
            (xgrid, ygrid, pot1)
        end

        @series begin
            subplot := 2
            title  := L"A_y (x,y)"
            xguide := L"x"
            yguide := L"y"
            (xgrid, ygrid, pot2)
        end

        @series begin
            subplot := 3
            title  := L"B_z (x,y)"
            xguide := L"x"
            yguide := L"y"
            (xgrid, ygrid, Bfield)
        end
    end

end


text:
"""
Handles Http server related functionality, manages requests and responses and their logging.
"""
module AppServer

using HTTP, Sockets
import Millboard, Distributed, Logging, MbedTLS
import Genie

"""
    ServersCollection(webserver::Union{Task,Nothing}, websockets::Union{Task,Nothing})

Represents a object containing references to Genie's web and websockets servers.
"""
Base.@kwdef mutable struct ServersCollection
  webserver::Union{Task,Nothing} = nothing
  websockets::Union{Task,Nothing} = nothing
end

"""
    SERVERS

ServersCollection constant containing references to the current app's web and websockets servers.
"""
const SERVERS = ServersCollection[]
const Servers = SERVERS

function isrunning(server::ServersCollection, prop::Symbol = :webserver) :: Bool
  isa(getfield(server, prop), Task) && ! istaskdone(getfield(server, prop))
end
function isrunning(prop::Symbol = :webserver) :: Bool
  isempty(SERVERS) ? false : isrunning(SERVERS[1], prop)
end

function server_status(server::ServersCollection, prop::Symbol) :: Nothing
  if isrunning(server)
    @info("✔ server is running.")
  else
    @error("❌ $server is not running.")
    isa(getfield(server, prop), Task) && fetch(getfield(server, prop))
  end

  nothing
end

"""
    startup(port::Int = Genie.config.server_port, host::String = Genie.config.server_host;
        ws_port::Int = Genie.config.websockets_port, async::Bool = ! Genie.config.run_as_server) :: ServersCollection

Starts the web server.

# Arguments
- `port::Int`: the port used by the web server
- `host::String`: the host used by the web server
- `ws_port::Int`: the port used by the Web Sockets server
- `async::Bool`: run the web server task asynchronously

# Examples
```julia-repl
julia> up(8000, "127.0.0.1", async = false)
[ Info: Ready!
Web Server starting at http://127.0.0.1:8000
```
"""
function startup(port::Int, host::String = Genie.config.server_host;
                  ws_port::Int = port,
                  async::Bool = ! Genie.config.run_as_server,
                  verbose::Bool = false,
                  ratelimit::Union{Rational{Int},Nothing} = nothing,
                  server::Union{Sockets.TCPServer,Nothing} = nothing,
                  wsserver::Union{Sockets.TCPServer,Nothing} = server,
                  ssl_config::Union{MbedTLS.SSLConfig,Nothing} = Genie.config.ssl_config,
                  open_browser::Bool = false,
                  reuseaddr::Bool = false,
                  http_kwargs...) :: ServersCollection

  if server !== nothing
    try
      socket_info = Sockets.getsockname(server)
      port = Int(socket_info[2])
      host = string(socket_info[1])
    catch ex
      @error "Failed parsing `server` parameter info."
      @error ex
    end
  end

  update_config(port, host, ws_port)

  new_server = ServersCollection()

  if Genie.config.websockets_server && port != ws_port
    print_server_status("Web Sockets server starting at $host:$ws_port")

    new_server.websockets = @async HTTP.listen(host, ws_port; verbose = verbose, rate_limit = ratelimit, server = wsserver,
                                                sslconfig = ssl_config, reuseaddr = reuseaddr, http_kwargs...) do http::HTTP.Stream
      if HTTP.WebSockets.is_upgrade(http.message)
        HTTP.WebSockets.upgrade(http) do ws
          setup_ws_handler(http.message, ws)
        end
      end
    end
  end

  command = () -> begin
    HTTP.listen(parse(Sockets.IPAddr, host), port; verbose = verbose, rate_limit = ratelimit, server = server,
                sslconfig = ssl_config, reuseaddr = reuseaddr, http_kwargs...) do http::HTTP.Stream
      try
        if Genie.config.websockets_server && port == ws_port && HTTP.WebSockets.is_upgrade(http.message)
          HTTP.WebSockets.upgrade(http) do ws
            setup_ws_handler(http.message, ws)
          end
        else
          setup_http_streamer(http)
        end
      catch ex
        isa(ex, Base.IOError) || @error ex
        nothing
      end
    end
  end

  server_url = "$( (ssl_config !== nothing && Genie.config.ssl_enabled) ? "https" : "http" )://$host:$port"

  status = if async
    print_server_status("Web Server starting at $server_url")
    @async command()
  else
    print_server_status("Web Server starting at $server_url - press Ctrl/Cmd+C to stop the server.")
    command()
  end

  if status !== nothing && status.state == :runnable
    new_server.webserver = status

    try
      open_browser && openbrowser(server_url)
    catch ex
      @error "Failed to open browser"
      @error ex
    end
  end

  push!(SERVERS, new_server)

  new_server
end

function startup(; port = Genie.config.server_port, ws_port = Genie.config.websockets_port, kwargs...) :: ServersCollection
    startup(port; ws_port = ws_port, kwargs...)
end

const up = startup

print_server_status(status::String) = @info "\n$status \n"

@static if Sys.isapple()
  openbrowser(url::String) = run(`open $url`)
elseif Sys.islinux()
  openbrowser(url::String) = run(`xdg-open $url`)
elseif Sys.iswindows()
  openbrowser(url::String) = run(`cmd /C start $url`)
end

"""
    update_config(port::Int, host::String, ws_port::Int) :: Nothing

Updates the corresponding Genie configurations to the corresponding values for
  `port`, `host`, and `ws_port`, if these are passed as arguments when starting up the server.
"""
function update_config(port::Int, host::String, ws_port::Int) :: Nothing
  Genie.config.server_port = port
  Genie.config.server_host = host
  Genie.config.websockets_port = ws_port

  nothing
end

"""
    down(; webserver::Bool = true, websockets::Bool = true) :: ServersCollection

Shuts down the servers optionally indicating which of the `webserver` and `websockets` servers to be stopped.
It does not remove the servers from the `SERVERS` collection. Returns the collection.
"""
function down(; webserver::Bool = true, websockets::Bool = true) :: Vector{ServersCollection}
  for i in 1:length(SERVERS)
    down(SERVERS[i]; webserver, websockets)
  end

  SERVERS
end

function down(server::ServersCollection; webserver::Bool = true, websockets::Bool = true) :: ServersCollection
  webserver && (@async Base.throwto(server.webserver, InterruptException()))
  isnothing(websockets) || (websockets && (@async Base.throwto(server.websockets, InterruptException())))

  server
end

"""
    function down!(; webserver::Bool = true, websockets::Bool = true) :: Vector{ServersCollection}

Shuts down all the servers and empties the `SERVERS` collection. Returns the empty collection.
"""
function down!() :: Vector{ServersCollection}
  down()
  empty!(SERVERS)

  SERVERS
end

"""
    handle_request(req::HTTP.Request, res::HTTP.Response) :: HTTP.Response

Http server handler function - invoked when the server gets a request.
"""
function handle_request(req::HTTP.Request, res::HTTP.Response) :: HTTP.Response
  try
    req = Genie.Headers.normalize_headers(req)
  catch ex
    @error ex
  end

  try
    Genie.Headers.set_headers!(req, res, Genie.Router.route_request(req, res))
  catch ex
    rethrow(ex)
  end
end

function setup_http_streamer(http::HTTP.Stream)
  if Genie.config.features_peerinfo
    try
      task_local_storage(:peer, Sockets.getpeername( HTTP.IOExtras.tcpsocket(HTTP.Streams.getrawstream(http)) ))
    catch ex
      @error ex
    end
  end

  HTTP.handle(HTTP.RequestHandlerFunction(setup_http_listener), http)
end

"""
    setup_http_listener(req::HTTP.Request, res::HTTP.Response = HTTP.Response()) :: HTTP.Response

Configures the handler for the HTTP Request and handles errors.
"""
function setup_http_listener(req::HTTP.Request, res::HTTP.Response = HTTP.Response()) :: HTTP.Response
  try
    Distributed.@fetch handle_request(req, res)
  catch ex # ex is a Distributed.RemoteException
    if isa(ex, Distributed.RemoteException) &&
      hasfield(typeof(ex), :captured) && isa(ex.captured, Distributed.CapturedException) &&
        hasfield(typeof(ex.captured), :ex) && isa(ex.captured.ex, Genie.Exceptions.RuntimeException)

      @error ex.captured.ex
      return Genie.Router.error(ex.captured.ex.code, ex.captured.ex.message, Genie.Router.response_mime(),
                              error_info = string(ex.captured.ex.code, " ", ex.captured.ex.info))
    end

    error_message = string(sprint(showerror, ex), "\n\n")
    @error error_message

    message = Genie.Configuration.isprod() ?
                "The error has been logged and we'll look into it ASAP." :
                error_message

    Genie.Router.error(message, Genie.Router.response_mime(), Val(500))
  end
end

"""
    setup_ws_handler(req::HTTP.Request, ws_client) :: Nothing

Configures the handler for WebSockets requests.
"""
function setup_ws_handler(req::HTTP.Request, ws_client) :: Nothing
  try
    while ! eof(ws_client)
      write(ws_client, String(Distributed.@fetch handle_ws_request(req, String(readavailable(ws_client)), ws_client)))
    end
  catch ex
    if isa(ex, Distributed.RemoteException) &&
      hasfield(typeof(ex), :captured) && isa(ex.captured, Distributed.CapturedException) &&
        hasfield(typeof(ex.captured), :ex) && isa(ex.captured.ex, Genie.Exceptions.RuntimeException)
      @error ex.captured.ex
    end
  end

  nothing
end

"""
    handle_ws_request(req::HTTP.Request, msg::String, ws_client) :: String

Http server handler function - invoked when the server gets a request.
"""
function handle_ws_request(req::HTTP.Request, msg::String, ws_client) :: String
  isempty(msg) && return "" # keep alive
  Genie.Router.route_ws_request(req, msg, ws_client)
end

end


text:
# This file was generated, do not modify it. # hide
using MLJ, CategoricalArrays, PrettyPrinting
import DataFrames: DataFrame, nrow
using UrlDownload
@load LinearRegressor pkg = GLM
@load LinearBinaryClassifier pkg=GLM


text:
abstract type CollisionModel end

include("collision_models/srt.jl")
include("collision_models/trt.jl")
include("collision_models/mrt.jl")
include("collision_models/iterative_initialization.jl")

"""
Our default collision model uses the Single Relaxation Time method
"""
function CollisionModel(
    cm::Type{<:CollisionModel},
    q::Quadrature,
    problem::FluidFlowProblem,
)
    return CollisionModel(SRT, q, problem)
end
CollisionModel(cm::CollisionModel, ::Quadrature, ::FluidFlowProblem) = cm
collide!(cm, q::Quadrature; time, f_new, f_old) = collide!(cm, q, f_old, f_new, time = time)


text:
"""
Tools and helper functions for analyzing the results
"""

"""
Returns analysis of how many times heuristic MCTS planner returns action that is
different from the VI (assumed to be optimal).

The method calculates this across all MDP states, so it only works for small problem instances.
"""
function compare_actions(mdp_vi::PMDPe, vi_policy::ValueIterationPolicy, mc_planner::MCTSPlanner; rng_seed=123, verbose=false)
    rng = MersenneTwister(rng_seed)
    if verbose
        println("\t\t\t\t\t\t\t\t Actions: ", mdp_vi.actions)
    end
    bad_a = 0
    avg_q_Δ=0
    avg_a_Δ = 0
    for i in 1:length(mdp_vi.states)
    #     s_i = rand(rng, 1:length(mdp_vi.states))
        s = mdp_vi.states[i]
        a_vi = action(vi_policy, s)
        a_mc = action(mc_planner, s)
        if a_vi!=a_mc && abs(a_vi - a_mc)!=1000
            Q_s = vi_policy.qmat[stateindex(mdp_vi, s),:]
            q_Δ = Q_s[actionindex(mdp_vi, a_vi)] - Q_s[actionindex(mdp_vi, a_mc)]
            avg_q_Δ += q_Δ
            avg_a_Δ += abs(a_vi - a_mc)
            if verbose
                print("$s: a_vi=$a_vi, a_mc=$a_mc, q_Δ=$q_Δ Q:")
                println(Q_s)
            end
            bad_a+=1
        end
    end
    n_S = length(mdp_vi.states)
    print("Total of $bad_a bad actions of $n_S")
    return bad_a, avg_q_Δ/bad_a, avg_a_Δ/bad_a
end