text:
@with_kw struct Parameter

    T=Float32                 # number format

    Tprog=T                   # number format for prognostic variables
    Tcomm=Tprog               # number format for ghost-point copies

    # DOMAIN RESOLUTION AND RATIO
    nx::Int=100                         # number of grid cells in x-direction
    Lx::Real=2000e3                     # length of the domain in x-direction [m]
    L_ratio::Real=2                     # Domain aspect ratio of Lx/Ly

    # PHYSICAL CONSTANTS
    g::Real=10.                         # gravitational acceleration [m/s]
    H::Real=500.                        # layer thickness at rest [m]
    ρ::Real=1e3                         # water density [kg/m^3]
    ϕ::Real=45.                         # central latitude of the domain (for coriolis) [°]
    ω::Real=2π/(24*3600)                # Earth's angular frequency [s^-1]
    R::Real=6.371e6                     # Earth's radius [m]

    # WIND FORCING OPTIONS
    wind_forcing_x::String="channel"    # "channel", "double_gyre", "shear","constant" or "none"
    wind_forcing_y::String="constant"   # "channel", "double_gyre", "shear","constant" or "none"
    Fx0::Real=0.12                      # wind stress strength [Pa] in x-direction
    Fy0::Real=0.0                       # wind stress strength [Pa] in y-direction
    seasonal_wind_x::Bool=false         # Change the wind stress with a sine of frequency ωFx,ωFy
    seasonal_wind_y::Bool=false         # same for y-component
    ωFx::Real=1.0                       # frequency [1/year] for x component
    ωFy::Real=1.0                       # frequency [1/year] for y component

    # BOTTOM TOPOGRAPHY OPTIONS
    topography::String="ridge"          # "ridge", "seamount", "flat", "ridges", "bathtub"
    topo_height::Real=50.               # height of seamount [m]
    topo_width::Real=300e3              # horizontal scale [m] of the seamount

    # SURFACE RELAXATION
    surface_relax::Bool=false           # yes?
    t_relax::Real=100.                  # time scale of the relaxation [days]
    η_refh::Real=5.                     # height difference [m] of the interface relaxation profile
    η_refw::Real=50e3                   # width [m] of the tangent used for the interface relaxation

    # SURFACE FORCING
    surface_forcing::Bool=false         # yes?
    ωFη::Real=1.0                       # frequency [1/year] for surfance forcing
    A::Real=3e-5                        # Amplitude [m/s]
    ϕk::Real=ϕ                          # Central latitude of Kelvin wave pumping
    wk::Real=10e3                       # width [m] in y of Gaussian used for surface forcing

    # TIME STEPPING OPTIONS
    RKo::Int=4                          # Order of the RK time stepping scheme (3 or 4)
    cfl::Real=1.0                       # CFL number (1.0 recommended for RK4, 0.6 for RK3)
    Ndays::Real=10.0                    # number of days to integrate for
    nstep_diff::Int=1                   # diffusive part every nstep_diff time steps.
    nstep_advcor::Int=0                 # advection and coriolis update every nstep_advcor time steps.
                                        # 0 means it is included in every RK4 substep

    # BOUNDARY CONDITION OPTIONS
    bc::String="periodic"               # "periodic" or anything else for nonperiodic
    α::Real=2.                          # lateral boundary condition parameter
                                        # 0 free-slip, 0<α<2 partial-slip, 2 no-slip

    # MOMENTUM ADVECTION OPTIONS
    adv_scheme::String="ArakawaHsu"     # "Sadourny" or "ArakawaHsu"
    dynamics::String="nonlinear"        # "linear" or "nonlinear"

    # BOTTOM FRICTION OPTIONS
    bottom_drag::String="quadratic"     # "linear", "quadratic" or "none"
    cD::Real=1e-5                       # bottom drag coefficient [dimensionless] for quadratic
    τD::Real=300.                       # bottom drag coefficient [days] for linear

    # DIFFUSION OPTIONS
    diffusion::String="constant"        # "Smagorinsky" or "constant", biharmonic in both cases
    νB::Real=500.0                      # [m^2/s] scaling constant for constant biharmonic diffusion
    cSmag::Real=0.15                    # Smagorinsky coefficient [dimensionless]

    # TRACER ADVECTION
    tracer_advection::Bool=true         # yes?
    tracer_relaxation::Bool=false       # yes?
    tracer_consumption::Bool=false      # yes?
    tracer_pumping::Bool=false          # yes?
    injection_region::String="west"     # "west", "south", "rect" or "flat"
    sst_initial::String="south"         # "west", "south", "rect", "flat" or "restart"
    sst_rect_coords::Array{Float64,1}=[0.,0.15,0.,1.0]
                                        # (x0,x1,y0,y1) are the size of the rectangle in [0,1]
    Uadv::Real=0.25                     # Velocity scale [m/s] for tracer advection
    SSTmax::Real=1.                     # tracer (sea surface temperature) max for restoring
    SSTmin::Real=0.                     # tracer (sea surface temperature) min for restoring
    τSST::Real=500.                     # tracer restoring time scale [days]
    jSST::Real=365.                     # tracer consumption [days]
    SST_λ0::Real=222e3                  # [m] transition position of relaxation timescale
    SST_λs::Real=111e3                  # [m] transition width of relaxation timescale
    SST_γ0::Real=8.35                   # [days] injection time scale
    SSTw::Real=5e3                      # width [m] of the tangent used for the IC and interface relaxation
    SSTϕ::Real=0.5                      # latitude/longitude fraction ∈ [0,1] of sst edge

    # OUTPUT OPTIONS
    output::Bool=false                  # netcdf output?
    output_vars::Array{String,1}=["u","v","η","sst"]  # which variables to output? "du","dv","dη" also allowed
    output_dt::Real=6                   # output time step [hours]
    outpath::String=pwd()               # path to output folder

    # INITIAL CONDITIONS
    initial_cond::String="rest"         # "rest" or "ncfile" for restart from file
    initpath::String=outpath            # folder where to pick the restart files from
    init_run_id::Int=0                  # run id for restart from run number
    init_starti::Int=-1                 # timestep to start from (-1 meaning last)
    get_id_mode::String="continue"      # How to determine the run id: "continue" or "fill"
    run_id::Int=-1                      # Output with a specific run id
    init_interpolation::Bool=true       # Interpolate the initial conditions in case grids don't match?

    # ASSERT - CHECK THAT THE INPUT PARAMETERS MAKE SENSE
    @assert all((nx,Lx,L_ratio) .> 0.)  "nx, Lx, L_ratio have to be >0"
    @assert all((g,H,ρ,ω,R) .> 0.)      "g,H,ρ,ω,R have to be >0"
    @assert ϕ <= 90.0 && ϕ >= -90.0     "ϕ has to be in (-90,90), $ϕ given."
    @assert wind_forcing_x in ["channel","double_gyre","shear","constant","none"] "Wind forcing '$wind_forcing_x' unsupported"
    @assert wind_forcing_y in ["channel","double_gyre","shear","constant","none"] "Wind forcing '$wind_forcing_y' unsupported"
    @assert topography in ["ridge","seamount","flat","ridges"] "Topography '$topography' unsupported"
    @assert topo_width > 0.0    "topo_width has to be >0, $topo_width given."
    @assert t_relax > 0.0       "t_relax has to be >0, $t_relax given."
    @assert η_refw > 0.0        "η_refw has to be >0, $η_refw given."
    @assert RKo in [2,3,4]        "RKo has to be 2,3 or 4, $RKo given."
    @assert Ndays > 0.0         "Ndays has to be >0, $Ndays given."
    @assert nstep_diff > 0      "nstep_diff has to be >0, $nstep_diff given."
    @assert nstep_advcor >= 0   "nstep_advcor has to be >=0, $nstep_advcor given."
    @assert bc in ["periodic","nonperiodic"]    "boundary condition '$bc' unsupported."
    @assert α >= 0.0 && α <= 2.0    "Tangential boundary condition α has to be in (0,2), $α given."
    @assert adv_scheme in ["Sadourny","ArakawaHsu"] "Advection scheme '$adv_scheme' unsupported"
    @assert dynamics in ["linear","nonlinear"]  "Dynamics '$dynamics' unsupoorted."
    @assert bottom_drag in ["quadratic","linear","none"] "Bottom drag '$bottom_drag' unsupported."
    @assert cD >= 0.0    "Bottom drag coefficient cD has to be >=0, $cD given."
    @assert τD >= 0.0    "Bottom drag coefficient τD has to be >=0, $τD given."
    @assert diffusion in ["Smagorinsky", "constant"] "Diffusion '$diffusion' unsupoorted."
    @assert νB > 0.0     "Diffusion scaling constant νB has to be > 0, $νB given."
    @assert cSmag > 0.0  "Smagorinsky coefficient cSmag has to be >0, $cSmag given."
    @assert injection_region in ["west","south"] "Injection region '$injection_region' unsupported."
    @assert Uadv > 0.0   "Advection velocity scale Uadv has to be >0, $Uadv given."
    @assert output_dt > 0   "Output time step has to be >0, $output_dt given."
    @assert initial_cond in ["rest", "ncfile"] "Initial conditions '$initial_cond' unsupported."
    @assert init_run_id >= 0 "Initial condition run id, init_run_id, has to be >= 0, $init_run_id given."
    @assert init_starti > 0 || init_starti == -1 "Start index, init_starti, has to be >0 || -1, $init_starti given."
    @assert get_id_mode in ["continue","fill","specific"] "get_id_mode $get_id_mode unsupported."
end

"""
Creates a Parameter struct with following options and default values

    T::DataType=Float32                 # number format

    Tprog::DataType=T                   # number format for prognostic variables
    Tcomm::DataType=Tprog               # number format for ghost-point copies

    # DOMAIN RESOLUTION AND RATIO
    nx::Int=100                         # number of grid cells in x-direction
    Lx::Real=2000e3                     # length of the domain in x-direction [m]
    L_ratio::Real=2                     # Domain aspect ratio of Lx/Ly

    # PHYSICAL CONSTANTS
    g::Real=10.                         # gravitational acceleration [m/s]
    H::Real=500.                        # layer thickness at rest [m]
    ρ::Real=1e3                         # water density [kg/m^3]
    ϕ::Real=45.                         # central latitude of the domain (for coriolis) [°]
    ω::Real=2π/(24*3600)                # Earth's angular frequency [s^-1]
    R::Real=6.371e6                     # Earth's radius [m]

    # WIND FORCING OPTIONS
    wind_forcing_x::String="channel"    # "channel", "double_gyre", "shear","constant" or "none"
    wind_forcing_y::String="constant"   # "channel", "double_gyre", "shear","constant" or "none"
    Fx0::Real=0.12                      # wind stress strength [Pa] in x-direction
    Fy0::Real=0.0                       # wind stress strength [Pa] in y-direction
    seasonal_wind_x::Bool=false         # Change the wind stress with a sine of frequency ωFx,ωFy
    seasonal_wind_y::Bool=false         # same for y-component
    ωFx::Real=1.0                       # frequency [1/year] for x component
    ωFy::Real=1.0                       # frequency [1/year] for y component

    # BOTTOM TOPOGRAPHY OPTIONS
    topography::String="ridge"          # "ridge", "seamount", "flat", "ridges", "bathtub"
    topo_height::Real=50.               # height of seamount [m]
    topo_width::Real=300e3              # horizontal scale [m] of the seamount

    # SURFACE RELAXATION
    surface_relax::Bool=false           # yes?
    t_relax::Real=100.                  # time scale of the relaxation [days]
    η_refh::Real=5.                     # height difference [m] of the interface relaxation profile
    η_refw::Real=50e3                   # width [m] of the tangent used for the interface relaxation

    # SURFACE FORCING
    surface_forcing::Bool=false         # yes?
    ωFη::Real=1.0                       # frequency [1/year] for surfance forcing
    A::Real=3e-5                        # Amplitude [m/s]
    ϕk::Real=ϕ                          # Central latitude of Kelvin wave pumping
    wk::Real=10e3                       # width [m] in y of Gaussian used for surface forcing

    # TIME STEPPING OPTIONS
    RKo::Int=4                          # Order of the RK time stepping scheme (2,3 or 4)
    cfl::Real=1.0                       # CFL number (1.0 recommended for RK4, 0.6 for RK3, 0.1 for RK2)
    Ndays::Real=10.0                    # number of days to integrate for
    nstep_diff::Int=1                   # diffusive part every nstep_diff time steps.
    nstep_advcor::Int=0                 # advection and coriolis update every nstep_advcor time steps.
                                        # 0 means it is included in every RK4 substep

    # BOUNDARY CONDITION OPTIONS
    bc::String="periodic"               # "periodic" or anything else for nonperiodic
    α::Real=2.                          # lateral boundary condition parameter
                                        # 0 free-slip, 0<α<2 partial-slip, 2 no-slip

    # MOMENTUM ADVECTION OPTIONS
    adv_scheme::String="ArakawaHsu"     # "Sadourny" or "ArakawaHsu"
    dynamics::String="nonlinear"        # "linear" or "nonlinear"

    # BOTTOM FRICTION OPTIONS
    bottom_drag::String="quadratic"     # "linear", "quadratic" or "none"
    cD::Real=1e-5                       # bottom drag coefficient [dimensionless] for quadratic
    τD::Real=300.                       # bottom drag coefficient [days] for linear

    # DIFFUSION OPTIONS
    diffusion::String="constant"        # "Smagorinsky" or "constant", biharmonic in both cases
    νB::Real=500.0                      # [m^2/s] scaling constant for constant biharmonic diffusion
    cSmag::Real=0.15                    # Smagorinsky coefficient [dimensionless]

    # TRACER ADVECTION
    tracer_advection::Bool=true         # yes?
    tracer_relaxation::Bool=false       # yes?
    tracer_consumption::Bool=false      # yes?
    tracer_pumping::Bool=false          # yes?
    injection_region::String="west"     # "west", "south", "rect" or "flat"
    sst_initial::String="south"         # "west", "south", "rect", "flat" or "restart"
    sst_rect_coords::Array{Float64,1}=[0.,0.15,0.,1.0]
                                        # (x0,x1,y0,y1) are the size of the rectangle in [0,1]
    Uadv::Real=0.25                     # Velocity scale [m/s] for tracer advection
    SSTmax::Real=1.                     # tracer (sea surface temperature) max for restoring
    SSTmin::Real=0.                     # tracer (sea surface temperature) min for restoring
    τSST::Real=500.                     # tracer restoring time scale [days]
    jSST::Real=365.                     # tracer consumption [days]
    SST_λ0::Real=222e3                  # [m] transition position of relaxation timescale
    SST_λs::Real=111e3                  # [m] transition width of relaxation timescale
    SST_γ0::Real=8.35                   # [days] injection time scale
    SSTw::Real=5e3                      # width [m] of the tangent used for the IC and interface relaxation
    SSTϕ::Real=0.5                      # latitude/longitude fraction ∈ [0,1] of sst edge

    # OUTPUT OPTIONS
    output::Bool=false                  # netcdf output?
    output_vars::Array{String,1}=["u","v","η","sst"]  # which variables to output? q,ζ,du,dv,dη also allowed.
    output_dt::Real=6                   # output time step [hours]
    outpath::String=pwd()               # path to output folder

    # INITIAL CONDITIONS
    initial_cond::String="rest"         # "rest" or "ncfile" for restart from file
    initpath::String=outpath            # folder where to pick the restart files from
    init_run_id::Int=0                  # run id for restart from run number
    init_starti::Int=-1                 # timestep to start from (-1 meaning last)
    get_id_mode::String="continue"      # How to determine the run id: "continue" or "fill"
    run_id::Int=-1                      # Output with a specific run id
    init_interpolation::Bool=true       # Interpolate the initial conditions in case grids don't match?

"""
Parameter


text:
# stub tests for coverage; disregards output.

f = IOBuffer()

@test traverse_graph_withlog(g6, BreadthFirst(), [1;], f) == nothing

@test visited_vertices(g6, BreadthFirst(), [1;]) == [1, 2, 3, 4, 5]

function trivialgraphvisit(
    g::SimpleGraph,
    alg::LightGraphs.SimpleGraphVisitAlgorithm,
    sources
)
    visitor = TrivialGraphVisitor()
    traverse_graph!(g, alg, sources, visitor)
end

@test trivialgraphvisit(g, BreadthFirst(), 1) == nothing

# this just exercises some graph visitors
@test traverse_graph!(g, BreadthFirst(), 1, TrivialGraphVisitor()) == nothing
@test traverse_graph!(g, BreadthFirst(), 1, LogGraphVisitor(IOBuffer())) == nothing

# dummy edge map test
d = LightGraphs.DummyEdgeMap()
e = Edge(1,2)
@test d[e] == 0

ext: jl


text:
2
# Tests the code for computing the derivatives
# of M_n with respect to k.
# include("../src/transit_poly_struct.jl")
# include("../src/Mn_compute.jl")
# include("../src/transit_structure.jl")
# include("../src/cel_bulirsch.jl")
# include("random.jl")

# using PyPlot

# Randomizer seed
#using Random
seed = Random.seed!(42)

using QuadGK

@testset "Mn_test" begin

function Mn_num(k2::T,m::Int64) where {T <: Real}
# Numerically integrates M_n(k^2)/(4br)^m (note: m can be a half-integer).
# See 11/10/2018 notes.
f(x) = sqrt(k2-sin(x)^2)^m
if k2 < 1.0
  kap2 = convert(T,asin(sqrt(big(k2))))
  Mn,error = quadgk(f,-kap2,kap2,rtol=1e-15)
else
  pi2 = 0.5*pi
  Mn,error = quadgk(f,-pi2,pi2,rtol=1e-15)
end
return Mn
end

# Carries out a test of M_n for k^2 and n_max:
function test_Mn(r::T,b::T) where {T <: Real}
n_max = 30
#n_max = 10
# Set up transit structures for Float64 and BigFloat:
u = ones(n_max+2)
prec_frac = zeros(n_max+3)
prec_abs  = zeros(n_max+3)
# Initialize the transit structure to pass to routines:
t = transit_init(r,b,u,true)  # Float64
t_big = transit_init(big(r),big(b),big.(u),false) # BigFloat
# Call the transit routines, thereby computing Mn:
transit_poly!(t)
transit_poly!(t_big)

# Now compute with numerical integration, and compare:
reltol = 1e-6
abstol = 1e-15
# Compare with numerical integration:
for m=0:t.n_max
  Mnn = Mn_num(t.k2,m)*(2*t.sqbr)^m
  test1 = isapprox(Mnn,t.Mn[m+1],atol=abstol,rtol = reltol)
  if !test1
    println("m: ",m," k2: ",t.k2," Mn_num: ",Mnn," M_n: ",t.Mn[m+1]," diff: ",Mnn-t.Mn[m+1]," M_n[big]: ",convert(Float64,t_big.Mn[m+1]))
  end
  test2 = isapprox(t.Mn[m+1],convert(Float64,t_big.Mn[m+1]),atol=abstol,rtol=reltol)
  prec_frac[m+1] = t.Mn[m+1]/convert(Float64,t_big.Mn[m+1])-1.0
  prec_abs[m+1] = asinh(t.Mn[m+1])-asinh(convert(Float64,t_big.Mn[m+1]))
  if !test2
    println("m: ",m," k2: ",t.k2," Mn: ",t.Mn[m+1]," M_n_big: ",convert(Float64,t_big.Mn[m+1])," diff: ",t.Mn[m+1]-convert(Float64,t_big.Mn[m+1]))
  end
  @test test1
  @test test2
end
return prec_frac,prec_abs
end

epsilon = 1e-8
r=100.0; b0=[r-1+epsilon,r,r+1-epsilon]
for i=1:length(b0)
  b=b0[i]
  k2 = (1-b+r)*(1+b-r)/(4*b*r)
  if k2 >= 0
    prec_frac,prec_abs = test_Mn(r,b)
#    semilogy(abs.(prec_frac))
    #semilogy(abs.(prec_abs),":")
    println("r: ",r," b: ",b," k2: ",k2," max error frac: ",maximum(abs.(prec_frac))," max error abs: ",maximum(abs.(prec_abs)))
  end
end

r=0.01; b0=[epsilon,r,1-r-epsilon,1-r+epsilon,1.0,r+1-epsilon]
for i=1:length(b0)
  b=b0[i]
  k2 = (1-b+r)*(1+b-r)/(4*b*r)
  if k2 >= 0
    prec_frac,prec_abs= test_Mn(r,b)
#    semilogy(abs.(prec_frac))
    #semilogy(abs.(prec_abs),":")
    println("r: ",r," b: ",b," k2: ",k2," max error frac: ",maximum(abs.(prec_frac))," max error abs: ",maximum(abs.(prec_abs)))
  end
end

ntest = 10
for i=1:ntest
  r= 2.0 ; b = 0.25
  while r > 1 + b || r < b-1
    r = 2rand(seed); b=2rand(seed)
  end
  k2 = (1-b+r)*(1+b-r)/(4*b*r)
  prec_frac,prec_abs = test_Mn(r,b)
#  semilogy(abs.(prec_frac))
  #semilogy(abs.(prec_abs),":")
  println("r: ",r," b: ",b," k2: ",k2," max error frac: ",maximum(abs.(prec_frac))," max error abs: ",maximum(abs.(prec_abs)))
end
#axis([0,32,1e-17,1e-5])
end


text:
# syntax: proto3
using ProtoBuf
import ProtoBuf.meta
import ProtoBuf.google.protobuf

mutable struct ListComponentsRequest <: ProtoType
    __protobuf_jl_internal_meta::ProtoMeta
    __protobuf_jl_internal_values::Dict{Symbol,Any}
    __protobuf_jl_internal_defaultset::Set{Symbol}

    function ListComponentsRequest(; kwargs...)
        obj = new(meta(ListComponentsRequest), Dict{Symbol,Any}(), Set{Symbol}())
        values = obj.__protobuf_jl_internal_values
        symdict = obj.__protobuf_jl_internal_meta.symdict
        for nv in kwargs
            fldname, fldval = nv
            fldtype = symdict[fldname].jtyp
            (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
            if fldval !== nothing
                values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
            end
        end
        obj
    end
end # mutable struct ListComponentsRequest
const __meta_ListComponentsRequest = Ref{ProtoMeta}()
function meta(::Type{ListComponentsRequest})
    ProtoBuf.metalock() do
        if !isassigned(__meta_ListComponentsRequest)
            __meta_ListComponentsRequest[] = target = ProtoMeta(ListComponentsRequest)
            allflds = Pair{Symbol,Union{Type,String}}[:namespace => AbstractString]
            meta(target, ListComponentsRequest, allflds, ProtoBuf.DEF_REQ, ProtoBuf.DEF_FNUM, ProtoBuf.DEF_VAL, ProtoBuf.DEF_PACK, ProtoBuf.DEF_WTYPES, ProtoBuf.DEF_ONEOFS, ProtoBuf.DEF_ONEOF_NAMES)
        end
        __meta_ListComponentsRequest[]
    end
end
function Base.getproperty(obj::ListComponentsRequest, name::Symbol)
    if name === :namespace
        return (obj.__protobuf_jl_internal_values[name])::AbstractString
    else
        getfield(obj, name)
    end
end

mutable struct ComponentUpdateRequest <: ProtoType
    __protobuf_jl_internal_meta::ProtoMeta
    __protobuf_jl_internal_values::Dict{Symbol,Any}
    __protobuf_jl_internal_defaultset::Set{Symbol}

    function ComponentUpdateRequest(; kwargs...)
        obj = new(meta(ComponentUpdateRequest), Dict{Symbol,Any}(), Set{Symbol}())
        values = obj.__protobuf_jl_internal_values
        symdict = obj.__protobuf_jl_internal_meta.symdict
        for nv in kwargs
            fldname, fldval = nv
            fldtype = symdict[fldname].jtyp
            (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
            if fldval !== nothing
                values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
            end
        end
        obj
    end
end # mutable struct ComponentUpdateRequest
const __meta_ComponentUpdateRequest = Ref{ProtoMeta}()
function meta(::Type{ComponentUpdateRequest})
    ProtoBuf.metalock() do
        if !isassigned(__meta_ComponentUpdateRequest)
            __meta_ComponentUpdateRequest[] = target = ProtoMeta(ComponentUpdateRequest)
            allflds = Pair{Symbol,Union{Type,String}}[:namespace => AbstractString]
            meta(target, ComponentUpdateRequest, allflds, ProtoBuf.DEF_REQ, ProtoBuf.DEF_FNUM, ProtoBuf.DEF_VAL, ProtoBuf.DEF_PACK, ProtoBuf.DEF_WTYPES, ProtoBuf.DEF_ONEOFS, ProtoBuf.DEF_ONEOF_NAMES)
        end
        __meta_ComponentUpdateRequest[]
    end
end
function Base.getproperty(obj::ComponentUpdateRequest, name::Symbol)
    if name === :namespace
        return (obj.__protobuf_jl_internal_values[name])::AbstractString
    else
        getfield(obj, name)
    end
end

mutable struct ComponentUpdateEvent <: ProtoType
    __protobuf_jl_internal_meta::ProtoMeta
    __protobuf_jl_internal_values::Dict{Symbol,Any}
    __protobuf_jl_internal_defaultset::Set{Symbol}

    function ComponentUpdateEvent(; kwargs...)
        obj = new(meta(ComponentUpdateEvent), Dict{Symbol,Any}(), Set{Symbol}())
        values = obj.__protobuf_jl_internal_values
        symdict = obj.__protobuf_jl_internal_meta.symdict
        for nv in kwargs
            fldname, fldval = nv
            fldtype = symdict[fldname].jtyp
            (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
            if fldval !== nothing
                values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
            end
        end
        obj
    end
end # mutable struct ComponentUpdateEvent
const __meta_ComponentUpdateEvent = Ref{ProtoMeta}()
function meta(::Type{ComponentUpdateEvent})
    ProtoBuf.metalock() do
        if !isassigned(__meta_ComponentUpdateEvent)
            __meta_ComponentUpdateEvent[] = target = ProtoMeta(ComponentUpdateEvent)
            allflds = Pair{Symbol,Union{Type,String}}[:component => Vector{UInt8}]
            meta(target, ComponentUpdateEvent, allflds, ProtoBuf.DEF_REQ, ProtoBuf.DEF_FNUM, ProtoBuf.DEF_VAL, ProtoBuf.DEF_PACK, ProtoBuf.DEF_WTYPES, ProtoBuf.DEF_ONEOFS, ProtoBuf.DEF_ONEOF_NAMES)
        end
        __meta_ComponentUpdateEvent[]
    end
end
function Base.getproperty(obj::ComponentUpdateEvent, name::Symbol)
    if name === :component
        return (obj.__protobuf_jl_internal_values[name])::Vector{UInt8}
    else
        getfield(obj, name)
    end
end

mutable struct ListComponentResponse <: ProtoType
    __protobuf_jl_internal_meta::ProtoMeta
    __protobuf_jl_internal_values::Dict{Symbol,Any}
    __protobuf_jl_internal_defaultset::Set{Symbol}

    function ListComponentResponse(; kwargs...)
        obj = new(meta(ListComponentResponse), Dict{Symbol,Any}(), Set{Symbol}())
        values = obj.__protobuf_jl_internal_values
        symdict = obj.__protobuf_jl_internal_meta.symdict
        for nv in kwargs
            fldname, fldval = nv
            fldtype = symdict[fldname].jtyp
            (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
            if fldval !== nothing
                values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
            end
        end
        obj
    end
end # mutable struct ListComponentResponse
const __meta_ListComponentResponse = Ref{ProtoMeta}()
function meta(::Type{ListComponentResponse})
    ProtoBuf.metalock() do
        if !isassigned(__meta_ListComponentResponse)
            __meta_ListComponentResponse[] = target = ProtoMeta(ListComponentResponse)
            allflds = Pair{Symbol,Union{Type,String}}[:components => Base.Vector{Vector{UInt8}}]
            meta(target, ListComponentResponse, allflds, ProtoBuf.DEF_REQ, ProtoBuf.DEF_FNUM, ProtoBuf.DEF_VAL, ProtoBuf.DEF_PACK, ProtoBuf.DEF_WTYPES, ProtoBuf.DEF_ONEOFS, ProtoBuf.DEF_ONEOF_NAMES)
        end
        __meta_ListComponentResponse[]
    end
end
function Base.getproperty(obj::ListComponentResponse, name::Symbol)
    if name === :components
        return (obj.__protobuf_jl_internal_values[name])::Base.Vector{Vector{UInt8}}
    else
        getfield(obj, name)
    end
end

mutable struct GetConfigurationRequest <: ProtoType
    __protobuf_jl_internal_meta::ProtoMeta
    __protobuf_jl_internal_values::Dict{Symbol,Any}
    __protobuf_jl_internal_defaultset::Set{Symbol}

    function GetConfigurationRequest(; kwargs...)
        obj = new(meta(GetConfigurationRequest), Dict{Symbol,Any}(), Set{Symbol}())
        values = obj.__protobuf_jl_internal_values
        symdict = obj.__protobuf_jl_internal_meta.symdict
        for nv in kwargs
            fldname, fldval = nv
            fldtype = symdict[fldname].jtyp
            (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
            if fldval !== nothing
                values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
            end
        end
        obj
    end
end # mutable struct GetConfigurationRequest
const __meta_GetConfigurationRequest = Ref{ProtoMeta}()
function meta(::Type{GetConfigurationRequest})
    ProtoBuf.metalock() do
        if !isassigned(__meta_GetConfigurationRequest)
            __meta_GetConfigurationRequest[] = target = ProtoMeta(GetConfigurationRequest)
            allflds = Pair{Symbol,Union{Type,String}}[:name => AbstractString, :namespace => AbstractString]
            meta(target, GetConfigurationRequest, allflds, ProtoBuf.DEF_REQ, ProtoBuf.DEF_FNUM, ProtoBuf.DEF_VAL, ProtoBuf.DEF_PACK, ProtoBuf.DEF_WTYPES, ProtoBuf.DEF_ONEOFS, ProtoBuf.DEF_ONEOF_NAMES)
        end
        __meta_GetConfigurationRequest[]
    end
end
function Base.getproperty(obj::GetConfigurationRequest, name::Symbol)
    if name === :name
        return (obj.__protobuf_jl_internal_values[name])::AbstractString
    elseif name === :namespace
        return (obj.__protobuf_jl_internal_values[name])::AbstractString
    else
        getfield(obj, name)
    end
end

mutable struct GetConfigurationResponse <: ProtoType
    __protobuf_jl_internal_meta::ProtoMeta
    __protobuf_jl_internal_values::Dict{Symbol,Any}
    __protobuf_jl_internal_defaultset::Set{Symbol}

    function GetConfigurationResponse(; kwargs...)
        obj = new(meta(GetConfigurationResponse), Dict{Symbol,Any}(), Set{Symbol}())
        values = obj.__protobuf_jl_internal_values
        symdict = obj.__protobuf_jl_internal_meta.symdict
        for nv in kwargs
            fldname, fldval = nv
            fldtype = symdict[fldname].jtyp
            (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
            if fldval !== nothing
                values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
            end
        end
        obj
    end
end # mutable struct GetConfigurationResponse
const __meta_GetConfigurationResponse = Ref{ProtoMeta}()
function meta(::Type{GetConfigurationResponse})
    ProtoBuf.metalock() do
        if !isassigned(__meta_GetConfigurationResponse)
            __meta_GetConfigurationResponse[] = target = ProtoMeta(GetConfigurationResponse)
            allflds = Pair{Symbol,Union{Type,String}}[:configuration => Vector{UInt8}]
            meta(target, GetConfigurationResponse, allflds, ProtoBuf.DEF_REQ, ProtoBuf.DEF_FNUM, ProtoBuf.DEF_VAL, ProtoBuf.DEF_PACK, ProtoBuf.DEF_WTYPES, ProtoBuf.DEF_ONEOFS, ProtoBuf.DEF_ONEOF_NAMES)
        end
        __meta_GetConfigurationResponse[]
    end
end
function Base.getproperty(obj::GetConfigurationResponse, name::Symbol)
    if name === :configuration
        return (obj.__protobuf_jl_internal_values[name])::Vector{UInt8}
    else
        getfield(obj, name)
    end
end

mutable struct ListSubscriptionsResponse <: ProtoType
    __protobuf_jl_internal_meta::ProtoMeta
    __protobuf_jl_internal_values::Dict{Symbol,Any}
    __protobuf_jl_internal_defaultset::Set{Symbol}

    function ListSubscriptionsResponse(; kwargs...)
        obj = new(meta(ListSubscriptionsResponse), Dict{Symbol,Any}(), Set{Symbol}())
        values = obj.__protobuf_jl_internal_values
        symdict = obj.__protobuf_jl_internal_meta.symdict
        for nv in kwargs
            fldname, fldval = nv
            fldtype = symdict[fldname].jtyp
            (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
            if fldval !== nothing
                values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
            end
        end
        obj
    end
end # mutable struct ListSubscriptionsResponse
const __meta_ListSubscriptionsResponse = Ref{ProtoMeta}()
function meta(::Type{ListSubscriptionsResponse})
    ProtoBuf.metalock() do
        if !isassigned(__meta_ListSubscriptionsResponse)
            __meta_ListSubscriptionsResponse[] = target = ProtoMeta(ListSubscriptionsResponse)
            allflds = Pair{Symbol,Union{Type,String}}[:subscriptions => Base.Vector{Vector{UInt8}}]
            meta(target, ListSubscriptionsResponse, allflds, ProtoBuf.DEF_REQ, ProtoBuf.DEF_FNUM, ProtoBuf.DEF_VAL, ProtoBuf.DEF_PACK, ProtoBuf.DEF_WTYPES, ProtoBuf.DEF_ONEOFS, ProtoBuf.DEF_ONEOF_NAMES)
        end
        __meta_ListSubscriptionsResponse[]
    end
end
function Base.getproperty(obj::ListSubscriptionsResponse, name::Symbol)
    if name === :subscriptions
        return (obj.__protobuf_jl_internal_values[name])::Base.Vector{Vector{UInt8}}
    else
        getfield(obj, name)
    end
end

# service methods for Operator
const _Operator_methods = MethodDescriptor[
        MethodDescriptor("ComponentUpdate", 1, ComponentUpdateRequest, Channel{ComponentUpdateEvent}),
        MethodDescriptor("ListComponents", 2, ListComponentsRequest, ListComponentResponse),
        MethodDescriptor("GetConfiguration", 3, GetConfigurationRequest, GetConfigurationResponse),
        MethodDescriptor("ListSubscriptions", 4, ProtoBuf.google.protobuf.Empty, ListSubscriptionsResponse)
    ] # const _Operator_methods
const _Operator_desc = ServiceDescriptor("dapr.proto.operator.v1.Operator", 1, _Operator_methods)

Operator(impl::Module) = ProtoService(_Operator_desc, impl)

mutable struct OperatorStub <: AbstractProtoServiceStub{false}
    impl::ProtoServiceStub
    OperatorStub(channel::ProtoRpcChannel) = new(ProtoServiceStub(_Operator_desc, channel))
end # mutable struct OperatorStub

mutable struct OperatorBlockingStub <: AbstractProtoServiceStub{true}
    impl::ProtoServiceBlockingStub
    OperatorBlockingStub(channel::ProtoRpcChannel) = new(ProtoServiceBlockingStub(_Operator_desc, channel))
end # mutable struct OperatorBlockingStub

ComponentUpdate(stub::OperatorStub, controller::ProtoRpcController, inp::ComponentUpdateRequest, done::Function) = call_method(stub.impl, _Operator_methods[1], controller, inp, done)
ComponentUpdate(stub::OperatorBlockingStub, controller::ProtoRpcController, inp::ComponentUpdateRequest) = call_method(stub.impl, _Operator_methods[1], controller, inp)

ListComponents(stub::OperatorStub, controller::ProtoRpcController, inp::ListComponentsRequest, done::Function) = call_method(stub.impl, _Operator_methods[2], controller, inp, done)
ListComponents(stub::OperatorBlockingStub, controller::ProtoRpcController, inp::ListComponentsRequest) = call_method(stub.impl, _Operator_methods[2], controller, inp)

GetConfiguration(stub::OperatorStub, controller::ProtoRpcController, inp::GetConfigurationRequest, done::Function) = call_method(stub.impl, _Operator_methods[3], controller, inp, done)
GetConfiguration(stub::OperatorBlockingStub, controller::ProtoRpcController, inp::GetConfigurationRequest) = call_method(stub.impl, _Operator_methods[3], controller, inp)

ListSubscriptions(stub::OperatorStub, controller::ProtoRpcController, inp::ProtoBuf.google.protobuf.Empty, done::Function) = call_method(stub.impl, _Operator_methods[4], controller, inp, done)
ListSubscriptions(stub::OperatorBlockingStub, controller::ProtoRpcController, inp::ProtoBuf.google.protobuf.Empty) = call_method(stub.impl, _Operator_methods[4], controller, inp)

export ListComponentsRequest, ComponentUpdateRequest, ComponentUpdateEvent, ListComponentResponse, GetConfigurationRequest, GetConfigurationResponse, ListSubscriptionsResponse, Operator, OperatorStub, OperatorBlockingStub, ComponentUpdate, ListComponents, GetConfiguration, ListSubscriptions


text:
abstract type WrappedDateTime<: Base.Dates.AbstractTime end

struct UT <: WrappedDateTime
    value::DateTime

    function UT(dt::DateTime)
        fsecs = Base.Dates.datetime2unix(dt)
        isecs = floor(Int64, fsecs)
        ofs   = lcl_offset(isecs)
        fsecs += ofs
        new(Base.Dates.unix2datetime(fsecs))
    end
    UT() = new(utm_unwrapped())
end

struct LCL <: WrappedDateTime
    value::DateTime

    LCL(dt::DateTime) = new(dt)
    LCL() = new(now())
end

convert(::DateTime, dtm::UT)  = localtime(dtm.value)
convert(::UT, dtm::DateTime)  = ut(dtm)
convert(::DateTime, dtm::LCL)  = dtm.value
convert(::LCL, dtm::DateTime)  = LCL(dtm)
convert(::UT, dtm::LCL)  = ut(dtm.value)
convert(::LCL, dtm::UT)  = LCL(localtime(dtm.value))

#convert(::DateTime, dtm::UTC) = localtime(dtm.value)
#convert(::UTC, dtm::DateTime) = utc(dtm)
#convert(::UTC, dtm::UT) = utc(localtime(dtm))
#convert(::UT, dtm::UTC) = ut(localtime(dtm))

promote_rule(::DateTime, ::UT) = UT
promote_rule(::LCL, ::UT) = UT
promote_rule(::DateTime, ::LCL) = LCL

#promote_rule(::DateTime, ::UTC) = UTC
#promote_rule(::UT, ::UTC) = UTC

ut(dtm::DateTime) = UT(dtm)
ut() = UT()
ut(dtm::UT) = dtm
ut(dtm::LCL) = UT(dtm.value)

gmt(dtm::DateTime) = UT(dtm)
gmt() = UT()
gmt(dtm::UT) = dtm
gmt(dtm::LCL) = UT(dtm.value)

# dt as localtime --> ut (with leap seconds)
function utc(dt::DateTime)
    info("try ut($(dt)), utc requires leap seconds")
end
utc() = info("try ut(), utc requires leap seconds")
utc(dt::UT) = info("try ut(), utc requires leap seconds")
utc(dt::LCL) = info("try ut(), utc requires leap seconds")

# dt as ut --> localtime (without leap seconds)
function localtime(dt::DateTime)
    sec = floor(Int64, Base.Dates.datetime2unix(dt))
    sec = lcl_from_utmtime(sec)
    LCL(Base.Dates.unix2datetime( sec ))
end

#DateTime(dtm::UT) = localtime(dtm.value)
function localtime(dtm::UT)
    sec = Base.Dates.datetime2unix(dtm.value)
    sec = lcl_from_utmtime(sec)
    LCL(Base.Dates.unix2datetime( sec ))
end

localtime(dtm::LCL) = dtm
localtime() = LCL(Base.Dates.now())

for U in [:LCL, :UT]
  @eval begin
    $(U)(yr::T) where {T<:Integer} = $(U)(DateTime(yr))
    $(U)(yr::T,mo::T ) where {T<:Integer} = $(U)(DateTime(yr,mo))
    $(U)(yr::T,mo::T,dy::T) where {T<:Integer} = $(U)(DateTime(yr,mo,dy))
    $(U)(yr::T,mo::T,dy::T,hr::T) where {T<:Integer} =
      $(U)(DateTime(yr,mo,dy,hr))
    $(U)(yr::T,mo::T,dy::T,hr::T,mi::T) where {T<:Integer} =
      $(U)(DateTime(yr,mo,dy,hr,mi))
    $(U)(yr::T,mo::T,dy::T,hr::T,mi::T,sc::T) where {T<:Integer} =
      $(U)(DateTime(yr,mo,dy,hr,mi,sc))
    $(U)(yr::T,mo::T,dy::T,hr::T,mi::T,sc::T,ss::T) where {T<:Integer} =
      $(U)(DateTime(yr,mo,dy,hr,mi,sc,ss))
  end
end

# :Period, :DatePeriod, :TimePeriod

for fn in (:Year, :Month, :Week, :Day, :Hour, :Minute, :Second, :Millisecond)
    @eval begin
        convert(::Type{($fn)}, (dt::LCL)) = convert(($fn),(dt.value))
        convert(::Type{($fn)}, (dt::UT))  = convert(($fn),(dt.value))
        #convert(::($fn), (dt::UTC)) = convert(::($fn),(dt.value))
    end
end

for fn in (:yearmonthday, :yearmonth, :monthday, :year, :month,
           :week, :day, :hour, :minute, :second, :millisecond,
           :dayofmonth, :dayofweek, :isleapyear, :daysinmonth,
           :daysinyear, :dayofyear, :dayname, :dayabbr,
           :dayofweekofmonth, :daysofweekinmonth, :monthname,
           :monthabbr, :quarterofyear, :dayofquarter
          )
    @eval begin
        ($fn)(dt::LCL) = ($fn)(dt.value)
        ($fn)(dt::UT)  = ($fn)(dt.value)
        #($fn)(dt::UTC) = ($fn)(dt.value)
    end
end

for fn in [:firstdayofweek, :lastdayofweek,
           :firstdayofmonth, :lastdayofmonth, :firstdayofyear,
           :lastdayofyear, :firstdayofquarter, :lastdayofquarter
          ]
    @eval begin
        ($fn)(dt::LCL) = LCL(($fn)(dt.value))
        ($fn)(dt::UT)  = UT(($fn)(dt.value))
        #($fn)(dt::UTC) = ($fn)(dt.value)
    end
end

for fn in (:adjust, :tonext, :toprev, :tofirst, :tolast, :recur)
    @eval begin
      ($fn)(dt::LCL, args...) = UT(($fn)(dt.value, args...))
      ($fn)(dt::UT, args...)  = UT(($fn)(dt.value, args...))
    # ($fn)(dt::UTC, args...) = UT(($fn)(dt.value, args...))
    end
end

for U in (:LCL, :UT)
  @eval begin
    (-)(udt::($U), udt2::($U)) = (-)(udt.value, udt2.value)
    (-)(udt::($U), p::Period) = ($U)((-)(udt.value, p))
    Base.broadcast(::typeof(-), udt::($U), vec::Array{($U),1}) =
      [(-)(udt, i) for i in vec]
    Base.broadcast(::typeof(-), udt::($U), vec::Array{Period,1}) =
      [(-)(udt, i) for i in vec]
    Base.broadcast(::typeof(-), vec::Array{($U),1}, udt::($U)) =
      [(-)(i,udt) for i in vec]
    Base.broadcast(::typeof(-), vec::Array{($U),1}, p::Period) =
      [(-)(i,p) for i in vec]

    (+)(udt::($U), p::Period) = ($U)((+)(udt.value, p))
    (+)(p::Period, udt::($U)) = (+)(udt, p)
    Base.broadcast(::typeof(+), udt::($U), vec::Array{Period,1}) =
      [(+)(udt, i) for i in vec]
    Base.broadcast(::typeof(+), vec::Array{($U),1},p::Period) =
      [(+)(i, p) for i in vec]
  end
end

const ISOUniversalTimeFormat = DateFormat("yyyy-mm-ddTHH:MM:SS.sZ");
const ISOUnivCoordTimeFormat = DateFormat("yyyy-mm-dd HH:MM:SS.sZ");
const isoDateTimeFormat = DateFormat("yyyy-mm-dd HH:MM:SS.s");

function format(udt::UT, pattern::AbstractString, addUTC=true::Bool)
   s = format(udt.value, pattern)
end

format(udt::UT, fmt::Base.Dates.DateFormat) = format(udt.value, fmt)

function show(io::IO, dt::UT)
    dtm = dt.value
    str = string(string(dtm),"Z")
    # a = replace(a, "T", "𝘻") # using symbol
    print(io, str)
end

function show(io::IO, dt::LCL)
    dtm = dt.value
    secs = floor(Int64,Base.Dates.datetime2unix(dtm))
    utmofs = utm_offset(secs)
    hr = div(utmofs,3_600)
    mn = string(mod(utmofs,3_600))
    s,h = signbit(hr), string("0",string(abs(hr)))[end-1:end]
    m   = string("0",mn)[end-1:end]
    dtz = s ? string("-",h,":",m) : string("+",h,":",m)
    dtm = dt.value
    str = string(string(dtm),dtz)
    # a = replace(a, "T", "𝘻") # using symbol
    print(io, str)
end

# attempt to determine if this works with the local host
# Good reader, this is code to be avoided in almost any
# other circumstance; it three distinct ways, it intends
# to subvert the logic that makes this module sound.
#
function ok()
    ofs(dtm::UT) =
       UTime.lcl_offset(trunc(Int64,Dates.datetime2unix(dtm.value)))
    dofs(dtm1::UT,dtm2::UT)=
       fld(ofs(dtm1)-ofs(dtm2), 60)

    Jan1 = UT(DateTime(2000,1,1,0,0,0))
    Mar3 = UT(DateTime(2000,3,3,0,0,0))
    Jul1 = UT(DateTime(2000,7,1,0,0,0))
    Sep1 = UT(DateTime(2000,9,3,0,0,0))
    JanMar = dofs(Mar3,Jan1)
    JanJul = dofs(Jul1,Jan1)
    JanSep = dofs(Sep1,Jan1)
    MarJul = dofs(Jul1,Mar3)
    MarSep = dofs(Sep1,Mar3)
    JulSep = dofs(Sep1,Jul1)
    sumtest  = (JanMar+JanJul+JanSep+MarJul+MarSep+JulSep != 0)
    prodtest = (JanMar*JanJul*JanSep*MarJul*MarSep*JulSep == 0)
    sumtest & prodtest
end


text:
using StochasticDiffEq, DiffEqDevTools, DiffEqBase, Test
using DiffEqProblemLibrary.SDEProblemLibrary: importsdeproblems; importsdeproblems()
import DiffEqProblemLibrary.SDEProblemLibrary: prob_sde_linear
Random.seed!(100)
prob = prob_sde_linear

integrator = init(prob,EM(),dt=1//2^(4),tstops = [0.33])

for (u,t) in tuples(integrator)
  @show u,t
end

sol = solve(prob,EM(),dt=1//2^(4),tstops = [0.33])

@test 0.33 ∈ sol.t

sol = solve(prob,EM(),tstops = [0.33,0.80,1.0])

@test sol.t == [0.0,0.33,0.80,1.0]

sol = solve(prob,SRIW1(),tstops = [0.33])

@test 0.33 ∈ sol.t


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

struct FirewallRulesApi <: SwaggerApi
    client::Swagger.Client
end

"""

Creates or updates the specified firewall rule. During update, the firewall rule with the specified name will be replaced with this new firewall rule.
Param: resourceGroupName::String (required)
Param: accountName::String (required)
Param: firewallRuleName::String (required)
Param: parameters::FirewallRule (required)
Param: api_version::String (required)
Param: subscriptionId::String (required)
Return: FirewallRule
"""
function firewallRulesCreateOrUpdate(_api::FirewallRulesApi, resourceGroupName::String, accountName::String, firewallRuleName::String, parameters, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "PUT", FirewallRule, "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeStore/accounts/{accountName}/firewallRules/{firewallRuleName}", ["azure_auth"], parameters)
    Swagger.set_param(_ctx.path, "resourceGroupName", resourceGroupName)  # type String
    Swagger.set_param(_ctx.path, "accountName", accountName)  # type String
    Swagger.set_param(_ctx.path, "firewallRuleName", firewallRuleName)  # type String
    Swagger.set_param(_ctx.path, "subscriptionId", subscriptionId)  # type String
    Swagger.set_param(_ctx.query, "api-version", api_version)  # type String
    Swagger.set_header_accept(_ctx, ["application/json"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json"] : [_mediaType])
    Swagger.exec(_ctx)
end

"""

Deletes the specified firewall rule from the specified Data Lake Store account
Param: resourceGroupName::String (required)
Param: accountName::String (required)
Param: firewallRuleName::String (required)
Param: api_version::String (required)
Param: subscriptionId::String (required)
Return: Nothing
"""
function firewallRulesDelete(_api::FirewallRulesApi, resourceGroupName::String, accountName::String, firewallRuleName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "DELETE", Nothing, "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeStore/accounts/{accountName}/firewallRules/{firewallRuleName}", ["azure_auth"])
    Swagger.set_param(_ctx.path, "resourceGroupName", resourceGroupName)  # type String
    Swagger.set_param(_ctx.path, "accountName", accountName)  # type String
    Swagger.set_param(_ctx.path, "firewallRuleName", firewallRuleName)  # type String
    Swagger.set_param(_ctx.path, "subscriptionId", subscriptionId)  # type String
    Swagger.set_param(_ctx.query, "api-version", api_version)  # type String
    Swagger.set_header_accept(_ctx, ["application/json"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json"] : [_mediaType])
    Swagger.exec(_ctx)
end

"""

Gets the specified Data Lake Store firewall rule.
Param: resourceGroupName::String (required)
Param: accountName::String (required)
Param: firewallRuleName::String (required)
Param: api_version::String (required)
Param: subscriptionId::String (required)
Return: FirewallRule
"""
function firewallRulesGet(_api::FirewallRulesApi, resourceGroupName::String, accountName::String, firewallRuleName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "GET", FirewallRule, "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeStore/accounts/{accountName}/firewallRules/{firewallRuleName}", ["azure_auth"])
    Swagger.set_param(_ctx.path, "resourceGroupName", resourceGroupName)  # type String
    Swagger.set_param(_ctx.path, "accountName", accountName)  # type String
    Swagger.set_param(_ctx.path, "firewallRuleName", firewallRuleName)  # type String
    Swagger.set_param(_ctx.path, "subscriptionId", subscriptionId)  # type String
    Swagger.set_param(_ctx.query, "api-version", api_version)  # type String
    Swagger.set_header_accept(_ctx, ["application/json"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json"] : [_mediaType])
    Swagger.exec(_ctx)
end

"""

Lists the Data Lake Store firewall rules within the specified Data Lake Store account.
Param: resourceGroupName::String (required)
Param: accountName::String (required)
Param: api_version::String (required)
Param: subscriptionId::String (required)
Return: DataLakeStoreFirewallRuleListResult
"""
function firewallRulesListByAccount(_api::FirewallRulesApi, resourceGroupName::String, accountName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "GET", DataLakeStoreFirewallRuleListResult, "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeStore/accounts/{accountName}/firewallRules", ["azure_auth"])
    Swagger.set_param(_ctx.path, "resourceGroupName", resourceGroupName)  # type String
    Swagger.set_param(_ctx.path, "accountName", accountName)  # type String
    Swagger.set_param(_ctx.path, "subscriptionId", subscriptionId)  # type String
    Swagger.set_param(_ctx.query, "api-version", api_version)  # type String
    Swagger.set_header_accept(_ctx, ["application/json"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json"] : [_mediaType])
    Swagger.exec(_ctx)
end

"""

Updates the specified firewall rule.
Param: resourceGroupName::String (required)
Param: accountName::String (required)
Param: firewallRuleName::String (required)
Param: api_version::String (required)
Param: subscriptionId::String (required)
Param: parameters::UpdateFirewallRuleParameters
Return: FirewallRule
"""
function firewallRulesUpdate(_api::FirewallRulesApi, resourceGroupName::String, accountName::String, firewallRuleName::String, api_version::String, subscriptionId::String; parameters=nothing, _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "PATCH", FirewallRule, "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeStore/accounts/{accountName}/firewallRules/{firewallRuleName}", ["azure_auth"], parameters)
    Swagger.set_param(_ctx.path, "resourceGroupName", resourceGroupName)  # type String
    Swagger.set_param(_ctx.path, "accountName", accountName)  # type String
    Swagger.set_param(_ctx.path, "firewallRuleName", firewallRuleName)  # type String
    Swagger.set_param(_ctx.path, "subscriptionId", subscriptionId)  # type String
    Swagger.set_param(_ctx.query, "api-version", api_version)  # type String
    Swagger.set_header_accept(_ctx, ["application/json"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json"] : [_mediaType])
    Swagger.exec(_ctx)
end

export firewallRulesCreateOrUpdate, firewallRulesDelete, firewallRulesGet, firewallRulesListByAccount, firewallRulesUpdate


text:
### Functions for Converting a Route to a Pose Graph ###
### Ted Steiner ###
### August 2014 ###

# Get truth poses
function getPoses2D( nodes::Dict{Int,OpenStreetMap.ENU}, route )
    poses = Pose2D[]

    # Add initial pose
    push!(poses,Pose2D(nodes[route[1]].east,nodes[route[1]].north,0.0))

    for k = 1:length(route)-1
        push!(poses,getPose2D(nodes,route[k],route[k+1]))
    end

    # Add final pose
    push!(poses,Pose2D(nodes[route[end]].east,nodes[route[end]].north,0.0))

    return poses
end

# Pose of node A, using orientation from A -> B
function getPose2D( nodes::Dict{Int,OpenStreetMap.ENU}, A::Int, B::Int )
    theta = atan2(nodes[B].north-nodes[A].north,nodes[B].east-nodes[A].east)
    return Pose2D( nodes[A].east, nodes[A].north, theta )
end

# Generate odometry measurements between poses
function getPoseOdometry( route, poses, noise_odom )
    odom = BetweenFactor[]

    info_odom = getInfoMatrix(noise_odom)

    for k = 0:length(poses)-2
        s = k
        t = k+1
        nodeT = route[t]

        if k == 0
            push!(odom,BetweenFactor(s,t,Meas2D(0,0,poses[t+1].theta),info_odom,0,nodeT))
        else
            nodeS = route[s]
            push!(odom,BetweenFactor(s,t,getPoseMeas2D(poses[s+1],poses[t+1],noise_odom),info_odom,nodeS,nodeT))
        end
    end

    return odom
end

# Combine odometry measurements with loop closures given anchors and poses
function getMeasurements( route,
                          poses,
                          anchors::Array{Int,1},
                          odometry_factors::Array{BetweenFactor,1},
                          noise_loop )

    anchor_sets = Array{Int,1}[]
    push!(anchor_sets,anchors)
    return getMeasurements(route,poses,anchor_sets,odometry_factors,noise_loop)[1]
end

# Generate measurement sets for anchor sets
# Any loop closure measurement present in mulitple measurement sets will have
# the same noise, enabling comparison of anchor sets
function getMeasurements( route,
                          poses,
                          anchors::Array{Array{Int,1},1},
                          odometry_factors::Array{BetweenFactor,1},
                          noise_loop )

    all_anchors = Int[]
    meas = Array{BetweenFactor,1}[]
    info_loop = getInfoMatrix(noise_loop)

    for a in anchors
        push!(all_anchors,a...)
        push!(meas,BetweenFactor[])
    end
    all_anchors = Set(all_anchors...)

    for k = 0:length(poses)-2
        for a = 1:length(anchors)
            push!(meas[a],odometry_factors[k+1])
        end

        if k > 10
            t = k+1
            nodeT = route[t]
            if nodeT in all_anchors
                for kk = 1:k-5
                    if route[kk] == nodeT
                        # Generate loop-closure constraint
                        s = kk
                        nodeS = route[kk]

                        factor = BetweenFactor(s,t,getAnchorPoseMeas2D(poses[s+1],poses[t+1],noise_loop),info_loop,nodeS,nodeT)

                        for a = 1:length(anchors)
                            if route[t] in anchors[a]
                                push!(meas[a],factor)
                            end
                        end

                        break # Add constraint only to original pose
                    end
                end
            end
        end
    end

    return meas
end

# For use when factors are already computed
function getMeasurements( route,
                          poses,
                          anchors::Array{Array{Int,1},1},
                          odometry_factors::Array{BetweenFactor,1},
                          loop_factors::Dict{(Int,Int),BetweenFactor},
                          prior_meas::Dict{Int,Meas2D}=Dict{Int,Meas2D}(),
                          prior_inf::Inf2D=Inf2D(50,0,0,50,0,100) )

    all_anchors = Int[]
    meas = Array{Factor,1}[]

    for a in anchors
        push!(all_anchors,a...)
        push!(meas,BetweenFactor[])
    end
    all_anchors = Set(all_anchors...)

    for k = 0:length(poses)-2
        # Odometry Factors
        for a = 1:length(anchors)
            push!(meas[a],odometry_factors[k+1])
        end

        if k > 10
            t = k+1
            if route[t] in all_anchors

                # Loop-closure Factors
                loop_found = false
                for s = 1:k-5
                    if route[s] == route[t]
                        loop_found = true
                        # Find and add loop-closure constraint
                        if haskey(loop_factors,(s,t))
                            factor = loop_factors[(s,t)]
                            for a = 1:length(anchors)
                                if route[t] in anchors[a]
                                    push!(meas[a],factor)
                                end
                            end
                        else
                            warn("Loop closure missing between poses $s and $t.")
                        end

                        break # Add constraint only to original pose
                    end
                end

                # Prior Factors: Only if first occurence of this node
                if !loop_found && haskey(prior_meas,route[t])
                    factor = PriorFactor(t,prior_meas[route[t]],prior_inf,route[t])
                    for a = 1:length(anchors)
                        if route[t] in anchors[a]
                            push!(meas[a],factor)
                        end
                    end
                end
            end
        end
    end

    return meas
end

# Generate loop-closure measurements and return as dictionary
# This is used to precompute measurements when the actual anchor sets are not yet known
function getLoopFactors( route,
                         poses,
                         anchors::Vector{Int},
                         noise_loop )

    factors = Dict{(Int,Int),BetweenFactor}()
    info_loop = getInfoMatrix(noise_loop)
    all_anchors = Set(anchors)

    for k = 0:length(poses)-2
        if k > 10
            t = k+1
            nodeT = route[t]
            if nodeT in all_anchors
                for kk = 1:k-5
                    if route[kk] == nodeT
                        # Generate loop-closure constraint
                        s = kk
                        nodeS = route[kk]

                        factors[(s,t)] = BetweenFactor(s,t,getAnchorPoseMeas2D(poses[s+1],poses[t+1],noise_loop),info_loop,nodeS,nodeT)

                        break # Add constraint only to original pose
                    end
                end
            end
        end
    end

    return factors
end

function getPriorMeasurements( route, poses, anchors::Vector{Int}, noise_prior )
    priors = Dict{Int,Meas2D}()

    for a in anchors
        for k = 1:length(route)
            if route[k] == a
                priors[a] = getPriorMeas2D(poses[k],noise_prior)
                break
            end
        end
    end

    return priors
end

function getPriorMeas2D( pose, meas_cov )
    dx = pose.x
    dy = pose.y
    dt = pose.theta

    m = [dx,dy,dt] + meas_cov*randn(3)

    return Meas2D(m[1],m[2],m[3])
end

function getPoseMeas2D( pose0, pose1, meas_cov=zeros(3) )
    dx = sqrt((pose1.x - pose0.x)^2 + (pose1.y - pose0.y)^2)
    dy = 0.0
    dt = pose1.theta - pose0.theta

    m = [dx,dy,dt]

    return Meas2D(m[1],m[2],m[3])
end

function getAnchorPoseMeas2D( pose0, pose1, meas_cov=zeros(3) )
    dx = 0.0
    dy = 0.0
    dt = pose1.theta - pose0.theta

    m = [dx,dy,dt] + meas_cov*randn(3)

    return Meas2D(m[1],m[2],m[3])
end

function getInfoMatrix( noise )
    I = inv(noise)
    return Inf2D(I[1,1],I[1,2],I[1,3],I[2,2],I[2,3],I[3,3])
end


text:
using Crystalline: TEST_αβγ

function lattice2mpb(flat::AbstractFourierLattice)
    orbits = getorbits(flat); coefs = getcoefs(flat)
    Nterms = sum(length, coefs)
    orbits_mpb_vec = Vector{String}(undef, Nterms)
    coefs_mpb_vec  = Vector{String}(undef, Nterms)
    idx = 1
    for (G, c) in zip(Iterators.flatten(orbits), Iterators.flatten(coefs))
        orbits_mpb_vec[idx] = "(vector3"*mapfoldl(x-> " "*string(x), *, G)*")"
        c_re = real(c); c_im = imag(c);
        coefs_mpb_vec[idx]  = string(real(c))*signaschar(c_im)*string(abs(c_im))*"i"
        idx += 1
    end
    orbits_mpb = "(list"*mapfoldl(x->" "*x, *, orbits_mpb_vec)*")"
    coefs_mpb  = "(list"*mapfoldl(x->" "*x, *, coefs_mpb_vec)*")"
    return orbits_mpb, coefs_mpb
end

function mpb_calcname!(io, dim, sgnum, id, res, runtype="all")
    write(io, "dim",  string(dim),
              "-sg",  string(sgnum),
              "-",    string(id),
              "-res", string(res))
    if runtype != "all"
        write(io, "-", runtype)
    end
    return nothing
end
function mpb_calcname(dim, sgnum, id, res, runtype="all")
    io = IOBuffer()
    mpb_calcname!(io, dim, sgnum, id, res, runtype)
    return String(take!(io))
end
mpb_calcname!(io, dim, sgnum, id::Nothing, res, runtype="all") = nothing
mpb_calcname(io, dim, sgnum, id::Nothing, res, runtype="all") = nothing

function _vec2list(io::IO, f, vs::AbstractVector)
    write(io, "(list")
    for v in vs
        print(io, ' ', f(v))
    end
    write(io, ')')
    return io
end
_vec2list(io::IO, vs::AbstractVector) = _vec2list(io, identity, vs)
_vec2list(f, vs::AbstractArray) = String(take!(_vec2list(IOBuffer(), f, vs)))
_vec2list(vs::AbstractArray) = _vec2list(identity, vs)

function _vec2vector3(v::AbstractVector)
    length(v) > 3 && throw(DomainError(v, "A vector3 must be either one-, two-, or three-dimensional"))

    return "(vector3 "*join(v, ' ')*')'
end

function _mat2matrix3x3(m::SMatrix{D,D,<:Real}) where D
    if D == 1     # extend 1D to 3D
        m′ = one(MMatrix{3,3,eltype(m)})
        m′[1,1] = only(m)
        m = SMatrix(m′)
    elseif D == 2 # extend 2D to 3D
        m = hcat(vcat(m, (@SVector [0,0])'), @SVector[0,0,1])
    elseif D ≠ 3
        throw(DomainError(m, "conversion to matrix3x3 only possible for matrices of size (1,1), (2,2), or (3,3)"))
    end

    io = IOBuffer()
    write(io, "(matrix3x3")
    for i in 1:3
        write(io, ' ', _vec2vector3(@view m[:,i]))
    end
    write(io, ')')
    return String(take!(io))
end

"""
    prepare_mpbcalc!(...)

Formats a set of parameters that uniquely specify an MPB calculation, given a
space group number `sgnum`, a Fourier lattice `flat`, a DirectBasis `Rs`, a filling
fraction `filling` for `flat`, interior and exterior (above, below the contour)
permittivities `εin` and `εout`, as well as a list of k-vectors `kvs`, an
identifying tag `id` (to label the calculation for book-keeping purposes), a
resolution for the MPB calculation `res`, and a selection of calculation type
`runtype` ("all", "te", or "tm"). The results are written to requested IO `io`.

Our preferred choice is to write these parameters to a bash file, with a name
generated by the `mpb_calcname(...)` method.

The options are expected to be fed to the `fourier-lattice.ctl` file, e.g. through
a bash script of the following kind:
```sh
    IFS=\$'\\n'; # stop command-substitutions from word-splitting at space

    PATH_TO_MPB_EXECUTABLE \\
        (cat \${calcname}.sh)
        ctl/fourier-lattice.ctl 2>&1 | tee logs/\${calcname}.log

    unset IFS; # restore usual command-substitution word-splitting practice
```
where `PATH_TO_MPB_EXECUTABLE` is the path to the MPB executable.
Locally, in `mpb-ctl` we have a file `run-fourier-lattice.sh` which performs the
above, with `calcname` specified as an input parameter (assumed to be a subfolder
`/input/`).
"""
function prepare_mpbcalc!(
            io::IO,
            sgnum::Integer,
            flat::AbstractFourierLattice{D},
            Rs::AbstractVector{<:AbstractVector},
            filling::Union{Real, Nothing}=0.5, εin::Real=10.0, εout::Real=1.0,
            runtype::String="all";
            # kwargs
            id=1,
            res::Integer=32,
            kvs::Union{Nothing, AbstractString, AbstractVector{<:AbstractVector{<:Real}}}=nothing,
            lgs::Union{Nothing, AbstractVector{LittleGroup{D}}}=nothing,
            nbands::Union{Nothing, Integer}=nothing,
            isoval::Union{Nothing, Real}=nothing,
            # TODO: remove below kwarg (here for deprecation of `kvecs` -> `kvs` kwarg)
            kvecs::Union{Nothing, AbstractString, AbstractVector{<:AbstractVector{<:Real}}}=nothing
            ) where D

    (kvs === nothing && kvecs !== nothing) && (kvs = kvecs) # TODO: remove with `kvecs` kwarg

    # --- prep work to actually call mpb ---
    calcname = mpb_calcname(D, sgnum, id, res, runtype)
    rvecs = _vec2list(_vec2vector3, Rs)
    uc_gvecs, uc_coefs = lattice2mpb(flat)
    if filling !== nothing
        uc_level = filling2isoval(flat, filling)
    elseif isoval !== nothing
        uc_level = isoval
    else
        throw(DomainError((filling, isoval), "Either filling or isoval must be a real number"))
    end
    if filling !== nothing && isoval !== nothing
        throw(DomainError((filling, isoval), "Either filling or isoval must be nothing"))
    end

    # prepare and write all runtype, structural, and identifying inputs
    print(io, # run-type ("all", "te", or "tm")
              "run-type", "=",  "\"", runtype,  "\"",  "\n",
              # dimension, space group, and resolution
              "dim",      "=",        D,               "\n",
              "sgnum",    "=",        sgnum,           "\n",
              "res",      "=",        res,             "\n",
              # crystal (basis vectors)
              "rvecs",    "=",        rvecs,           "\n",
              # unitcell/lattice shape
              "uc-gvecs", "=",        uc_gvecs,        "\n",
              "uc-coefs", "=",        uc_coefs,        "\n",
              "uc-level", "=",        uc_level,        "\n",
              # permittivities
              "epsin",    "=",        εin,             "\n",
              "epsout",   "=",        εout,            "\n")

    if calcname !== nothing && !isempty(calcname)
        println(io, "prefix", "=", "\"", calcname, "\"")
    end

    if nbands !== nothing # number of bands to solve for (otherwise default to .ctl choice)
        println(io, "nbands", "=", nbands)
    end

    # prepare and write k-vecs and possibly also little group operations
    if lgs !== nothing
        # if `lgs` is supplied, we interpret it as a request to do symmetry eigenvalue
        # calculations at requested little group k-points
        kvs !== nothing && throw(ArgumentError("One of `kvs` or `lgs` must be nothing"))
        kvs = write_lgs_to_mpb!(io, lgs)
        println(io)
    end

    # write `kvs` (if they are not nothing; we may not always want to give `kvs` explicitly,
    #              e.g. for berry phase calculations); note that we write them as "kvecs"
    #              rather than "kvs" for backwards compatibility with our .ctl files
    write(io, "kvecs", "=")
    if kvs !== nothing
        if kvs isa AbstractString
            write(io, "\"", kvs, "\"")
        elseif kvs isa AbstractVector{<:AbstractVector{<:Real}}
            _vec2list(io, _vec2vector3, kvs)
        else
            error("incompatible type for `kvs` ($(typeof(kvs)))")
        end
    else
        # easier just to write an empty string than nothing; otherwise we have to bother
        # with figuring out how to remove an empty newline at the end of the file
        write(io, "(list)")
    end

    return nothing
end

function prepare_mpbcalc(sgnum::Integer, flat::AbstractFourierLattice{D},
            Rs::DirectBasis{D},
            filling::Union{Real, Nothing}=0.5, εin::Real=10.0, εout::Real=1.0,
            runtype::String="all";
            # kwargs
            id=1,
            res::Integer=32,
            kvs::Union{Nothing, AbstractString, AbstractVector{<:AbstractVector{<:Real}}}=nothing,
            lgs::Union{Nothing, AbstractVector{LittleGroup{D}}}=nothing,
            nbands::Union{Nothing, Integer}=nothing,
            isoval::Union{Nothing, Real}=nothing,
            # TODO: remove below kwarg (here for deprecation of `kvecs` -> `kvs` kwarg)
            kvecs::Union{Nothing, AbstractString, AbstractVector{<:AbstractVector{<:Real}}}=nothing
            ) where D
    io = IOBuffer()
    prepare_mpbcalc!(io, sgnum, flat, Rs, filling, εin, εout, runtype;
                         res, id, kvs, lgs, nbands, isoval, kvecs)
    return String(take!(io))
end

# TODO: Maybe remove this method?
#       Only parts worth keeping are the matching_littlegroups+primitivize parts...
function gen_symeig_mpbcalc(sgnum, D, εin::Real=10.0, εout::Real=1.0; res::Integer=32, id=1)
    D ∉ (1,2,3) && _throw_invaliddim(D)

    brs  = bandreps(sgnum, allpaths=false, spinful=false, timereversal=true)
    lgs  = matching_littlegroups(brs)

    cntr = centering(sgnum, D)
    flat = modulate(levelsetlattice(sgnum, D, (1,1,1)))
    Rs   = directbasis(sgnum, D)

    # go to a primitive basis (the lgs from ISOTROPY do not include operations that are
    # equivalent in a primitive basis, so we _must_ go to the primitive basis)
    lgs′  = primitivize.(lgs)
    flat′ = primitivize(flat, cntr)
    Rs′   = primitivize(Rs, cntr)

    prepare_mpbcalc(sgnum, flat′, Rs′, εin, εout; res=res, lgs=lgs′, id=id)
end

function write_lgs_to_mpb!(io::IO, lgs::AbstractVector{<:LittleGroup{D}}) where D
    # build a unique set of all SymOperations across `lgs` and then find the indices
    # into this set for each lg
    ops = unique(Iterators.flatten(operations.(lgs)))
    idxs2ops = [[findfirst(==(op), ops) for op in operations(lg)] for lg in lgs]

    # write little group symmetry operations at each k-point (as indexing list of lists)
    write(io, "Ws",     "=");  _vec2list(io, _mat2matrix3x3∘rotation,  ops); println(io)
    write(io, "ws",     "=");  _vec2list(io, _vec2vector3∘translation, ops); println(io)
    write(io, "opidxs", "=");  _vec2list(io, _vec2list, idxs2ops);

    # define the k-points across `lgs`, evaluated with (α,β,γ) = TEST_αβγ
    αβγ   = length(TEST_αβγ) == D ? TEST_αβγ : TEST_αβγ[1:D]
    kvs = map(lg->position(lg)(αβγ), lgs)
    # ... does not print a newline after last line; should be added by callee if relevant

    return kvs
end

"""
    lattice_from_mpbparams(filepath::String)

This will load an input file with path `filepath` that was previously created by
`prepare_mpbcalc(!)` and return the associated lattice as Julia objects.

Output:
```jl
    Rs::DirectBasis,
    flat::ModulatedFourierLattice,
    isoval::Float64,
    epsin::Float64,
    epsout::Float64
    kvs::Vector{SVector{D, Float64}}
```

Note that `flat` does not retain information about orbit groupings, since we flatten the
orbits into a single vector in `lattice2mpb`. This doesn't matter as we typically just want
to plot the saved lattice (see `plot_lattice_from_mpbparams` from `compat/pyplot.jl`).
"""
function lattice_from_mpbparams(io::IO)

    # --- dimension ---
    readuntil(io, "dim=")
    D = parse(Int64, readline(io))

    # --- basis vectors ---
    rewinding_readuntil(io, "rvecs=")
    vecs = Tuple(Vector{Float64}(undef, D) for _ in 1:D)
    for R in vecs
        readuntil(io, "(vector3 ")
        coords = split.(readuntil(io, ')'))
        R .= parse.(Ref(Float64), coords)
    end
    Rs = DirectBasis{D}(vecs...)

    # --- ("flattened") orbits ---
    rewinding_readuntil(io, "uc-gvecs=")
    gvecs = Vector{SVector{D, Int64}}()
    while true
        readuntil(io, "(vector3 ")
        coords = split.(readuntil(io, ')'))
        next_gvec = parse.(Ref(Int64), coords)
        push!(gvecs, next_gvec)
        (read(io, Char) == ')') && break # look for a closing (double) parenthesis to match the assumed opening "(list "
    end

    # --- ("flattened") orbit coefficients ---
    rewinding_readuntil(io, "uc-coefs=")
    readuntil(io, "(list ")
    gcoefs = Vector{ComplexF64}(undef, length(gvecs))
    for n in eachindex(gcoefs)
        gcoefs[n] = parse(ComplexF64, readuntil(io, x -> isspace(x) || x==')'))
    end

    # --- ("flattened") Fourier Lattice ---
    # note that we've lost info about orbit groupings (since we flatten on exporting
    # to mpb in lattice2mpb(...)) but it doesn't matter much, as we only ever need
    # to reload these to see the lattice itself.
    flat = ModulatedFourierLattice{D}([gvecs], [gcoefs])

    # --- iso-level ---
    rewinding_readuntil(io, "uc-level=")
    isoval = parse(Float64, readline(io))

    # --- epsilon values ---
    rewinding_readuntil(io, "epsin=")
    epsin = tryparse(Float64, readline(io))
    rewinding_readuntil(io, "epsout=")
    epsout = tryparse(Float64, readline(io))

    # --- k-vectors ---
    kvs = kvecs_from_mpbparams(io, Val(D))

    return Rs, flat, isoval, epsin, epsout, kvs
end
lattice_from_mpbparams(filepath::String) = open(filepath) do io; lattice_from_mpbparams(io); end

function kvecs_from_mpbparams(io::IO, ::Val{D}) where D
    rewinding_readuntil(io, "kvecs=")
    mark(io)
    # if kvecs is a not string marked by "(vector3 ...)", interpret as a list points
    if read(io, Char) !== '"'
        reset(io)
        kvs = SVector{D, Float64}[]
        while true
            readuntil(io, "(vector3 ")
            coords = split(readuntil(io, ')'))
            next_kv = parse.(Ref(Float64), coords)
            push!(kvs, SVector{D,Float64}(next_kv[1:D]))
            (read(io, Char) == ')') && break # look for a closing (double) parenthesis to match the assumed opening "(list "
        end
    else # kvs is a string, interpret as filename in same directory as io's "origin"
        ioname = io.name
        kvsfile = readuntil(io, "\"")
        if ioname[1:6] == "<file "
            dir = dirname(ioname[7:end-1])
            kvs = SVector{D, Float64}[]
            open(dir*"/"*kvsfile) do ioᵏ
                # assume a format "((0.0 0.1 0.2) (0.2 0.3 .4) ... (.3 .1 .2) )" [note the space at the end]
                (read(ioᵏ, Char) == '(' && read(ioᵏ, Char) == '(') || throw("Unexpected format of kvecs entry")
                while true
                    coords = split(readuntil(ioᵏ, ")"))
                    next_kv = parse.(Ref(Float64), coords)
                    push!(kvs, SVector{D,Float64}(next_kv[1:D]))
                    (read(ioᵏ, Char) == ' ' && read(ioᵏ, Char) == '(') || break
                end
            end
        else
            return nothing
        end
    end

    return kvs
end
function kvecs_from_mpbparams(filepath::String, Dᵛ::Val{D}=Val(3)) where D
    open(filepath) do io
        kvecs_from_mpbparams(io, Dᵛ)
    end
end
# type-unstable variants
kvecs_from_mpbparams(filepath::String, D::Integer) = kvecs_from_mpbparams(filepath, Val(D))
kvecs_from_mpbparams(io::IO, D::Integer) = kvecs_from_mpbparams(io, Val(D))

function rewinding_readuntil(io::IO, str::AbstractString)
    readuntil(io, str)
    # we try to be robust to arbitrary ordering of input (otherwise we must assume and
    # commit to a fixed order of parameters in the input), so we allow the stream to be
    # reset to its beginnings if we don't find what we're looking for in the first place
    if eof(io); seekstart(io); readuntil(io, str); end # try to be robust to arbitrary ordering

    nothing
end


text:
include("mds_metric.jl")
include("output.jl")
include("interpolate.jl")

data = contact_freq_to_distance_matrix("data_fish/combined_You_Pro_merged_chr4_arm1.csv", scale=10, exponent=1/3)
coords = mds_metric(data)
interp_coords = interp_3d(coords, 10)
output_txt(coords, "pro_shortest_paths_exact.txt")
output_txt(interp_coords, "interp_pro_shortest_paths_exact.txt")
#output_pdb(coords, "pro_shortest_paths_exact.pdb")


text:
function ShortPeriodicsInterpolatedCoefficient(arg0::jint)
    return ShortPeriodicsInterpolatedCoefficient((jint,), arg0)
end

function add_grid_point(obj::ShortPeriodicsInterpolatedCoefficient, arg0::AbsoluteDate, arg1::Vector{jdouble})
    return jcall(obj, "addGridPoint", void, (AbsoluteDate, Vector{jdouble}), arg0, arg1)
end

function clear_history(obj::ShortPeriodicsInterpolatedCoefficient)
    return jcall(obj, "clearHistory", void, ())
end

function value(obj::ShortPeriodicsInterpolatedCoefficient, arg0::AbsoluteDate)
    return jcall(obj, "value", Vector{jdouble}, (AbsoluteDate,), arg0)
end


text:
# script to install required packages

module Setup
    using Pkg

    packages = [
        :PackageCompiler, :PyCall, :PyPlot,
        :Plots, :DataFrames, :CSV, :Test,
        :StatsPlots, :Statistics, :FreqTables,
        :NamedArrays, :Distributions, :LinearAlgebra,
        :StatsBase, :PDMats, :Combinatorics, :SpecialFunctions
    ]

    function install_packages()
        for pkg in packages
            Pkg.add(String(pkg))
        end
    end

    function update_packages()
        for pkg in packages
            Pkg.update(String(pkg))
        end
    end
end

max_stars_repo_name: ShisatoYano/JuliaAutonomy

max_issues_repo_name: ShisatoYano/JuliaAutonomy

max_forks_repo_name: ShisatoYano/JuliaAutonomy


text:
# `CSV.readline(io::IO, q='"', e='\\', buf::IOBuffer=IOBuffer())` => `String`
str = "field1,field2,\"quoted \\\"field with \n embedded newline\",field3"
io = IOBuffer(str)
@test CSV.readline(io) == str
io = IOBuffer(str * "\n" * str * "\r\n" * str)
@test CSV.readline(io) == str * "\n"
@test CSV.readline(io) == str * "\r\n"
@test CSV.readline(io) == str

# `CSV.readline(source::CSV.Source)` => `String`
strsource = CSV.Source(IOBuffer(str); header=["col1","col2","col3","col4"])
@test CSV.readline(strsource) == str

# `CSV.readsplitline(io, d=',', q='"', e='\\', buf::IOBuffer=IOBuffer())` => `Vector{String}`
spl = [CSV.RawField("field1", false),
       CSV.RawField("field2", false),
       CSV.RawField("quoted \\\"field with \n embedded newline", true),
       CSV.RawField("field3", false)]
io = IOBuffer(str)
@test CSV.readsplitline(io) == spl
io = IOBuffer(str * "\n" * str * "\r\n" * str)
@test CSV.readsplitline(io) == spl
@test CSV.readsplitline(io) == spl
@test CSV.readsplitline(io) == spl

@testset "empty fields" begin
    str2 = "field1,,\"\",field3,"
    spl2 = [CSV.RawField("field1", false),
           CSV.RawField("", false),
           CSV.RawField("", true),
           CSV.RawField("field3", false),
           CSV.RawField("", false)]
    ioo = IOBuffer(str2)
    @test CSV.readsplitline(ioo) == spl2
end

# `CSV.readsplitline(source::CSV.Source)` => `Vector{String}`
strsource = CSV.Source(IOBuffer(str); header=["col1","col2","col3","col4"])
@test CSV.readsplitline(strsource) == spl

# `CSV.countlines(io::IO, quotechar, escapechar)` => `Int`
@test CSV.countlines(IOBuffer(str)) == 1
@test CSV.countlines(IOBuffer(str * "\n" * str)) == 2

# `CSV.countlines(source::CSV.Source)` => `Int`
intsource = CSV.Source(IOBuffer(str); header=["col1","col2","col3","col4"])
@test CSV.countlines(intsource) == 1

@testset "misformatted CSV lines" begin
    @testset "missing quote" begin
        str1 = "field1,field2,\"quoted \\\"field with \n embedded newline,field3"
        io2 = IOBuffer(str1)
        @test_throws CSV.ParsingException CSV.readsplitline(io2)
    end

    @testset "misplaced quote" begin
        str1 = "fi\"eld1\",field2,\"quoted \\\"field with \n embedded newline\",field3"
        io2 = IOBuffer(str1)
        @test_throws CSV.ParsingException CSV.readsplitline(io2)

        str2 = "field1,field2,\"quoted \\\"field with \n\"\" embedded newline\",field3"
        io2 = IOBuffer(str2)
        @test_throws CSV.ParsingException CSV.readsplitline(io2)

        str3 = "\"field\"1,field2,\"quoted \\\"field with \n embedded newline\",field3"
        io2 = IOBuffer(str3)
        @test_throws CSV.ParsingException CSV.readsplitline(io2)
    end
end


text:
primitive type Code 32 end

Code(x::Integer) = reinterpret(Code, convert(UInt32, x))
Base.UInt32(x::Code) = reinterpret(UInt32, x)

Base.show(io::IO, c::Code) = print(io, UInt32(c))
Base.print(io::IO, c::Code) = print(io, UInt32(c))

Base.isless(i::Real, c::Code) = (UInt32(c) > i)
Base.isless(c::Code, i::Real) = (UInt32(c) < i)

macro name(c)
	string(c)
end

const OK = Code(0)
export OK

const Canceled = Code(1)
export Canceled

const Unknown = Code(2)
export Unknown

const InvalidArgument = Code(3)
export InvalidArgument

const DeadlineExceeded = Code(4)
export DeadlineExceeded

const NotFound = Code(5)
export NotFound

const AlreadyExists = Code(6)
export AlreadyExists

const PermissionDenied = Code(7)
export PermissionDenied

const ResourceExhausted = Code(8)
export ResourceExhausted

const FailedPrecondition = Code(9)
export FailedPrecondition

const Aborted = Code(10)
export Aborted

const OutOfRange = Code(11)
export OutOfRange

const Unimplemented = Code(12)
export Unimplemented

const Internal = Code(13)
export Internal

const Unavailable = Code(14)
export Unavailable

const DataLoss = Code(15)
export DataLoss

const Unauthenticated = Code(16)
export Unauthenticated

struct gRPCException <: Exception
	code::Code
	message::String

	gRPCException(code::Code, message::String) = begin
		if code > 16 || code < 0
			code = Unknown
		end
		new(code, message)
	end
end

gRPCException(;code::Code, message::String) = gRPCException(code, message)
gRPCException(message::String) = gRPCException(Internal, message)

wrap(ex::gRPCException) = ex
wrap(ex::Exception) = gRPCException(string(ex))


text:
using Test
using EzXML
using GraphIO.GEXF

@testset "GEXF" begin
    for g in values(allgraphs)
        write_test(GEXFFormat(), g)
    end
end


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

name = "gb"
version = v"0.17.0"

# Collection of sources required to complete build
sources = [
    GitSource("https://github.com/ederc/gb.git", "4b579882b5dccf8fbf2294838d34da35ae6adbb7"),
    DirectorySource("./bundled")
]

# Bash recipe for building across all platforms
script = raw"""
cd $WORKSPACE/srcdir
for f in ${WORKSPACE}/srcdir/patches/*.patch; do
    atomic_patch -p1 ${f}
done
cd gb
./autogen.sh
./configure --enable-shared --disable-static --prefix=${prefix} --build=${MACHTYPE} --host=${target} --with-gmp=${prefix}
make -j${nproc}
make install
"""

# These are the platforms we will build for by default, unless further
# platforms are passed in on the command line

platforms = filter(!Sys.iswindows, supported_platforms())

# The products that we will ensure are always built
products = [
    LibraryProduct("libgb", :libgb)
]

# Dependencies that must be installed before this package can be built
dependencies = [
    Dependency(PackageSpec(name="GMP_jll", uuid="781609d7-10c4-51f6-84f2-b8444358ff6d"), v"6.1.2"),
    Dependency(PackageSpec(name="CompilerSupportLibraries_jll", uuid="e66e0078-7015-5450-92f7-15fbd957f2ae")),
]

# Build the tarballs, and possibly a `build.jl` as well.
build_tarballs(ARGS, name, version, sources, script, platforms, products, dependencies)

max_stars_repo_name: sharanry/Yggdrasil

max_issues_repo_name: sharanry/Yggdrasil

max_forks_repo_name: sharanry/Yggdrasil


text:
"""
Abstract type representing a pattern used in all the various pattern matching backends.
You can use the `Pattern` constructor to recursively convert an `Expr` (or any type satisfying [`Metatheory.TermInterface`](@ref)) to a [`Pattern`](@ref).
"""
abstract type Pattern end

# TODO implement debrujin indexing?
"""
Pattern variables will first match on any subterm
and instantiate the substitution to that subterm.
"""
struct PatVar <: Pattern
    var::Symbol
end

"""
A pattern literal will match only against an instance of itself.
Example:
```julia
PatLiteral(2)
```
Will match only against values that are equal (using `Base.(==)`) to 2.

```julia
PatLiteral(:a)
```
Will match only against instances of the literal symbol `:a`.
"""
struct PatLiteral{T} <: Pattern
    val::T
end

"""
Type assertions on a [`PatVar`](@ref), will match if and only if
the type of the matched term for the pattern variable `var` is a subtype
of `type`.
"""
struct PatTypeAssertion <: Pattern
    var::PatVar
    type::Type
end

struct PatSplatVar <: Pattern
    var::PatVar
end

"""
This type of pattern will match if and only if
the two subpatterns exist in the same equivalence class,
in the e-graph on which the matching is performed.
**Can be used only in the e-graphs backend**
"""
struct PatEquiv <: Pattern
    left::Pattern
    right::Pattern
end

"""
Term patterns will match
on terms of the same `arity` and with the same
function symbol (`head`).
"""
struct PatTerm <: Pattern
    head::Any
    args::Vector{Pattern}
    metadata::Union{Nothing, NamedTuple}
end
TermInterface.arity(p::PatTerm) = length(p.args)
PatTerm(head, args) = PatTerm(head, args, nothing)

"""
This pattern type matches on a function application
but instead of strictly matching on a head symbol,
it has a pattern variable as head. It can be used for
example to match arbitrary function calls.
"""
struct PatAllTerm <: Pattern
    head::PatVar
    args::Vector{Pattern}
    metadata::Union{Nothing, NamedTuple}
end
TermInterface.arity(p::PatAllTerm) = length(p.args)
PatAllTerm(head, args) = PatAllTerm(head, args, nothing)

# collect pattern variables in a set of symbols
patvars(p::PatLiteral; s=PatVar[]) = s
patvars(p::PatVar; s=PatVar[]) = push!(s, p)
patvars(p::PatTypeAssertion; s=PatVar[]) = patvars(p.var; s=s)
patvars(p::PatSplatVar; s=PatVar[]) = patvars(p.var; s=s)

function patvars(p::PatTerm; s=PatVar[])
    for x ∈ p.args
        patvars(x; s)
    end
    return s
end

function patvars(p::PatAllTerm; s=PatVar[])
    push!(s, p.head)
    for x ∈ p.args
        patvars(x; s)
    end
    return s
end


text:
using AMRVW
using Test
const A = AMRVW

include("test-amrvw-basics.jl")
include("test-passthrough.jl")
include("test-roots.jl")
include("test-twisted.jl")


text:
function BasicBlock()
    BasicBlock(
        LookupTable{LinearInstruction}(),          # instructions
        LookupTable{ImmutableVariable}(),          # inputs
        LookupTable{MutableVariable}(),            # mutable_locals
        Dict{ImmutableVariable, ImmutableValue}(), # immutable_locals
        LookupTable{Variable}()                    # outputs
    )
end

input_variables(bb::BasicBlock) = bb.inputs
output_variables(bb::BasicBlock) = bb.outputs

"""
    constant(val) :: Const

Creates a constant value.
"""
constant(val) = Const(val)

#hasbranches(bb::BasicBlock) = bb.branch != nothing || bb.next != nothing
is_input(bb::BasicBlock, var::ImmutableVariable) = var ∈ bb.inputs
is_input(bb::BasicBlock, var::MutableVariable) = false
is_output(bb::BasicBlock, var::Variable) = var ∈ bb.outputs

struct InstructionIterator{T}
    instructions::T
end
Base.iterate(itr::InstructionIterator) = iterate(itr.instructions)
Base.iterate(itr::InstructionIterator, state) = iterate(itr.instructions, state)
eachinstruction(bb::BasicBlock) = InstructionIterator(bb.instructions)
eachinstruction(bb::CompiledBasicBlock) = InstructionIterator(bb.instructions)

"""
    has_symbol(bb::BasicBlock, sym::Symbol) :: Bool

Returns `true` if there is any variable (input, local or output)
defined that is identified by the symbol `sym`.
"""
function has_symbol(bb::BasicBlock, sym::Symbol) :: Bool
    for itr in (bb.inputs, bb.mutable_locals, keys(bb.immutable_locals), bb.outputs)
        if any(v -> v.symbol == sym, itr)
            return true
        end
    end

    return false
end

"""
    generate_unique_variable_symbol(bb::BasicBlock) :: Symbol

OptimizingIR's version of `Base.gensym`.

Returns a new symbol for which [`OptimizingIR.has_symbol`](@ref)
is `false`.
"""
function generate_unique_variable_symbol(bb::BasicBlock) :: Symbol
    local new_sym::Symbol = gensym()

    while has_symbol(bb, new_sym)
        new_sym = gensym()
    end

    return new_sym
end

"""
    addinstruction!(b::BasicBlock, instruction::LinearInstruction) :: ImmutableValue

Pushes an instruction to a basic block.
Returns the value that represents the result
after the execution of the instruction.
"""
function addinstruction!(b::BasicBlock, instruction::LinearInstruction) :: ImmutableValue

    result = try_on_add_instruction_passes(b, instruction)
    if result !== nothing
        return result
    end

    return SSAValue(addentry!(b.instructions, instruction))
end

inputindex(bb::BasicBlock, op::Variable) = indexof(bb.inputs, op)

"""
    addinput!(b::BasicBlock, iv::ImmutableVariable) :: Int

Registers `iv` as an input variable of the function.
Returns the index of this variable in the tuple of inputs (function arguments).
"""
addinput!(b::BasicBlock, iv::ImmutableVariable) = addentry!(b.inputs, iv)

"""
    addoutput!(b::BasicBlock, iv::Variable) :: Int

Registers `iv` as an output variable of the function.
Returns the index of this variable in the tuple of returned values.
"""
addoutput!(b::BasicBlock, iv::Variable) = addentry!(b.outputs, iv)

function optimization_rule(::Type{Op{F, O}}) where {F, O}
    O
end

function check_args_mutability(op, args...)

    or = optimization_rule(op)

    if or.mutable_arg === nothing
        # no-op
        return

    elseif isa(or.mutable_arg, Integer)

        @assert args[or.mutable_arg] <: MutableVariable "Expected MutableVariable at argument index $(or.mutable_arg), but found $(args[or.mutable_arg])."

    elseif isa(or.mutable_arg, Tuple) || isa(or.mutable_arg, NTuple)

        for arg in or.mutable_arg
            @assert isa(arg, Integer) "mutable_arg element must be Integer."
            @assert args[arg] <: MutableVariable "Expected MutableVariable at argument index $arg, but found $(args[arg])."
        end

    else
        error("Unexpected mutable_arg type: $(or.mutable_arg)::$(typeof(or.mutable_arg))")
    end
end

"""
    call(op, args...) :: LinearInstruction

Creates an instruction as a call to operation `op`
with arguments `args`.

Internally, it returns either a [`OptimizingIR.PureInstruction`](@ref)
or an [`OptimizingIR.ImpureInstruction`](@ref).
"""
@generated function call(op::Op, arg::A) :: LinearInstruction where {A<:AbstractValue}

    check_args_mutability(op, arg)

    # a call is pure if the Op itself is pure and the argument is immutable
    pure = is_pure(op) && is_immutable(A)
    wrapper_type = pure ? :PureInstruction : :ImpureInstruction
    return quote
        $wrapper_type(CallUnary(op, arg))
    end
end

@generated function call(op::Op, arg1::A, arg2::B) :: LinearInstruction where {A<:AbstractValue, B<:AbstractValue}

    check_args_mutability(op, arg1, arg2)

    pure = is_pure(op) && is_immutable(arg1) && is_immutable(arg2)
    wrapper_type = pure ? :PureInstruction : :ImpureInstruction
    return quote
        $wrapper_type(CallBinary(op, arg1, arg2))
    end
end

@generated function call(op::Op, arg1::A, arg2::B, arg3::C) :: LinearInstruction where {A<:AbstractValue, B<:AbstractValue, C<:AbstractValue}

    check_args_mutability(op, arg1, arg2, arg3)

    pure = is_pure(op) && is_immutable(arg1) && is_immutable(arg2) && is_immutable(arg3)
    wrapper_type = pure ? :PureInstruction : :ImpureInstruction
    return quote
        $wrapper_type(Call3Args(op, arg1, arg2, arg3))
    end
end

@generated function call(op::Op, arg1::A, arg2::B, arg3::C, arg4::D) :: LinearInstruction where {A<:AbstractValue, B<:AbstractValue, C<:AbstractValue, D<:AbstractValue}

    check_args_mutability(op, arg1, arg2, arg3, arg4)

    pure = is_pure(op) && is_immutable(arg1) && is_immutable(arg2) && is_immutable(arg3) && is_immutable(arg4)
    wrapper_type = pure ? :PureInstruction : :ImpureInstruction
    return quote
        $wrapper_type(Call4Args(op, arg1, arg2, arg3, arg4))
    end
end

@generated function call(op::Op, arg1::A, arg2::B, arg3::C, arg4::D, arg5::E) :: LinearInstruction where {A<:AbstractValue, B<:AbstractValue, C<:AbstractValue, D<:AbstractValue, E<:AbstractValue}

    check_args_mutability(op, arg1, arg2, arg3, arg4, arg5)

    pure = is_pure(op) && is_immutable(arg1) && is_immutable(arg2) && is_immutable(arg3) && is_immutable(arg4) && is_immutable(arg5)
    wrapper_type = pure ? :PureInstruction : :ImpureInstruction
    return quote
        $wrapper_type(Call5Args(op, arg1, arg2, arg3, arg4, arg5))
    end
end

@generated function call(op::Op, arg1::A, arg2::B, arg3::C, arg4::D, arg5::E, arg6::F) :: LinearInstruction where {A<:AbstractValue, B<:AbstractValue, C<:AbstractValue, D<:AbstractValue, E<:AbstractValue, F<:AbstractValue}

    check_args_mutability(op, arg1, arg2, arg3, arg4, arg5, arg6)

    pure = is_pure(op) && is_immutable(arg1) && is_immutable(arg2) && is_immutable(arg3) && is_immutable(arg4) && is_immutable(arg5) && is_immutable(arg6)
    wrapper_type = pure ? :PureInstruction : :ImpureInstruction
    return quote
        $wrapper_type(Call6Args(op, arg1, arg2, arg3, arg4, arg5, arg6))
    end
end

"""
    assign!(bb::BasicBlock, lhs::Variable, rhs::AbstractValue)

Assigns the value `rhs` to variable `lhs`.
"""
function assign!(bb::BasicBlock, lhs::ImmutableVariable, rhs::ImmutableValue)
    @assert !haskey(bb.immutable_locals, lhs) "Cannot assign to immmutable variable `$lhs` twice."
    bb.immutable_locals[lhs] = rhs
    addentry!(bb.instructions, ImpureInstruction(Assignment(lhs, rhs)))
    nothing
end

function assign!(bb::BasicBlock, lhs::MutableVariable, rhs::ImmutableValue)
    addentry!(bb.mutable_locals, lhs)
    addentry!(bb.instructions, ImpureInstruction(Assignment(lhs, rhs)))
    nothing
end


text:
#=
binary_tree:
- Julia version: 1.5.0
- Author: shisa
- Date: 2020-08-21

Tree definition
      A
    /  \
   B    H
  / \
 C  D
   / \
  E   F
 /
G
=#

module MyBinaryTree

    # Node class
    mutable struct Node
        label
        right
        left
    end

    function pre_order(node)
        if node == nothing
            return
        end
        println(node.label)
        pre_order(node.left)
        pre_order(node.right)
    end

    function in_order(node)
        if node == nothing
            return
        end
        in_order(node.left)
        println(node.label)
        in_order(node.right)
    end

    function post_order(node)
        if node == nothing
            return
        end
        post_order(node.left)
        post_order(node.right)
        println(node.label)
    end

    function main()
        # define root node
        root = Node('A', nothing, nothing)
        root.left = Node('B', nothing, nothing)
        root.right = Node('H', nothing, nothing)
        root.left.left = Node('C', nothing, nothing)
        root.left.right = Node('D', nothing, nothing)
        root.left.right.left = Node('E', nothing, nothing)
        root.left.right.right = Node('F', nothing, nothing)
        root.left.right.left.left = Node('G', nothing, nothing)

        println("Pre-Order Traversal")
        pre_order(root)
        println("")
        println("In-Order Traversal")
        in_order(root)
        println("")
        println("Post-Order Traversal")
        post_order(root)
    end

end

if abspath(PROGRAM_FILE) == @__FILE__
    using .MyBinaryTree
    MyBinaryTree.main()
end

max_stars_repo_name: ShisatoYano/JuliaPractice

max_issues_repo_name: ShisatoYano/JuliaPractice

max_forks_repo_name: ShisatoYano/JuliaPractice


text:
using Documenter
using GasChromatographySimulator

makedocs(
            sitename = "GasChromatographySimulator.jl",
            pages = Any[
                "Home" => "index.md",
                "Installation" => "installation.md",
                "Usage" => "usage.md",
                "Functions" => "functions.md",
                "References" => "references.md"
            ]
        )

# Documenter can also automatically deploy documentation to gh-pages.
# See "Hosting Documentation" and deploydocs() in the Documenter manual
# for more information.
deploydocs(
    repo = "github.com/JanLeppert/GasChromatographySimulator.jl",
    devbranch = "main"
)


text:
export NormalScore

"""
    struct NormalScore <: Score{Float64}

A score defined by a normal density given the mean and sd of the score.
"""
struct NormalScore <: Score{Float64}
    mean :: Float64
    sd :: Float64
end

@impl begin
    struct NormalScoreGetScore end
    function get_score(sf::NormalScore, i::Float64)::AbstractFloat
        return normal_density(i, sf.mean, sf.sd)
    end
end