text:
module PanX

using GZip, JSON
using Rematch
using ProgressMeter

import ..Graphs
# ------------------------------------------------------------------------
# Phylogenetic tree manipulation

module Phylo

using Rematch

# use internal python so we can build a conda environment
import PyCall
Ete3 = PyCall.PyNULL()

function __init__()
    PyCall.pyimport("warnings").filterwarnings("ignore") # ignore syntax warnings
    copy!(Ete3, PyCall.pyimport_conda("ete3", "ete3", "etetoolkit"))
end

function tree(newick)
    return Ete3.Tree(newick)
end

function binary!(tree)
    tree.resolve_polytomy(recursive=true)
    return tree
end

function root!(tree)
    midpoint = tree.get_midpoint_outgroup()
    tree.set_outgroup(midpoint)
    tree.ladderize()
    return tree
end

function rescale!(tree, by::T) where T <: Real
    for node in tree.traverse("preorder")
        node.dist *= by
    end
end

write(io::IO, tree::PyCall.PyObject) = Base.write(io, tree.write(format=1))

function dictionary(tree::PyCall.PyObject, level::Int, i::Int; mutations=false)
    node = Dict(
        "name" => if tree.name == ""
            i += 1
            suffix = string(i-1)
            suffix = @match length(suffix) begin
                1 => "0000$(suffix)"
                2 => "000$(suffix)"
                3 => "00$(suffix)"
                4 => "0$(suffix)"
                _ => suffix
            end
            "NODE_$(suffix)"
        else
            tree.name
        end,
        "branch_length" => tree.dist,
    )

    if mutations
        # TODO: actually write mutations?
        node["muts"]    = ""
        node["aa_muts"] = ""
    else
        node["clade"] = level
    end

    if tree.name != ""
        if mutations
            node["accession"]  = split(tree.name,'#')[1]
            node["annotation"] = "pan-contig"
        else
            node["attr"] = Dict(
                "host"   => tree.name,
                "strain" => tree.name,
            )
        end
        return node, i
    end

    node["children"] = Dict[]
    for child in tree.children
        c, i = dictionary(child, level+1, i; mutations=mutations)
        push!(node["children"], c)
    end

    return node, i
end

end # Phylo

function gzip(from::AbstractString, to::AbstractString; clean=false)
    isfile(from) || error("$(from) not found")

    Base.open(from, "r") do rdr; GZip.open(to, "w") do wtr
        write(wtr, read(rdr))
    end; end

    clean && rm(from)
end

gzip(path::AbstractString; clean=true) = gzip(path,"$path.gz"; clean=clean)

function polymorphisms(alignment)
    alleles = [ length(Set(row)) != 1 for row in eachrow(alignment) ]
    return alignment[alleles,:]
end

function identifiers(graph::Graphs.Graph)
    name = Dict{Graphs.Node, String}()
    for path in values(graph.sequence)
        counter = Dict{Graphs.Block, Int}()
        for node in path.node
            if node.block ∈ keys(counter)
                counter[node.block] += 1
                name[node] = "$(path.name)#$(counter[node.block])"
            else
                counter[node.block] = 1
                name[node] = "$(path.name)#1"
            end
        end
    end

    return function(node,_...)
        name[node]
    end
end

function emitblock(block::Graphs.Block, root, prefix, identifier; reduced=true)
    path = "$(root)/$(prefix)_na_aln.fa"
    open(path, "w") do io
        Graphs.marshal(io, block;
            fmt=:fasta,
            opt=(gaps=true, name=identifier)
        )
    end

    # grab reduced alignment
    alignment, scale = if reduced
        gzip(path; clean=true) # compress our previous alignment
        path = "$(root)/$(prefix)_na_aln_alleles.fa"

        align, nodes, _ = Graphs.alignment(block)
        numbp = size(align,1)

        align = polymorphisms(align)
        names = [identifier(node,i) for (i,node) in enumerate(nodes)]

        open(path, "w") do io
            for (name, seq) in zip(names, eachcol(align))
                Graphs.Utility.write_fasta(io, name, seq)
            end
        end

        path, size(align,1)/numbp
    else
        path, 1
    end

    out = IOBuffer()
    run(pipeline(
        `fasttree -nt -gtr $(alignment)`, stdout=out, stderr=devnull);
        wait=true
    )
    tree = Phylo.tree(String(take!(out)))

    Phylo.binary!(tree)
    Phylo.root!(tree)
    Phylo.rescale!(tree, scale)

    open("$root/$prefix.nwk", "w") do io
        Phylo.write(io, tree)
    end

    open("$root/$(prefix)_tree.json", "w") do io
        out, _ = Phylo.dictionary(tree,0,0;mutations=true)
        JSON.print(io, out)
    end

    gzip(path; clean=true)

    # emit a reduced alignment (panX by default looks for this)
    align, nodes, consensus = Graphs.alignment(block)
    reduce = [ length(Set(row)) == 1 for row in eachrow(align) ]
    align[reduce,:] .= '.'

    names = [identifier(node,i) for (i,node) in enumerate(nodes)]
    GZip.open("$root/$(prefix)_na_aln_reduced.fa.gz", "w") do io
        Graphs.Utility.write_fasta(io, "consensus", consensus)

        for (name, seq) in zip(names, eachcol(align))
            seq[seq.==consensus] .= '.'
            Graphs.Utility.write_fasta(io, name, seq)
        end
    end

    return tree
end

function coreblocks(G::Graphs.Graph, identifier)
    core  = Graphs.Block[]
    depth = length(G.sequence)
    for block in values(G.block)
        Graphs.depth(block) == depth || continue
        unique = reduce(&,
            map(collect(keys(block))) do node
                split(identifier(node),'#')[end] == "1"
            end
        )
        unique || continue

        push!(core, block)
    end

    return core
end

function emitcore(genes::Array{Graphs.Block}, root::String, identifier)
    length(genes) ≥ 1 || return

    isolate = (node) -> split(identifier(node),'#')[1]

    one, nodes, _ = Graphs.alignment(genes[1])
    order = Dict( isolate(node)=>i for (i,node) in enumerate(nodes) )

    aln = if length(genes) > 1
        reduce(vcat,
            map(genes[2:end]) do blk
                seq, ns, _ = Graphs.alignment(blk)
                permute = [order[isolate(n)] for n in ns]
                seq[:,permute]
            end;
        init=one)
    else
        one
    end

    numbp = size(aln,2)
    aln = polymorphisms(aln)
    scale = size(aln,2)/numbp

    names = map(isolate, nodes)
    path  = "$(root)/core_na_reduced.fa"
    open(path, "w") do io
        for (name, seq) in zip(names, eachcol(aln))
            Graphs.Utility.write_fasta(io, name, seq)
        end
    end

    out = IOBuffer()
    run(pipeline(
        `fasttree -nt -gtr $(path)`, stdout=out, stderr=devnull);
        wait=true
    )
    tree = Phylo.tree(String(take!(out)))
    gzip(path)

    Phylo.binary!(tree)
    Phylo.root!(tree)
    Phylo.rescale!(tree, scale)

    # emit as newick
    open("$root/strain_tree.nwk", "w") do io
        Phylo.write(io, tree)
    end

    # emit as bespoke json
    open("$root/coreGenomeTree.json", "w") do io
        out, _ = Phylo.dictionary(tree, 0, 0,)
        JSON.print(io, out)
    end
end

function fmt(i::Int)
    s = string(i)
    @match length(s) begin
        1 => "0000000$s"
        2 => "000000$s"
        3 => "00000$s"
        4 => "0000$s"
        5 => "000$s"
        6 => "00$s"
        7 => "0$s"
        _ => s
    end
end

function emit(G::Graphs.Graph, root::String)
    isdir(root) || mkdir(root)
    isdir("$root/geneCluster") || mkdir("$root/geneCluster")

    idents = identifiers(G)
    blocks = sort(collect(values(G.block)); by=(blk)->Graphs.depth(blk), rev=true)

    # emit all blocks
    meter = Progress(length(blocks), 1, "Aligning blocks. Building trees...")
    metadata = Array{Dict}(undef,length(blocks))
    for (i,b) in enumerate(blocks)
        prefix = "RC$(fmt(i))"
        node_ids = [idents(node) for node in keys(b)]
        not_dupl = all([endswith(id, "#1") for id in node_ids])
        metadata[i] = Dict(
            "geneId"     => i,
            "geneLen"    => length(b),
            "count"      => Graphs.depth(b),
            "dupli"      => not_dupl ? "no" : "yes",
            "dup_detail" => "",
            "ann"        => b.uuid,
            "msa"        => prefix,
            "divers"     => Graphs.diversity(b),
            "allAnn"     => b.uuid,
            "GName"      => "none",
            "allGName"   => "none",
            "locus"      => node_ids,
        )
        emitblock(b, "$(root)/geneCluster", "$(prefix)", idents; reduced=length(b) ≥ 5e4)
        next!(meter)
    end

    open("$root/geneCluster.json","w") do io
        JSON.print(io, metadata)
    end

    # emit core genome
    core = coreblocks(G, idents)
    emitcore(core, root, idents)

    # emit dummy strain meta info
    open("$root/metainfo.tsv", "w") do io
        write(io, join(
            ["accession",
             "strain",
             "collection_date",
             "country",
             "host",
             "organism"
            ], "\t"),
        "\n")

        for isolate in keys(G.sequence)
            write(io, join([
                isolate,
                "unknown",
                "unknown",
                "unknown",
                isolate,
                "unknown",
            ],"\t"), "\n")
        end
    end

    metainfo = [
        Dict("strain" => "unknown", "host"   => isolate, "accession" => isolate)
    for isolate  in keys(G.sequence)]

    open("$root/strainMetainfo.json","w") do io
        JSON.print(io, Dict("data"=>metainfo))
    end

    open("$root/metaConfiguration.js","w") do io
        write(io, """
        var meta_details={
            "host": $(collect(keys(G.sequence)))
        },
        meta_display={
            "meta_display_order": ["host"],
            "color_options": {"host": {"menuItem": "host", "type": "discrete"}},
        };
        var association_columns=[];
        """)
    end
end

end

max_stars_repo_name: neherlab/pangraph

max_issues_repo_name: neherlab/pangraph

max_forks_repo_name: neherlab/pangraph


text:
using StaticCompiler
using StaticTools
using LoopVectorization

function loopvec_product(argc::Int, argv::Ptr{Ptr{UInt8}})
    argc == 3 || return printf(stderrp(), c"Incorrect number of command-line arguments\n")
    rows = parse(Int64, argv, 2)            # First command-line argument
    cols = parse(Int64, argv, 3)            # Second command-line argument

    s = 0
    @turbo for i=1:rows
        for j=1:cols
           s += i*j
        end
    end
    # Print result to stdout
    printf(s)
    # Also print to file
    fp = fopen(c"product.tsv",c"w")
    printf(fp, s)
    fclose(fp)
end

# Attempt to compile
path = compile_executable(loopvec_product, (Int64, Ptr{Ptr{UInt8}}), "./")

ext: jl


text:
module DataInterpolations

### Interface Functionality

abstract type AbstractInterpolation{FT,T} <: AbstractVector{T} end

Base.size(A::AbstractInterpolation) = size(A.u)
Base.size(A::AbstractInterpolation{true}) = length(A.u) .+ size(A.t)
Base.getindex(A::AbstractInterpolation,i) = A.u[i]
Base.getindex(A::AbstractInterpolation{true},i) = i<=length(A.u) ? A.u[i] : A.t[i-length(A.u)]
Base.setindex!(A::AbstractInterpolation,x,i) = A.u[i] = x
Base.setindex!(A::AbstractInterpolation{true},x,i) =
                                   i <= length(A.u) ? (A.u[i] = x) : (A.t[i-length(A.u)] = x)

using LinearAlgebra, RecursiveArrayTools, RecipesBase, Reexport
@reexport using Optim

include("interpolation_caches.jl")
include("interpolation_utils.jl")
include("interpolation_methods.jl")
include("plot_rec.jl")

export LinearInterpolation, QuadraticInterpolation, LagrangeInterpolation, AkimaInterpolation,
       ConstantInterpolation, QuadraticSpline, CubicSpline, BSplineInterpolation, BSplineApprox, Curvefit

# Deprecated April 2020
export ZeroSpline

end # module


text:
using AdversarialPrediction
using Test

include("test_expr.jl")
include("test_metric.jl")
include("test_projection.jl")


text:
push!(LOAD_PATH, pwd()*"/../../src/")
using Distributions
using PyPlot
using BVB

lower = -100.
upper = 100.

max_iter = 30
init_approx_d =  Normal(0, 40)

# example 2
true_d = MixtureModel(Normal, [(-3.5, 1), (-1.0, 0.4), (1.0, 0.5), (6.0, 1)], [0.2, 0.3, 0.3, 0.2])
ll(x) = logpdf(true_d, x)
x = linspace(-20,20,500)

include("run_laplacian_gradient_boosting_exclusive.jl")
save_trace("./mog-1/", x, init_approx_d, approx_d, true_d,
                    iter_vec, α_vec,
                    eval_vec, -elbo_vec)
show()

println("Done.")
readline(STDIN)

max_stars_repo_name: richardkwo/boosting-VB

max_issues_repo_name: richardkwo/boosting-VB

max_forks_repo_name: richardkwo/boosting-VB


text:
export Pathfinding

"""
    Pathfinding
Submodule containing functionality for path-finding based on the A* algorithm.
Currently available for [`GridSpace`](@ref) and [`ContinuousSpace`](@ref).
Discretization of [`ContinuousSpace`](@ref) is taken care of internally.

You can enable path-finding and set its options by creating an instance of a
[`Pathfinding.AStar`](@ref) struct. This must be passed to the relevant pathfinding functions
during the simulation. Call [`plan_route!`](@ref) to set the destination for an agent. This
triggers the algorithm to calculate a path from the agent's current position to the one
specified. You can alternatively use [`plan_best_route!`](@ref) to choose the best target
from a list. Once a target has been set, you can move an agent one step along its
precalculated path using the [`move_along_route!`](@ref) function.

Refer to the [Maze Solver](@ref), [Mountain Runners](@ref) and [Rabbit, Fox, Hawk](@ref)
examples using path-finding and see the available functions below as well.
"""
module Pathfinding

using Agents
using DataStructures
using LinearAlgebra

abstract type GridPathfinder{D,P,M} end

include("metrics.jl")
include("pathfinding_utils.jl")
include("astar.jl")
include("astar_grid.jl")
include("astar_continuous.jl")

export CostMetric,
    DirectDistance,
    MaxDistance,
    PenaltyMap,
    AStar,
    delta_cost,
    penaltymap,
    nearby_walkable,
    random_walkable

end


text:
using Test

import Pluto: Notebook, ServerSession, ClientSession, Cell, load_notebook, load_notebook_nobackup, save_notebook, WorkspaceManager, cutename, numbered_until_new, readwrite, without_pluto_file_extension, PlutoEvent, update_run!
import Random
import Pkg
import UUIDs: UUID

@testset "Private API stability for extended Pluto deployments" begin

    events = []
    function test_listener(a::PlutoEvent)
        @info "this run!"
        push!(events, typeof(a))
    end
    🍭 = ServerSession()
    🍭.options.server.on_event = test_listener
    🍭.options.evaluation.workspace_use_distributed = false

    fakeclient = ClientSession(:fake, nothing)
    🍭.connected_clients[fakeclient.id] = fakeclient
    notebook = Notebook([
        Cell("[1,1,[1]]"),
        Cell("Dict(:a => [:b, :c])"),
    ])

    fakeclient.connected_notebook = notebook

    update_run!(🍭, notebook, notebook.cells)
    WorkspaceManager.unmake_workspace((🍭, notebook))
    @test_broken events[1:3] == ["NewNotebookEvent", "OpenNotebookEvent" , "FileSaveEvent"]

# Pluto.CustomLaunchEvent: Gets fired
# Pluto.NewNotebookEvent: Gets fired
# Pluto.OpenNotebookEvent: Gets fired
# Pluto.FileSaveEvent: Gets fired
# Pluto.responses[:juliahub_initiate] = function (🙋::Pluto.ClientRequest) EXTEND end
# Pluto.SessionActions.open(session, string(jhnb_path); notebook_id = UUID(jhub_params[:id]),)
# Pluto.cutename(): returns string
# Pluto.save_notebook(io::IOBuffer, notebook): saves notebook to IO
# Pluto.ServerSession(;options, event_listener)

end


text:
using Test
using BitBasis
using YaoExtensions, Yao
using YaoExtensions: pattern53, upperright, lowerleft, upperleft, lowerright
using Yao.Optimise: to_basictypes, simplify, replace_block

lattice = Lattice53()
@test upperright(lattice,1,1) == 0
@test upperright(lattice,2,1) == lattice[1,2]
@test upperright(lattice,1,2) == lattice[1,3]
@test lowerright(lattice,1,1) == lattice[1,2]
@test lowerright(lattice,1,2) == lattice[2,3]
@test upperleft(lattice,1,2) == lattice[1,1]
@test upperleft(lattice,1,3) == 0
@test upperleft(lattice,2,3) == lattice[1,2]
@test lowerleft(lattice,1,2) == lattice[2,1]
@test lowerleft(lattice,2,3) == lattice[2,2]

lattice = Lattice53()
for (sym, nvar) in [('A', 24), ('B', 19), ('C', 23), ('D', 20),
                    ('E', 22), ('F', 21), ('G', 21), ('H', 22)]
    @test length(pattern53(lattice, sym)) == nvar
end

@testset "circuit build" begin
    c = rand_google53(4)
    @test length(collect_blocks(FSimGate, c)) == 86
    @test nparameters(c) == 86*2
    @test length(collect_blocks(PrimitiveBlock{1}, c)) == 53*4
end

max_stars_repo_name: QuantumBFS/YaoExtensions

max_issues_repo_name: QuantumBFS/YaoExtensions

max_forks_repo_name: QuantumBFS/YaoExtensions


text:
using Documenter, DynamicNLPModels

const _PAGES = [
    "Introduction" => "index.md",
    "Quick Start"=>"guide.md",
    "API Manual" => "api.md"
]

makedocs(
    sitename = "DynamicNLPModels",
    authors = "David Cole, Sungho Shin, Francois Pacaud",
    format = Documenter.LaTeX(platform="docker"),
    pages = _PAGES
)

makedocs(
    sitename = "DynamicNLPModels",
    modules = [DynamicNLPModels],
    authors = "David Cole, Sungho Shin, Francois Pacaud",
    format = Documenter.HTML(
        prettyurls = get(ENV, "CI", nothing) == "true",
        sidebar_sitename = true,
        collapselevel = 1,
    ),
    pages = _PAGES,
    clean = false,
)

deploydocs(
    repo = "github.com/MadNLP/DynamicNLPModels.jl.git",
    target = "build",
    devbranch = "main",
    devurl = "dev",
    push_preview = true,
)


text:
import Pkg
import UUIDs

function maketempdir()::String
    path::String = mktempdir()
    atexit(() -> _force_remove_path(path))
    return path
end

function _force_remove_path(path)::Nothing
    try
        rm(path; force = true, recursive = true)
    catch
    end
    return nothing
end

original_directory = pwd()
project_root = joinpath(splitpath(@__DIR__)...)
cd(project_root)

include(joinpath(project_root, "ci", "RegistryTestingTools", "types.jl",))

if length(ARGS) < 3
    @error(
        string(
            "syntax: julia overwrite_from_external_registry.jl ",
            "\"EXTERNAL_REGISTRY_NAME\" ",
            "\"EXTERNAL_REGISTRY_UUID\" ",
            "\"EXTERNAL_REGISTRY_URL\" ",
            "[list of packages or interval of packages (optional)]",
            )
        )
    @error(
        string(
            "example usage #1: julia overwrite_from_external_registry.jl ",
            "\"General\" ",
            "\"23338594-aafe-5451-b93e-139f81909106\" ",
            "\"https://github.com/JuliaRegistries/General.git\"",
            )
        )
    @error(
        string(
            "example usage #2: julia overwrite_from_external_registry.jl ",
            "\"General\" ",
            "\"23338594-aafe-5451-b93e-139f81909106\" ",
            "\"https://github.com/JuliaRegistries/General.git\" ",
            "\"[,)\"",
            )
        )
    @error(
        string(
            "example usage #3: julia overwrite_from_external_registry.jl ",
            "\"General\" ",
            "\"23338594-aafe-5451-b93e-139f81909106\" ",
            "\"https://github.com/JuliaRegistries/General.git\" ",
            "\"[,M)\"",
            )
        )
    @error(
        string(
            "example usage #4: julia overwrite_from_external_registry.jl ",
            "\"General\" ",
            "\"23338594-aafe-5451-b93e-139f81909106\" ",
            "\"https://github.com/JuliaRegistries/General.git\" ",
            "\"[Pre,)\"",
            )
        )
    @error(
        string(
            "example usage #5: julia overwrite_from_external_registry.jl ",
            "\"General\" ",
            "\"23338594-aafe-5451-b93e-139f81909106\" ",
            "\"https://github.com/JuliaRegistries/General.git\" ",
            "\"[G,Req)\"",
            )
        )
    @error(
        string(
            "example usage #6: julia overwrite_from_external_registry.jl ",
            "\"General\" ",
            "\"23338594-aafe-5451-b93e-139f81909106\" ",
            "\"https://github.com/JuliaRegistries/General.git\" ",
            "\"Foo\"",
            )
        )
    @error(
        string(
            "example usage #7: julia overwrite_from_external_registry.jl ",
            "\"General\" ",
            "\"23338594-aafe-5451-b93e-139f81909106\" ",
            "\"https://github.com/JuliaRegistries/General.git\" ",
            "\"Foo\" \"Bar\" \"Baz\"",
            )
        )
    error("Not enough command-line arguments")
elseif length(ARGS) == 3
    push!(ARGS, "[,)",)
else
end

external_registry = Pkg.RegistrySpec(
    name = strip(ARGS[1]),
    uuid = UUIDs.UUID(strip(ARGS[2])),
    url = strip(ARGS[3]),
    )

this_registry_toml_path = joinpath(project_root,"Registry.toml",)
this_registry_configuration = Pkg.TOML.parsefile(this_registry_toml_path)
this_registry_name_to_path = Dict{String, String}()
this_registry_name_to_uuid = Dict{String, String}()
this_registry_all_packages = String[]
for pair in this_registry_configuration["packages"]
    uuid = pair[1]
    name = pair[2]["name"]
    path = pair[2]["path"]
    push!(this_registry_all_packages, name,)
    this_registry_name_to_path[name] = path
    this_registry_name_to_uuid[name] = uuid
end

unique!(this_registry_all_packages)
sort!(this_registry_all_packages)
n = length(this_registry_all_packages)
@debug(
    "this_registry_all_packages",
    length(this_registry_all_packages),
    this_registry_all_packages,
    repr(this_registry_all_packages),
    )
if _is_interval(ARGS[4])
    this_job_interval = _construct_interval(
        convert(String, strip(ARGS[4]))
        )
    _this_job_interval_contains_x(x) = _interval_contains_x(
        this_job_interval,
        x,
        )
    packages_to_overwrite_in_this_job_interval = this_registry_all_packages[
        _this_job_interval_contains_x.(
            this_registry_all_packages
            )
        ]
else
    packages_to_overwrite_in_this_job_interval = String[
        strip(s) for s in ARGS[4:end]
        ]
end
unique!(packages_to_overwrite_in_this_job_interval)
sort!(packages_to_overwrite_in_this_job_interval)
@debug(
    "packages_to_overwrite_in_this_job_interval",
    length(packages_to_overwrite_in_this_job_interval),
    packages_to_overwrite_in_this_job_interval,
    repr(packages_to_overwrite_in_this_job_interval),
    )

my_depot = joinpath(maketempdir(), "depot",)
my_environment = joinpath(maketempdir(), "depot",)
rm(my_depot; force = true, recursive = true,)
rm(my_environment;force = true,recursive = true,)
mkpath(my_depot)
mkpath(my_environment)
original_depot_path = [x for x in Base.DEPOT_PATH]
empty!(Base.DEPOT_PATH)
pushfirst!(Base.DEPOT_PATH, my_depot,)
Pkg.activate(my_environment)
Pkg.Registry.add(external_registry)
external_registry_afteradding = first(
    Pkg.Types.collect_registries()
    )
external_registry_configuration = Pkg.TOML.parsefile(
    joinpath(external_registry_afteradding.path,"Registry.toml",)
    )
external_registry_name_to_path = Dict{String, String}()
external_registry_name_to_uuid = Dict{String, String}()
for pair in external_registry_configuration["packages"]
    uuid = pair[1]
    name = pair[2]["name"]
    path = pair[2]["path"]
    external_registry_name_to_path[name] = path
    external_registry_name_to_uuid[name] = uuid
end
external_registry_all_packages = Set(
    collect(keys(external_registry_name_to_path))
    )

n = length(packages_to_overwrite_in_this_job_interval)
for i = 1:n
    name = packages_to_overwrite_in_this_job_interval[i]
    @debug("Overwriting \"$(name)\" (package $(i) of $(n))")
    if name in this_registry_all_packages
        if name in external_registry_all_packages
            our_uuid = this_registry_name_to_uuid[name]
            their_uuid = external_registry_name_to_uuid[name]
            if strip(our_uuid) == strip(their_uuid)
                our_path = this_registry_name_to_path[name]
                their_path = external_registry_name_to_path[name]
                our_full_path = joinpath(project_root, our_path)
                their_full_path = joinpath(
                    external_registry_afteradding.path,
                    their_path,
                    )
                rm(
                    our_full_path;
                    force = true,
                    recursive = true,
                    )
                mkpath(our_full_path)
                our_compat_toml = joinpath(our_full_path, "Compat.toml")
                our_deps_toml = joinpath(our_full_path, "Deps.toml")
                our_package_toml = joinpath(our_full_path, "Package.toml")
                our_versions_toml = joinpath(our_full_path, "Versions.toml")
                their_compat_toml = joinpath(their_full_path, "Compat.toml")
                their_deps_toml = joinpath(their_full_path, "Deps.toml")
                their_package_toml = joinpath(their_full_path, "Package.toml")
                their_versions_toml = joinpath(their_full_path, "Versions.toml")
                if isfile(their_compat_toml)
                    cp(
                        their_compat_toml,
                        our_compat_toml;
                        force = true,
                        )
                end
                if isfile(their_deps_toml)
                    cp(
                        their_deps_toml,
                        our_deps_toml;
                        force = true,
                        )
                end
                if isfile(their_package_toml)
                    cp(
                        their_package_toml,
                        our_package_toml;
                        force = true,
                        )
                end
                if isfile(their_versions_toml)
                    cp(
                        their_versions_toml,
                        our_versions_toml;
                        force = true,
                        )
                end
                @info("Overwrote $(name)")
            else
                error(
                    string(
                        "Our registry says that the UUID of package ",
                        "\"$(name)\" is ",
                        "\"$(our_uuid)\", ",
                        "but the external registry says that ",
                        "the UUID of package ",
                        "\"$(name)\" is ",
                        "\"$(their_uuid)\".",
                        )
                    )
            end
        else
            @warn(
                string(
                    "The external registry does not have the package ",
                    "\"$(name)\" ",
                    "in their registry. ",
                    "Therefore, I will skip the ",
                    "\"$(name)\" package.",
                    )
                )
        end
    else
        error(
            string(
                "We do not have the package ",
                "\"$(name)\" ",
                "in our registry.",
                )
            )
    end
end

empty!(Base.DEPOT_PATH)
for x in original_depot_path
    push!(Base.DEPOT_PATH, x,)
end
unique!(Base.DEPOT_PATH)

temp_registry_toml = read(this_registry_toml_path, String)
temp_registry_toml_parsed = Pkg.TOML.parse(temp_registry_toml)
if !haskey(temp_registry_toml_parsed, "packages")
    temp_output = string(temp_registry_toml,
                         "\n\n\n\n",
                         "[packages]",
                         "\n\n\n\n")
    rm(this_registry_toml_path; force = true, recursive = true)
    write(this_registry_toml_path, temp_output)
end

cd(original_directory)


text:
using HypergeometricFunctions, Test
import LinearAlgebra: norm
import HypergeometricFunctions: _₂F₁general, iswellpoised # not exported

import HypergeometricFunctions: drummond0F0, drummond1F0, drummond0F1,
                                drummond2F0, drummond1F1, drummond0F2,
                                drummond2F1, pFqdrummond, pFqweniger

const rtol = 1.0e-3
const NumberType = Float64

@testset "Hypergeometric Function tests" begin
    @testset "_₂F₁ vs _₂F₁general" begin
        e = exp(1.0)
        regression_max_accumulated_error = 2.0e-13 # discovered by running the test
        for z in (.9rand(Float64, 10), 10rand(ComplexF64, 10))
            j = 1
            for (a,b,c) in ((√2/e, 1.3, 1.3), (1.2, √3, 1.2), (-0.4, 0.4, 0.5),
                            (-0.3, 1.3, 0.5), (0.35, 0.85, 0.5), (0.5, 0.5, 1.5),
                            (1.0, 1.0, 1.5), (0.5, 1.0, 1.5), (0.3, 0.7, 1.5),
                            (0.7, 1.3, 1.5), (0.35, 0.85, 1.5), (1.0, 1.0, 2.0),
                            (3.0, 1.0, 2.0), (-2.0, 1.0, 2.0), (-3.0, 1.0, 2.0),
                            (1.0, -4.0, 2.0), (2.0, 2.0, 4.0), (1.0, 1.5, 2.5))
                error_accum = 0.0
                for zi in z
                    twoFone = _₂F₁(a,b,c,zi)
                    aa,bb,cc = big(a),big(b),big(c)
                    twoFonegeneral = convert(Complex{Float64},_₂F₁general(aa, bb, cc, big(zi)))
                    norm(twoFone / twoFonegeneral - 1) > sqrt(eps()) && println("This is ₂F₁($a,$b;$c;zi) - ₂F₁general($a,$b;$c;zi): ", norm(twoFone / twoFonegeneral - 1), "   ", twoFone, "   ", twoFonegeneral, "   ", isfinite(twoFone), "   ", isfinite(twoFonegeneral), " this is zi: ", zi)
                    error_accum += Float64(norm(twoFone / twoFonegeneral - 1))
                end
                @test error_accum < regression_max_accumulated_error
                j += 1
            end
        end
        @testset "Test that _₂F₁ is inferred for Float32 arguments" begin
            @test @inferred(_₂F₁(0.3f0, 0.7f0, 1.3f0, 0.1f0)) ≈ Float32(_₂F₁(0.3, 0.7, 1.3, 0.1))
        end
    end

    @testset "method = positive" begin
        for (a, b, c, z) in ((1, 2, 3, 0.5), (3, 5, 7, 0.75), (1, 8537, 6042, 0.25))
            positivetwoFone = _₂F₁(a, b, c, z; method = :positive)
            twoFone = Float64(pFqweniger(BigFloat[a, b], BigFloat[c], big(z)))
            @test positivetwoFone > 0
            @test positivetwoFone ≈ twoFone
        end
    end

    @testset "_₂F₁ argument unity" begin
        for (a, b, c, z) in ((1, 2, 3, 1), (3, 5, 7, 1.0), (1, 8537, 6042, 1.0))
            twoFone = _₂F₁(a, b, c, z)
            twoFonep = _₂F₁(a, b, c, z; method = :positive)
            if iswellpoised(a, b, c)
                @test isfinite(twoFone) == true
                @test isfinite(twoFonep) == true
            else
                @test isinf(twoFone) == true
                @test isinf(twoFonep) == true
            end
        end
    end

    @testset "pFq vs mpmath" begin
        (a, b, c, result) = NumberType.([-1.138]), NumberType.([-1.17865]), NumberType(0.29524203533943405), 1.3211939223293958
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([-0.00209496]), NumberType.([1.55444]), NumberType(1.9964304489951332), 0.9956895798837077
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([-0.550861]), NumberType.([-2.76028]), NumberType(1.686164802648714), 2.26529646755787
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([0.522481]), NumberType.([2.43767]), NumberType(0.07397564666157663), 1.0161190845825492
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([1.14629]), NumberType.([-1.71237]), NumberType(0.865999806211927), 6.09627259912178
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([-0.977563]), NumberType.([-0.943489]), NumberType(1.3295519796473885), 2.9650972591473237
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([2.19487]), NumberType.([-2.84673]), NumberType(-2.946765152780697), -10.159918912696533
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([-1.40648]), NumberType.([-2.09642]), NumberType(0.003973775403141477), 1.002667944757093
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([2.78115]), NumberType.([-0.974578]), NumberType(-0.289876068484225), -9.436220915244991
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([-2.0195]), NumberType.([2.97415]), NumberType(1.9088632413219395), 0.020342030150391748
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([-1.29058]), NumberType.([1.12475, 2.20863]), NumberType(2.5233777332943026), -0.23709345988925976
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([1.93422]), NumberType.([-0.403018, -1.68818]), NumberType(1.8841553851312423), -368.4667336251361
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([1.38965]), NumberType.([1.34519, 2.18274]), NumberType(-2.967668498991821), 0.12382284309201524
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([0.317445]), NumberType.([2.83319, 2.08577]), NumberType(-0.8292545561139764), 0.9574454648148745
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([-1.53034]), NumberType.([-2.00218, 2.71893]), NumberType(-0.055950986916451395), 0.984386941287138
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([1.8068]), NumberType.([2.785, -2.27362]), NumberType(-2.965224079697172), 3.343788228467509
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([2.01277]), NumberType.([0.0297853, 0.638178]), NumberType(2.87029742430684), 1862.664910896795
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([-1.332]), NumberType.([-0.571085, 2.40734]), NumberType(2.5191976052414615), 2.6748631921200974
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([0.585852]), NumberType.([-0.840541, -0.914398]), NumberType(-0.7114454462840016), 13.397306612348904
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([-1.30148]), NumberType.([-0.0397773, 0.452281]), NumberType(2.9085746526416285), 134.70529132344416
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([1/2]), NumberType.([1, 3/2]), NumberType(-10.0), 0.1215046687753564
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([1/2]), NumberType.([1, 3/2]), NumberType(-100.0), 0.05291894107105639
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([1/2]), NumberType.([1, 3/2]), NumberType(-1000.0), 0.015220788412455796
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([1/2]), NumberType.([1, 3/2]), NumberType(-10000.0), 0.004728870002692929
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([1.79664]), NumberType.([2.5454, -2.0446, -1.84776]), NumberType(-1.5647341841975129), 10.224086634371103
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([-1.08954]), NumberType.([-1.09992, -0.0898055, -1.21452]), NumberType(2.911146030454528), -281.8950930467646
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([2.50123]), NumberType.([1.481, 1.04535, -1.1706]), NumberType(1.2093267908720815), 4.297922628682247
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([-0.918156]), NumberType.([-1.66879, -1.26548, -2.71329]), NumberType(-1.4539176485483885), 0.7245506668664914
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([-2.25871]), NumberType.([0.734527, 2.69253, 1.52627]), NumberType(1.412857816927049), 0.0007367729643306418
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([1.75347]), NumberType.([-1.19881, 1.46644, 0.377671]), NumberType(-2.894612064681616), 31.986877557865302
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([-2.55356]), NumberType.([2.31273, -1.79583, 2.71976]), NumberType(-1.8211352681511421), 0.6524733226915893
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([-2.96471]), NumberType.([0.10731, 0.150247, -0.749495]), NumberType(-0.5456496601437784), -364.7310910695041
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([2.28595]), NumberType.([1.24272, -1.3733, -1.97931]), NumberType(2.694315046446391), 1427.85053117312
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([-1.02891]), NumberType.([-0.203779, 0.414445, -2.72581]), NumberType(2.7264202122777323), -11.325191332268156
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([1.21643, 2.56177]), NumberType.([-2.85355]), NumberType(-1.173143685351698), -2.6927101990763944
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([-0.884016, -0.278806]), NumberType.([-2.95573]), NumberType(-0.5131107181888153), 1.0423537583061855
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([-0.489218, 1.02043]), NumberType.([-1.8805]), NumberType(-2.054787166536263), 1.3985297910285344
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([-2.61829, -0.0405846]), NumberType.([-2.52321]), NumberType(-2.8547909742932127), 1.111640235796153
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([-1.78806, 0.244808]), NumberType.([-2.03175]), NumberType(0.5005127629084343), 1.0071139633716848
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([2.79663, 2.95841]), NumberType.([-2.23659]), NumberType(-2.1658329294772676), -1.298805755547899
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([0.473781, -0.844289]), NumberType.([-0.228894]), NumberType(0.8762669945656332), 3.026596343521232
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([-1.99653, -2.15667]), NumberType.([1.45492]), NumberType(0.5669144675224369), 2.901074111158336
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([1.89145, -2.17305]), NumberType.([-1.97603]), NumberType(-2.2566276457677343), 145.35756041830106
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([0.998819, -0.225309]), NumberType.([0.447173]), NumberType(-0.10835817353459554), 1.051599100560819
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([-0.383828, 1.77538]), NumberType.([-1.0875, -2.84315]), NumberType(1.4065086054194986), 715.336897395762
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([0.733652, -1.6307]), NumberType.([-0.0608787, 0.896927]), NumberType(0.10210464529041374), 3.1665794151940694
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([-0.202523, -1.68826]), NumberType.([-1.92541, 2.88428]), NumberType(0.23168614635513318), 0.9854522687722247
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([-0.946942, 1.58094]), NumberType.([-0.150083, 2.30757]), NumberType(-2.109785441324441), -7.76796376651872
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([1.55118, -2.75387]), NumberType.([1.46214, 2.18634]), NumberType(2.6348816640393258), -0.31994633361734
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([-2.06745, -0.28521]), NumberType.([-1.99816, -0.766774]), NumberType(-0.7965581191453945), 5.472490531872681
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([-2.20859, -1.41744]), NumberType.([1.85829, 1.92196]), NumberType(-1.2487286295352975), -0.053122867013287486
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([0.260072, 0.317936]), NumberType.([-1.4299, 1.60909]), NumberType(-1.554201646172852), 1.0698093358492726
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([-1.81949, 2.65844]), NumberType.([2.84994, -1.67876]), NumberType(1.5573520464968), 4.557008143231845
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([-2.09665, 1.27147]), NumberType.([-0.682723, 0.192544]), NumberType(-1.175497640118377), -118.5195721586634
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([0.472347, 2.38973]), NumberType.([1.23953, -2.45145, -0.0816949]), NumberType(2.9793981957869673), 562.1327877798817
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([2.70886, -2.26978]), NumberType.([-1.83008, -1.6277, -1.33282]), NumberType(2.7790611310114053), -12231.7908950255
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([1.48786, -2.73106]), NumberType.([-1.73601, -1.676, -2.17108]), NumberType(-0.6847891664895385), -36.681955083411964
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([-1.72604, -1.83087]), NumberType.([-2.68909, -0.904331, 1.93759]), NumberType(1.651593934432523), 0.9572670911067562
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([0.27953, 2.57139]), NumberType.([-1.72806, 2.13894, -0.674948]), NumberType(1.3654741919794335), -8.061422671050726
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([-0.363687, 1.0458]), NumberType.([-1.13771, -2.02746, -2.86789]), NumberType(2.026179003725624), -5919.391531381284
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([2.49209, -1.06563]), NumberType.([1.47807, 1.01142, -1.54966]), NumberType(-0.9883650134564901), -0.0985713724396932
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([0.416307, 1.24566]), NumberType.([1.56196, 1.32576, -1.82953]), NumberType(-2.4172898932733053), 1.0404646069316064
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([2.52485, 0.109503]), NumberType.([-1.3165, 0.177332, 2.58557]), NumberType(-2.84982197723157), 2.9369917768818667
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([-2.45525, -1.61598]), NumberType.([-1.75953, -1.59772, 2.05578]), NumberType(-1.1643127384783538), 0.5520841179227342
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([-1.7029, 1.4496, -2.82896]), NumberType.([-2.77533]), NumberType(-1.5171018909198049), 8.437330705993508
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([-1.34783, -0.324078, 2.44238]), NumberType.([-0.777003]), NumberType(-1.059855902026896), 3.9754790978546266
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([-1.87289, 2.99671, 2.99742]), NumberType.([-1.4312]), NumberType(-2.433424057786612), 638.863801591021
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([-0.963631, -1.36196, -2.90998]), NumberType.([-0.950805]), NumberType(-1.1275151312466227), -1.9506846998048282
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([2.20585, 1.21729, 0.419755]), NumberType.([-2.95176]), NumberType(-0.8474785819006732), -0.9897576725972367
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([-2.50248, -2.01281, -1.10468]), NumberType.([-1.47035]), NumberType(-2.161852515937607), -4.205644305802463
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([-1.373, 0.0281506, 1.31409]), NumberType.([-0.775952]), NumberType(-2.0586457735217407), 0.6176889810366223
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([1.4476, 0.286052, 1.71704]), NumberType.([1.29826]), NumberType(-0.9902327227931127), 0.7640485766337997
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([-2.49284, 1.34398, 1.38886]), NumberType.([-2.04354]), NumberType(-0.9516109943455211), -137.34441283528875
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([2.19033, -0.446436, -2.73578]), NumberType.([0.758367]), NumberType(-1.115415216535085), -8.890490669826645
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([1.21084, -1.43893, 1.56842]), NumberType.([-0.598469, 0.52221]), NumberType(-2.2391561626302376), -64.66480492684083
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([0.607277, -0.376803, -2.08424]), NumberType.([1.92106, 2.80899]), NumberType(-1.5589765316931263), 0.8516398920401931
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([-2.63828, 2.59771, 2.54461]), NumberType.([2.62021, -0.0157026]), NumberType(0.5526474385388149), -29.571181883739737
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([0.314356, 2.59205, -1.28807]), NumberType.([-1.22202, -1.66475]), NumberType(-0.7121680260550485), 0.856714022601912
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([0.694337, -2.06707, 0.214575]), NumberType.([-1.31576, 0.266519]), NumberType(-2.9461185849069706), 21.80248076992691
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([1.90394, 2.56441, 0.07523]), NumberType.([0.0390543, -1.65175]), NumberType(-0.7780439739130411), -3.184516491992518
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([-2.80752, 2.7876, -1.37287]), NumberType.([-2.9165, 0.49188]), NumberType(0.39686964583141693), -1.3014023309227971
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([2.36231, -0.901808, 1.00893]), NumberType.([1.39985, -2.34968]), NumberType(0.970806084927347), 42731.87930657499
        @test_broken pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        @test HypergeometricFunctions.pFqcontinuedfraction(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([-0.715302, 2.94101, -0.498188]), NumberType.([-0.393808, -0.0265878]), NumberType(0.4375358657735875), 61.68955383799459
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([-1.14105, 1.9464, -2.44787]), NumberType.([0.54636, -0.654353]), NumberType(-2.9505198429994763), -53.189709409599516
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([0.228056, -1.24092, 0.843438]), NumberType.([1.25348, 2.42447, -1.59626]), NumberType(-2.32373843841519), 0.8942755488371047
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([-1.78019, -2.49326, -1.62843]), NumberType.([-1.85186, -2.72869, -2.36236]), NumberType(-1.6400906330598044), 0.2981496993840609
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([1.98727, 2.31523, -0.0735596]), NumberType.([-0.0644426, 2.54497, -1.08036]), NumberType(-1.0705461999772998), 10.575143699481718
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([-1.45036, -2.25443, -2.74298]), NumberType.([-1.39353, -1.20841, 0.225826]), NumberType(-2.950872722868197), 982.2060223576477
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([-0.36497, 1.79508, 2.36814]), NumberType.([1.55155, 0.704328, -0.686943]), NumberType(0.2186808938362801), 1.7064306875530209
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([-1.51876, -1.37851, -1.12183]), NumberType.([1.3349, -2.95129, 1.10139]), NumberType(0.7674847040296018), 1.4158192973160308
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([-1.99362, -2.09819, -2.16471]), NumberType.([-1.76093, 2.0683, -0.947339]), NumberType(-1.8729057277220629), -41.660320326270636
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([1.82466, 1.28428, 2.67447]), NumberType.([2.10754, 0.871646, 1.39154]), NumberType(2.658591557834844), 81.52661900335721
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([-1.79631, -0.0269564, 0.915417]), NumberType.([-2.17853, 1.0933, -0.000243005]), NumberType(2.661306310651646), -83.69268822607185
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([1.36163, -0.758606, -0.716056]), NumberType.([-1.04856, 0.266574, -2.47814]), NumberType(1.8461964795702661), -113.75411958323524
        @test pFq(a, b, c) ≈ result atol=eps() rtol=rtol
    end
    @testset "_₂F₁ vs mpmath" begin
        (a, b, c, result) = NumberType.([-0.509718, 2.74761]), NumberType.([-0.650532]), NumberType(-2.9555898601070316), 1.2790428246176058
        @test _₂F₁(a..., b..., c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([-2.5215, -1.50451]), NumberType.([-0.759254]), NumberType(-0.5749286896537393), 1.1388556009105488
        @test _₂F₁(a..., b..., c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([-2.86391, 1.25904]), NumberType.([0.517432]), NumberType(-2.940843956490598), 189.9291251487297
        @test _₂F₁(a..., b..., c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([0.0877358, 0.682746]), NumberType.([2.84558]), NumberType(-1.0261339665475955), 0.9822590779186833
        @test _₂F₁(a..., b..., c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([2.3191, 1.94423]), NumberType.([1.88828]), NumberType(-1.3591292051020116), 0.12818348728367582
        @test _₂F₁(a..., b..., c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([2.56295, -0.753746]), NumberType.([-0.159836]), NumberType(-0.8246738184622906), -6.594728994176734
        @test _₂F₁(a..., b..., c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([1.67125, 0.101391]), NumberType.([0.107343]), NumberType(-0.7965765135904737), 0.40781958014265957
        @test _₂F₁(a..., b..., c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([-1.99678, -0.201406]), NumberType.([-1.95704]), NumberType(0.05697188547835097), 0.9880143477892287
        @test _₂F₁(a..., b..., c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([-1.45054, 0.439005]), NumberType.([0.908234]), NumberType(0.8723075146005943), 0.49786449277738715
        @test _₂F₁(a..., b..., c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([1.01798, -2.7207]), NumberType.([-2.9141]), NumberType(-2.164369297479041), 8.70430095368102
        @test _₂F₁(a..., b..., c) ≈ result atol=eps() rtol=rtol
    end
    @testset "_₃F₂ vs mpmath" begin
        (a, b, c, result) = NumberType.([-2.76481, 0.00672772, 0.741886]), NumberType.([-2.53237, 2.79933]), NumberType(-0.21967338526219615), 0.9995944744632735
        @test _₃F₂(a..., b..., c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([1.00388, -2.50276, -1.20821]), NumberType.([-1.552, 1.0715]), NumberType(0.6716163785419433), -0.050120516406253396
        @test _₃F₂(a..., b..., c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([0.483392, -1.42038, -1.82681]), NumberType.([2.98456, 1.87387]), NumberType(-1.241922052077597), 0.7292186256180657
        @test _₃F₂(a..., b..., c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([-2.80985, 1.57763, 0.344136]), NumberType.([-2.00075, -0.973491]), NumberType(-0.3899943196975246), 14466.732269418837
        @test _₃F₂(a..., b..., c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([-2.3729, 1.09037, -2.76876]), NumberType.([-1.13014, -1.81025]), NumberType(-2.3731909909995714), -1351.450695124059
        @test _₃F₂(a..., b..., c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([2.60036, 1.54435, -2.72411]), NumberType.([-0.141692, -2.06915]), NumberType(0.813329638552919), -79135.94437145953
        @test _₃F₂(a..., b..., c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([-1.32094, 1.1992, -0.270438]), NumberType.([-0.483108, -2.41227]), NumberType(-2.1529259273055366), 0.6103979954183846
        @test _₃F₂(a..., b..., c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([-1.39151, 0.699785, -0.457295]), NumberType.([-2.53724, -0.45027]), NumberType(0.4811844516239163), 1.1524122102606527
        @test _₃F₂(a..., b..., c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([-2.22368, 2.92094, -1.8566]), NumberType.([-2.35922, 2.78358]), NumberType(-0.06437623035744533), 1.121248505469995
        @test _₃F₂(a..., b..., c) ≈ result atol=eps() rtol=rtol
        (a, b, c, result) = NumberType.([-2.95746, -1.43804, -0.363603]), NumberType.([-1.59028, 1.87905]), NumberType(0.6408597427285083), 1.3015755922356282
        @test _₃F₂(a..., b..., c) ≈ result atol=eps() rtol=rtol
    end

end

@testset "₀F₀" begin
    for (S, T) in ((Float16, Float32),
                   (Float32, Float64),
                   (Float64, BigFloat),
                   (BigFloat, BigFloat))
        CS = Complex{S}
        CT = Complex{T}
        atol = rtol = 1000eps(S)
        for z in S(-4):S(0.25):S(1)
            @test drummond0F0(z) ≈ S(pFq(T[], T[], T(z))) atol=atol rtol=rtol
            @test pFqdrummond(S[], S[], z) ≈ S(pFq(T[], T[], T(z))) atol=atol rtol=rtol
            @test pFqweniger(S[], S[], z) ≈ S(pFq(T[], T[], T(z))) atol=atol rtol=rtol
        end
        atol *= 2
        rtol *= 2
        for x in S(-4):S(0.25):S(1), y in S(-4):S(0.25):S(1)
            z = complex(x, y)
            @test drummond0F0(z) ≈ CS(pFq(T[], T[], CT(z))) atol=atol rtol=rtol
            @test pFqdrummond(S[], S[], z) ≈ CS(pFq(T[], T[], CT(z))) atol=atol rtol=rtol
            @test pFqweniger(S[], S[], z) ≈ CS(pFq(T[], T[], CT(z))) atol=atol rtol=rtol
        end
    end
end

@testset "₁F₀" begin
    for (S, T) in ((Float32, Float64),
                   (Float64, BigFloat),
                   (BigFloat, BigFloat))
        CS = Complex{S}
        CT = Complex{T}
        atol = rtol = 1000eps(S)
        for α in S(-1.5):S(0.5):S(1.5), z in S(-0.75):S(0.25):S(0.25)
            @test drummond1F0(α, z) ≈ S(pFq(T[α], T[], T(z))) atol=atol rtol=rtol
            @test pFqdrummond(S[α], S[], z) ≈ S(pFq(T[α], T[], T(z))) atol=atol rtol=rtol
            @test pFqweniger(S[α], S[], z) ≈ S(pFq(T[α], T[], T(z))) atol=atol rtol=rtol
        end
        atol *= 2
        rtol *= 2
        for α in S(-1.5):S(0.5):S(1.5), x in S(-0.75):S(0.25):S(0.25), y in S(-0.75):S(0.25):S(0.25)
            z = complex(x, y)
            @test drummond1F0(α, z) ≈ CS(pFq(T[α], T[], CT(z))) atol=atol rtol=rtol
            @test pFqdrummond(S[α], S[], z) ≈ CS(pFq(T[α], T[], CT(z))) atol=atol rtol=rtol
            @test pFqweniger(S[α], S[], z) ≈ CS(pFq(T[α], T[], CT(z))) atol=atol rtol=rtol
        end
    end
end

@testset "₀F₁" begin
    for (S, T) in ((Float32, Float64),
                   (Float64, BigFloat),
                   (BigFloat, BigFloat))
        CS = Complex{S}
        CT = Complex{T}
        atol = rtol = 1000eps(S)
        for α in S(-1.5):S(1.0):S(1.5), z in S(-0.75):S(0.25):S(0.75)
            @test drummond0F1(α, z) ≈ S(pFq(T[], T[α], T(z))) atol=atol rtol=rtol
            @test pFqdrummond(S[], S[α], z) ≈ S(pFq(T[], T[α], T(z))) atol=atol rtol=rtol
            @test pFqweniger(S[], S[α], z) ≈ S(pFq(T[], T[α], T(z))) atol=atol rtol=rtol
        end
        atol *= 2
        rtol *= 2
        for α in S(-1.5):S(1.0):S(1.5), x in S(-0.75):S(0.25):S(0.75), y in S(-0.75):S(0.25):S(0.75)
            z = complex(x, y)
            @test drummond0F1(α, z) ≈ CS(pFq(T[], T[α], CT(z))) atol=atol rtol=rtol
            @test pFqdrummond(S[], S[α], z) ≈ CS(pFq(T[], T[α], CT(z))) atol=atol rtol=rtol
            @test pFqweniger(S[], S[α], z) ≈ CS(pFq(T[], T[α], CT(z))) atol=atol rtol=rtol
        end
    end
end

@testset "₂F₀" begin
    for (S, T) in ((Float32, Float64),
                   (Float64, BigFloat),
                   (BigFloat, BigFloat))
        CS = Complex{S}
        CT = Complex{T}
        atol = rtol = sqrt(eps(S))
        for α in S(-1.5):S(1.0):S(1.5), β in S(-1.5):S(1.0):S(1.5), z in S(-1.0):S(0.25):S(0.0)
            @test drummond2F0(α, β, z) ≈ S(drummond2F0(T(α), T(β), T(z))) atol=atol rtol=rtol
            @test pFqdrummond(S[α, β], S[], z) ≈ S(pFqdrummond(T[α, β], T[], T(z))) atol=atol rtol=rtol
            @test pFqweniger(S[α, β], S[], z) ≈ S(pFqweniger(T[α, β], T[], T(z))) atol=atol rtol=rtol
        end
        for α in S(-0.5):S(1.0):S(0.5), β in S(-0.5):S(1.0):S(0.5), x in S(-0.5):S(0.25):S(0.0), y in S(-0.5):S(0.25):S(0.0)
            z = complex(x, y)
            @test drummond2F0(α, β, z) ≈ CS(drummond2F0(T(α), T(β), CT(z))) atol=atol rtol=rtol
            @test pFqdrummond(S[α, β], S[], z) ≈ CS(pFqdrummond(T[α, β], T[], CT(z))) atol=atol rtol=rtol
            @test pFqweniger(S[α, β], S[], z) ≈ CS(pFqweniger(T[α, β], T[], CT(z))) atol=atol rtol=rtol
        end
    end
end

@testset "₁F₁" begin
    for (S, T) in ((Float32, Float64),
                   (Float64, BigFloat),
                   (BigFloat, BigFloat))
        CS = Complex{S}
        CT = Complex{T}
        atol = rtol = 1000eps(S)
        for α in S(-1.5):S(0.5):S(1.5), β in S(-1.5):S(1.0):S(1.5), z in S(-0.75):S(0.25):S(0.75)
            @test drummond1F1(α, β, z) ≈ S(pFq(T[α], T[β], T(z))) atol=atol rtol=rtol
            @test pFqdrummond(S[α], S[β], z) ≈ S(pFq(T[α], T[β], T(z))) atol=atol rtol=rtol
            @test pFqweniger(S[α], S[β], z) ≈ S(pFq(T[α], T[β], T(z))) atol=atol rtol=rtol
        end
        atol *= 2
        rtol *= 2
        for α in S(-1.5):S(0.5):S(1.5), β in S(-1.5):S(1.0):S(1.5), x in S(-0.75):S(0.25):S(0.75), y in S(-0.75):S(0.25):S(0.75)
            z = complex(x, y)
            @test drummond1F1(α, β, z) ≈ CS(pFq(T[α], T[β], CT(z))) atol=atol rtol=rtol
            @test pFqdrummond(S[α], S[β], z) ≈ CS(pFq(T[α], T[β], CT(z))) atol=atol rtol=rtol
            @test pFqweniger(S[α], S[β], z) ≈ CS(pFq(T[α], T[β], CT(z))) atol=atol rtol=rtol
        end
    end
end

@testset "₀F₂" begin
    for (S, T) in ((Float32, Float64),
                   (Float64, BigFloat),
                   (BigFloat, BigFloat))
        CS = Complex{S}
        CT = Complex{T}
        atol = rtol = 1000eps(S)
        for α in S(-1.5):S(1.0):S(1.5), β in S(-1.5):S(1.0):S(1.5), z in S(-0.75):S(0.25):S(0.75)
            @test drummond0F2(α, β, z) ≈ S(pFq(T[], T[α, β], T(z))) atol=atol rtol=rtol
            @test pFqdrummond(S[], S[α, β], z) ≈ S(pFq(T[], T[α, β], T(z))) atol=atol rtol=rtol
            @test pFqweniger(S[], S[α, β], z) ≈ S(pFq(T[], T[α, β], T(z))) atol=atol rtol=rtol
        end
        atol *= 2
        rtol *= 2
        for α in S(-1.5):S(1.0):S(1.5), β in S(-1.5):S(1.0):S(1.5), x in S(-0.75):S(0.25):S(0.75), y in S(-0.75):S(0.25):S(0.75)
            z = complex(x, y)
            @test drummond0F2(α, β, z) ≈ CS(pFq(T[], T[α, β], CT(z))) atol=atol rtol=rtol
            @test pFqdrummond(S[], S[α, β], z) ≈ CS(pFq(T[], T[α, β], CT(z))) atol=atol rtol=rtol
            @test pFqweniger(S[], S[α, β], z) ≈ CS(pFq(T[], T[α, β], CT(z))) atol=atol rtol=rtol
        end
    end
end

@testset "₂F₁" begin
    for (S, T) in ((Float32, Float64),
                   (Float64, BigFloat),
                   (BigFloat, BigFloat))
        CS = Complex{S}
        CT = Complex{T}
        atol = rtol = 1000eps(S)
        for α in S(-1.5):S(0.5):S(1.5), β in S(-1.5):S(0.5):S(1.5), γ in S(-1.5):S(1.0):S(1.5), z in S(-0.625):S(0.25):S(0.125)
            @test drummond2F1(α, β, γ, z) ≈ S(pFq(T[α, β], T[γ], T(z))) atol=atol rtol=rtol
            @test pFqdrummond(S[α, β], S[γ], z) ≈ S(pFq(T[α, β], T[γ], T(z))) atol=atol rtol=rtol
            @test pFqweniger(S[α, β], S[γ], z) ≈ S(pFq(T[α, β], T[γ], T(z))) atol=atol rtol=rtol
        end
        atol *= 2
        rtol *= 2
        for α in S(-1.5):S(0.5):S(1.5), β in S(-1.5):S(0.5):S(1.5), γ in S(-1.5):S(1.0):S(1.5), x in S(-0.375):S(0.25):S(0.125), y in S(-0.375):S(0.25):S(0.125)
            z = complex(x, y)
            @test drummond2F1(α, β, γ, z) ≈ CS(pFq(T[α, β], T[γ], CT(z))) atol=atol rtol=rtol
            @test pFqdrummond(S[α, β], S[γ], z) ≈ CS(pFq(T[α, β], T[γ], CT(z))) atol=atol rtol=rtol
            @test pFqweniger(S[α, β], S[γ], z) ≈ CS(pFq(T[α, β], T[γ], CT(z))) atol=atol rtol=rtol
        end
    end

    @testset "Integer arguments" begin
        @test _₂F₁(1, 0, 3, -1) ≡ _₂F₁(1.0, 0, 3, -1) ≡ 1.0
    end
end


text:
module GeometryTestsSeq
using PartitionedArrays
include("../GeometryTests.jl")
prun(GeometryTests.main,sequential,(2,2))
prun(GeometryTests.main,sequential,(2,2,2))
end


text:
# module Noosphere

using StatsBase
using PlotlyJS
using DataFrames
using HTTP
using StringEncodings
using CSV
using DelimitedFiles
using Missings
using Dates
using TranscodingStreams
using CodecZlib

include("types.jl")
include("util.jl")
include("cache.jl")
include("parse.jl")
include("plot.jl")
include("request.jl")

function test()
    start_day = Date(2021, 7, 1)
    end_day = Date(2021, 7, 2)

    dur = Duration(start_day, end_day)

    params = Params(duration=dur)
    res = get(params)

    saveplotmultiday(res)

    # params = Params(year=2021, month=8, day=1, stime="00:00:00", etime="23:59:59")
    # res = get(params)
    # saveplot(res)
end

test()

# end # module


text:
# example 8: stream one char at a time with write

module FastaIOExample8
using FastaIO
using GZip

# notes about the data:
#   1. the streamed data can be anything as long as
#      it's convertible to an ASCII Char
#   2. descriptions start with '>' and end with a
#      newline; sequence data can be split across
#      multiple lines (they will be reformatted
#      anyways) and end with a newline; whitespace
#      is ignored
#
fastadata = """
    >ITEM1
    -----------STVELTKEN-F--D-Q
    E--F-V--LI--------D-----F--
    P----C-----R----Q---F
    >ITEM2
    ----------MVKEITDAT-F--E-Q-
    --L-V--LT--------D-----F--W
    -------M-------D-----
    >ITEM3
    ----------NLESVEQFD--------
    -------G--K-S--VF--------M-
    -D------L------A-----
    """

function write_fasta_data(filename::String, data)
    println("Writing to file $filename")

    # note: FastaWriter can take a writable IO descriptor as
    #       argument instead of a filename; also, it has
    #       an optional mode argument which defaults to "w"
    #       (use "a" for appending to an exisitng file).
    #       The do-notation ensures closing of the stream
    #       when finished, which is crucial.
    FastaWriter(filename) do fw
        for char in data
            write(fw, char)
        end
    end

    println("This is the content of the file:")
    gzopen(filename) do f
        println(readall(f))
    end
end

examples_dir = dirname(Base.source_path())
# note: gzip compression is used because the filename ends with .gz
write_fasta_data(joinpath(examples_dir, "example_out.fasta.gz"), fastadata)

# remove the file
rm(joinpath(examples_dir, "example_out.fasta.gz"))

end


text:
# lgr_read.jl
#
#   Load Los Gatos Research (LGR) Methane data
#
# Jeremy Rüffer
# Thünen Institut
# Institut für Agrarklimaschutz
# Junior Research Group NITROSPHERE
# Julia 1.6.0
# 07.11.2014
# Last Edit: 28.04.2021

# - Programmatically zipped data files have a PGP signature at the end after the last line of data
# - Data files are TXT files withing a ZIP file
# - Sometimes multiple text files and a folder can be contained within a ZIP file
# - Line width is assumed to be fixed

"# lgr_read(source::String;verbose::Bool=false)

`time,data,columns = lgr_read(source)` Load a single LGR TXT files\n
* **source**::String = File name and location\n\n

---\n

#### Keywords:\n
* verbose::Bool = Display information as the function runs, TRUE is default\n\n"
function lgr_read(source::String;verbose::Bool=false)
	# Check for file
	!isfile(source) ? error(source * " must be a file") : nothing

	dfmt = Dates.DateFormat("dd/mm/yyyy HH:MM:SS.sss") # Date format

	#############################################
	##  Prepare Settings for Loading the Data  ##
	#############################################
	# Header Info
	fsize = stat(source).size
	fid = open(source,"r")
	readline(fid)
	cols = readline(fid,keep=true)[1:end-1]
	cols = permutedims(readdlm(IOBuffer("\"" * replace(replace(cols," " => ""),"," => "\",\"") * "\""),','),[2,1])
	startpos = position(fid)

	# Determine Line Count
	l = readline(fid)
	l_count = 1
	while !isempty(l) && !eof(fid)
		l = readline(fid)
		l_count += 1
	end
	footerlines = 1
	while !eof(fid)
		readline(fid)
		footerlines += 1
	end
	close(fid)

	# Column Types
	col_types = fill!(Array{DataType}(undef,length(cols)),Float64)
	col_types[length(col_types)] = String
	col_types[1] = DateTime

	# Column Names
	col_names = Array{String}(undef,length(cols))
	for i=1:length(cols)
		col_names[i] = replace(cols[i],"[" => "")
		col_names[i] = replace(col_names[i],"]" => "")
	end

	#####################
	##  Load the Data  ##
	#####################
	D = CSV.read(source,
		DataFrame,
		datarow=3,
		dateformat=dfmt,
		delim=',',
		header=col_names,
		#limit=l_count-1, # Read up until the PGP signature but not beyond it
		footerskip=footerlines, # PGP signed
		types=col_types)

	close(fid)
	if Sys.iswindows()
		# Garbage collection ensures the temporary file is closed so that it can be deleted.
		# Windows does not seem to close it in time whereas Linux does
		GC.gc()
	end
	return D
end


text:
##此文件用来进行定位解算的
##先写下测试文件，保证A，y和求解器能正常工作
export Position

struct Position{N, N1<:Int, F<:Symbol, T1<:Array{Float64, N}, T2<:Array{Float64, 2}, T3<:Array{Complex, 2}}
    y::T3
    real_x::T1    #求得的解
    imag_x::T1
    real_A::T2    #过完备原子基
    iamg_A::T2
    dims::N1   #定位维度
    solver::F    #求解方法，采用元编程，便于后期扩展
end
#角度方位，空间网格维度和步进角度,中心频率和波速度
function Position(y, A, dims::Int, solver::Symbol) where{N}
    @assert size(y, 1) == size(A, 1)
    real_x = Array{Float64, 2}(undef, size(A, 2), size(y, 2))
    imag_x = Array{Float64, 2}(undef, size(A, 2), size(y, 2))
    fill!(real_x, zero(eltype(real_x)))
    fill!(imag_x, zero(eltype(imag_x)))
    return Position(y, real_x, imag_x, real.(A), imag.(A), dims, solver)
end


text:
import MPI, HDF5
import Test: @testset, @test, @test_throws

@testset "cmdline" begin
    MPI.mpiexec() do runcmd
        juliacmd = `julia --project=.`

        @test run(`$runcmd -n 4 $juliacmd riopa.jl hello`).exitcode == 0
        if HDF5.has_parallel()
            @test_exists_and_rm("hello.h5")
        else
            for i = 0:3
                @test_exists_and_rm("hello_$i.h5")
            end
        end

        @test run(`$runcmd -n 4 $juliacmd riopa.jl generate-config`).exitcode ==
              0
        @test_exists_and_rm("riopa_default.yaml")
    end
end


text:
module JSXGraph

# Javascript
using JSExpr

# Display
import Blink

# Stdlib & simple things
using Random
using DocStringExtensions
import OrderedCollections: LittleDict

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

# board etc
export board, gcb, (++)
# save
export save, str

# defining functions
export @jsf, @js_str
export val, valx, valy, setx, sety

# controllers
export slider, button

# objects
export functiongraph, parametriccurve, polarcurve, dataplot, plot
export point
export scatterplot, scatter

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

abstract type Object end

Base.length(o::Object) = 1

# fallbacks overloaded by specific objects
val(x) = 1
valx(x) = 1
valy(y) = 1
setx(o, x) = 1
sety(o, y) = 1

function get_opts(x::Object)
    isnothing(x.opts) && return JSString("{}")
    return (;x.opts...)
end

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

include("jsfun.jl")

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

const Option{T} = Union{<:T,Nothing} where T

const FR = Union{JSFun,Real}
const AR = AbstractArray{<:Real}
const AFR = Union{AR,FR}

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

include("utils.jl")

include("board.jl")
include("objects/controllers.jl")
include("objects/curves.jl")
include("objects/geom.jl")
include("objects/extras.jl")

include("display.jl")

end # module


text:
abstract type AbstractExistence end

struct DynamicExistence <: AbstractExistence
    existence::Vector{Bool}
    sample_freq::typeof(1.0Hz)
    time::typeof(1.0s)
end

function DynamicExistence(existence, sample_freq; time = 0.0s)
    DynamicExistence(existence, sample_freq, time)
end

"""
$(SIGNATURES)

Simulates the static existence of either a satellite signal or a interference signal. Type:
Boolean (true if signal exists).
"""
function propagate(existence::Bool, Δt, rng)
    existence
end

function get_existence(existence::Bool)
    existence
end

"""
$(SIGNATURES)

Simulates the dynamic existence of either a satellite signal or a interference signal. Type:
Boolean (true if signal exists).
If time index exceeds data length, last available value is returned
"""
function propagate(existence::DynamicExistence, Δt, rng)
    next_time = existence.time + Δt
    DynamicExistence(existence.existence, existence.sample_freq, next_time)
end

function get_existence(existence::DynamicExistence)
    get_sampled_value(existence.time, existence.sample_freq, existence.existence)
end


text:
#WhatLang tests

# stop chars
@test Languages.is_stop_char(' ')
@test Languages.is_stop_char(',')
@test Languages.is_stop_char('-')
@test Languages.is_stop_char('-')
@test Languages.is_stop_char('9')
@test Languages.is_stop_char('0')

# non-stop chars
@test !Languages.is_stop_char('a')
@test !Languages.is_stop_char('z')
@test !Languages.is_stop_char('A') # latin A
@test !Languages.is_stop_char('Z')
@test !Languages.is_stop_char('я')
@test !Languages.is_stop_char('А') # cyrillic A

@test Languages.is_script(Languages.LatinScript(), 'z') == true
@test Languages.is_script(Languages.LatinScript(), 'A') == true
@test Languages.is_script(Languages.LatinScript(), 'č') == true
@test Languages.is_script(Languages.LatinScript(), 'š') == true
@test Languages.is_script(Languages.LatinScript(), 'Ĵ') == true

@test Languages.is_script(Languages.LatinScript(), 'ж') == false
@test Languages.is_script(Languages.LatinScript(), 'z') == true
@test Languages.is_script(Languages.LatinScript(), 'A') == true
@test Languages.is_script(Languages.LatinScript(), 'č') == true
@test Languages.is_script(Languages.LatinScript(), 'š') == true
@test Languages.is_script(Languages.LatinScript(), 'Ĵ') == true

@test Languages.is_script(Languages.LatinScript(), 'ж') == false

@test Languages.is_script(Languages.EthiopicScript(), 'ፚ') == true
@test Languages.is_script(Languages.EthiopicScript(), 'ᎀ') == true

@test Languages.is_script(Languages.EthiopicScript(), 'а') == false
@test Languages.is_script(Languages.EthiopicScript(), 'L') == false

@test Languages.is_script(Languages.BengaliScript(), 'ই') == true
@test Languages.is_script(Languages.BengaliScript(), 'z') == false

@test Languages.is_script(Languages.KatakanaScript(), 'カ') == true
@test Languages.is_script(Languages.KatakanaScript(), 'f') == false

@test Languages.is_script(Languages.HangulScript(), 'ᄁ') == true
@test Languages.is_script(Languages.HangulScript(), 't') == false

@test Languages.is_script(Languages.GreekScript(), 'φ') == true
@test Languages.is_script(Languages.GreekScript(), 'ф') == false

@test Languages.is_script(Languages.KannadaScript(), 'ಡ') == true
@test Languages.is_script(Languages.KannadaScript(), 'S') == false

@test Languages.is_script(Languages.TamilScript(), 'ஐ') == true
@test Languages.is_script(Languages.TamilScript(), 'Ж') == false

@test Languages.is_script(Languages.ThaiScript(), 'ก') == true
@test Languages.is_script(Languages.ThaiScript(), '๛') == true
@test Languages.is_script(Languages.ThaiScript(), 'Ж') == false

@test Languages.is_script(Languages.GujaratiScript(), 'ઁ') == true
@test Languages.is_script(Languages.GujaratiScript(), '૱') == true
@test Languages.is_script(Languages.GujaratiScript(), 'Ж') == false

@test Languages.is_script(Languages.GurmukhiScript(), 'ਁ') == true
@test Languages.is_script(Languages.GurmukhiScript(), 'ੴ') == true
@test Languages.is_script(Languages.GurmukhiScript(), 'Ж') == false

@test Languages.is_script(Languages.TeluguScript(), 'ఁ') == true
@test Languages.is_script(Languages.TeluguScript(), '౿') == true
@test Languages.is_script(Languages.TeluguScript(), 'Ж') == false

@test Languages.is_script(Languages.OriyaScript(), 'ଐ') == true
@test Languages.is_script(Languages.OriyaScript(), '୷') == true
@test Languages.is_script(Languages.OriyaScript(), '౿') == false

function test_valuable_trigram_chars(chars)
    for ch in chars
        @test Languages.to_trigram_char(ch) == ch
    end
end

function test_not_valuable_trigram_chars(chars)
    for ch in chars
        @test Languages.to_trigram_char(ch) == ' '
    end
end

test_valuable_trigram_chars(['a', 'z', 'A', 'Z', 'Ж', 'ß'])
test_not_valuable_trigram_chars(['\t', '\n', ' ', '.', '0', '9', ',', '@'])
# 0x5B - 0x60
test_not_valuable_trigram_chars(['[', ']', '^', '\\', '`'])
# 0x7B - 0x7E
test_not_valuable_trigram_chars(['[', '|', '{', '}', '~'])

function test_count(text::String,  pairs::Array)
     result = Languages.count_trigrams(text);
     for (trigram, expected_n) in pairs
         actual_n = result[trigram];
         @test actual_n == expected_n
     end
     @test length(result) == length(pairs)
 end

 test_count("", [])
 test_count(",", [])
 test_count("a", [(" a ", 1)])
 test_count("-a-", [(" a ", 1)])
 test_count("yes", [(" ye", 1), ("yes", 1), ("es ", 1)])
 test_count("Give - IT...", [(" gi", 1), ("giv", 1), ("ive", 1), ("ve ", 1), (" it", 1), ("it ", 1)])

res = Languages.get_trigrams_with_positions("xaaaaabbbbd")
@test res["aaa"] == 1
@test res["bbb"] == 2

#Detection
d = LanguageDetector()
text = "Además de todo lo anteriormente dicho, también encontramos..."
output = d(text)
@test output[1] == Languages.Spanish()
@test output[2] == Languages.LatinScript()

text = "Та нічого, все нормально. А в тебе як?"
global output = d(text)
@test output[1] == Languages.Ukrainian()
@test output[2] == Languages.CyrillicScript()

text = "I am begging pardon";
global output = d(text)
@test output[1] == Languages.Tagalog()

text = """
        Мой дядя самых честных правил,
        Когда не в шутку занемог,
        Он уважать себя заставил
        И лучше выдумать не мог.
    """

global output = d(text)
@test output[1] == Languages.Russian()

#Test all languages!
examples = JSON.parse(read(joinpath(dirname(@__FILE__), "examples.json"), String))
d(examples["deu"])

for (key, val) in examples
    global output = d(val)
    @test output[1] == Languages.from_code(key)
end


text:
struct GTPattern{N,L}
    data::NTuple{L,Int}
    function GTPattern{N}(data::NTuple{L,Int}) where {N,L}
        @assert 2*L == N*(N+1)
        return new{N,L}(data)
    end
end

Base.getproperty(m::GTPattern{N}, f::Symbol) where {N} = f == :N ? N : getfield(m, f)

Base.checkbounds(m::GTPattern, k, l) = 0 < k <= l <= m.N

@inline function Base.getindex(m::GTPattern{N}, k, l) where {N}
    @boundscheck begin
        checkbounds(m, k, l) || throw(BoundsError(m, (k, l)))
    end
    v = @inbounds m.data[k + (((l+1+N)*(N-l)) >> 1)]
    return v
end
@inline function Base.setindex(m::GTPattern{N}, v, k, l) where {N}
    @boundscheck begin
        (0 < k <= l <= N) || throw(BoundsError(m, (k, l)))
    end
    newdata = Base.setindex(m.data, v, k + (((l+1+N)*(N-l)) >> 1))
    return GTPattern{N}(newdata)
end

function Base.show(io::IO, m::GTPattern)
    N = m.N
    if get(io, :compact, false)
        return println(io, "GTPattern{$N}(", m.data, ")")
    end
    println(io, "GTPattern{", N, "}:")
    width = ndigits(maximum(m.data))
    s = repeat(" ", width)
    for i = 1:N
        if i == 1
            print(io, N == 1 ? "( " : "⎛ ")
        elseif i == N
            print(io, "⎝ ")
        else
            print(io, "⎜ ")
        end
        print(io, repeat(s, i-1))
        l = N - i + 1
        for k = 1:l-1
            print(io, repeat(" ", width - ndigits(m[k,l])), m[k,l], s)
        end
        print(io, repeat(" ", width - ndigits(m[l,l])), m[l,l])
        print(io, repeat(s, i-1))
        if i == 1
            println(io, N == 1 ? " )" : " ⎞")
        elseif i == N
            println(io, " ⎠")
        else
            println(io, " ⎟")
        end
    end
end
function Base.isless(ma::GTPattern{N}, mb::GTPattern{N}) where N
    @inbounds for l in N:-1:1, k in 1:l
        mb[k,l] > ma[k,l] && return true
        mb[k,l] < ma[k,l] && return false
    end
    return false
end
Base.hash(m::GTPattern, h::UInt) where {N} = hash(m.data, hash(m.N, h))
Base.:(==)(ma::GTPattern, mb::GTPattern) = ma.data == mb.data
rowsum(m::GTPattern, l) = l == 0 ? 0 : sum(m[k, l] for k = 1:l)

#the Z weight
Zweight(m::GTPattern) = Z2weight(m) .// 2
function Z2weight(m::GTPattern{N}) where {N}
    let w = (0, ntuple(l->rowsum(m, l), Val(N))...)
        return ntuple(Val(N-1)) do l
            2*w[l+1] - (w[l] + w[l+2])
        end
    end
end

#the pattern weight
function weight(m::GTPattern{N}) where N
    w = ntuple(l->rowsum(m, l), Val(N))
    @inbounds for l = N:-1:2
        w = Base.setindex(w, w[l]-w[l-1], l)
    end
    return w
end

# GTPatternIterator: iterate over all GT-patterns associated to a given irrep
struct GTPatternIterator{N}
    irrep::SUNIrrep{N}
end

Base.IteratorSize(::Type{<:GTPatternIterator}) = Base.SizeUnknown()
Base.IteratorEltype(::Type{<:GTPatternIterator}) = Base.HasEltype()
Base.eltype(::GTPatternIterator{N}) where {N} = GTPattern{N,(N*(N+1))>>1}
Base.length(iter::GTPatternIterator) = dim(iter.irrep)

function Base.iterate(iter::GTPatternIterator{1}, state = true)
    if state
        return GTPattern{1}((weight(iter.irrep)[1],)), false
    else
        return nothing
    end
end
function Base.iterate(iter::GTPatternIterator{N}) where {N}
    I = weight(iter.irrep)
    iter1 = Iterators.product(reverse(ntuple(i->I[i+1]:I[i], Val(N-1)))...)
    next1 = Base.iterate(iter1)
    next1 === nothing && return nothing # should not happen
    v, state1 = next1
    iter2 = GTPatternIterator(SUNIrrep(reverse(v)))
    next2 = Base.iterate(iter2)
    next2 === nothing && return nothing # should not happen
    pat, state2 = next2
    newpat = GTPattern{N}((I..., pat.data...))
    return newpat, (iter1, state1, iter2, state2)
end
function Base.iterate(iter::GTPatternIterator{N}, state) where {N}
    (iter1, state1, iter2, state2) = state
    next2 = Base.iterate(iter2, state2)
    if next2 === nothing
        next1 = Base.iterate(iter1, state1)
        next1 === nothing && return nothing
        v, state1 = next1
        iter2 = GTPatternIterator(SUNIrrep(reverse(v)))
        next2 = Base.iterate(iter2)
        next2 === nothing && return nothing # should not happen
    end
    pat, state2 = next2
    newpat = GTPattern{N}((weight(iter.irrep)..., pat.data...))
    return newpat, (iter1, state1, iter2, state2)
end

highest_weight(irrep::SUNIrrep{1}) = GTPattern{1}(weight(irrep))
function highest_weight(irrep::SUNIrrep{N}) where N
    I = weight(irrep)
    d = highest_weight(SUNIrrep(Base.front(I)))
    return GTPattern{N}((I..., d.data...))
end

function creation(s::SUNIrrep{N}) where N
    d = dim(s)
    table = Dict{GTPattern,Int}(m=>i for (i, m) in enumerate(basis(s)))
    result = [SparseArray{RationalRoot{Int}}(undef, (d, d)) for i in 1:N-1];
    @inbounds for (m, i) in table
        for l = 1:N-1, k = 1:l
            coef = -1//1;
            for k′ in 1:l+1
                coef *= m[k′,l+1] - m[k,l] + k - k′
                if k′ <= l-1
                    coef *= m[k′,l-1] - m[k,l] + k - k′ -1
                end
                numerator(coef) == 0 && break
                if k′ <= l && k′ != k
                    coef //= (m[k′,l] - m[k,l] + k - k′) * (m[k′,l] - m[k,l] + k - k′ - 1)
                end
                denominator(coef) == 0 && break;
            end
            (denominator(coef) == 0 || numerator(coef) == 0) && continue
            m′ = Base.setindex(m, m[k,l] + 1, k, l)
            j = table[m′]
            result[l][j,i] = signedroot(coef)
        end
    end
    return result
end

annihilation(s::SUNIrrep) = [SparseArray(op') for op in creation(s)]


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

name = "libblastrampoline"
version = v"5.1.0"

# Collection of sources required to build libblastrampoline
sources = [
    GitSource("https://github.com/JuliaLinearAlgebra/libblastrampoline.git",
              "d988464c12117c1def1324a91e3d50a4f4a32eff")
]

# Bash recipe for building across all platforms
script = raw"""
cd $WORKSPACE/srcdir/libblastrampoline/src

make -j${nproc} prefix=${prefix} install
install_license /usr/share/licenses/MIT
"""

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

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

# Dependencies that must be installed before this package can be built
dependencies = [
]

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

max_stars_repo_name: cmhamel/Yggdrasil

max_issues_repo_name: cmhamel/Yggdrasil

max_forks_repo_name: cmhamel/Yggdrasil


text:
using SharedArrays

function lazySolve(mdp::MDP, vi::ValueIteration)
  statespace, actionspace = getspaces(mdp, vi)
  vi.stategrid = RectangleGrid(statespace...)
  vi.actiongrid = RectangleGrid(actionspace...)
  return internalsolve(mdp, vi)
end

function getspaces(mdp::MDP, vi::ValueIteration)
  statedim = length(mdp.statemap)
  actiondim = length(mdp.actionmap)

  stateargs = mdp.reward.argnames[1:statedim]
  actionargs = mdp.reward.argnames[1 + statedim:end]

  statespace = getspace(statedim, stateargs, mdp.statemap, vi.statemap)
  actionspace = getspace(actiondim, actionargs, mdp.actionmap, vi.actionmap)

  return statespace, actionspace
end

function getspace(
    dim::Int64,
    args::Vector{String},
    lazymap::Dict{AbstractString, LazyVar},
    discmap::Dict{AbstractString, LazyDiscrete})

  space = Array{Vector{Float64},1}(undef, dim)
  for ivar in 1:length(args)
    var = args[ivar]
    lazy = lazymap[var]

    if isa(lazy, RangeVar)
      space[ivar] = collect(lazy.minval : discmap[var].step : lazy.maxval)
    elseif isa(lazy, ValuesVar)
      space[ivar] = map(Float64, collect(1:length(lazy.values)))  # map to indices
    else
      @error(string(
        "unknown state/action variable definition type for ", var))
    end
  end

  return space

end

# Returns the actual variable from GridInterpolations indices
function getvar(
    grid::RectangleGrid,
    map::Dict{AbstractString, LazyVar},
    argnames::Vector{String},
    index::Int64)

  raw = ind2x(grid, index)
  var = Array{Any,1}(undef, length(raw))

  for ivar in 1:length(raw)
    lazy = map[argnames[ivar]]
    if isa(lazy, RangeVar)
      var[ivar] = raw[ivar]
    elseif isa(lazy, ValuesVar)
      var[ivar] = lazy.values[Int64(raw[ivar])]
    else
      @error(string(
        "unknown state/action variable definition type for ", argnames[ivar]))
    end
  end

  return var

end

# Inverse of getvar; returns the GridInterpolations index for a state
function getidx(
    map::Dict{AbstractString, LazyVar},
    argnames::Vector{String},
    state::Vector)

  idx = Array{Float64,1}(undef, length(state))

  for i in 1:length(idx)
    lazy = map[argnames[i]]
    if isa(lazy, RangeVar)
      idx[i] = state[i]
    elseif isa(lazy, ValuesVar)
      idx[i] = findfirst(==(state[i]), lazy.values)
    else
      @error(string(
        "unknown state/action variable definition type for ", argnames[ivar]))
    end
  end

  return idx

end

function transition(
    mdp::MDP,
    vi::ValueIteration,
    state::Vector,
    action::Vector,
    stateargnames::Vector{String})

  results = mdp.transition.fn(state..., action...)
  nresults = length(results)

  interps = [
    interpolants(
      vi.stategrid,
      getidx(mdp.statemap, stateargnames, results[i][1]))
    for i in 1:nresults]

  nstateps = 0
  for interp in interps
    nstateps += length(interp[1])
  end

  states = Array{Int64,1}(undef, nstateps)
  probs = Array{Float64,1}(undef, nstateps)

  istate = 0
  for iresult in 1:nresults
    for iinterp in 1:length(interps[iresult][1])
      istate += 1
      states[istate] = interps[iresult][1][iinterp]
      probs[istate] = interps[iresult][2][iinterp] * results[iresult][2]
    end
  end

  return states, probs
end

function reward(mdp::MDP, state::Vector, action::Vector)
  mdp.reward.fn(state..., action...)
end

function segment(n::Int64, u::UnitRange)
    chunks = []

    cov = u.stop - u.start
    stride = round(Int, floor((u.stop - u.start) / (n-1)))
    for i = 1:(n-1)
        si = u.start + (i-1)*stride
        ei = si + stride - 1
        i == (n-1) ? (ei = u.stop) : nothing
        push!(chunks, si:ei)
    end
    return chunks
end

function shmat2mat(shmat::SharedArray{Float64, 2})
    result = zeros(shmat.dims)
    for i in 1:shmat.dims[1]
        for j in 1:shmat.dims[2]
            result[i, j] = shmat[i, j]
        end # for j
    end # for i
    return result
end # function shmat2mat

include("valueiteration_serial.jl")
include("valueiteration_parallel.jl")


text:
"
    Protocol buffer data writer in Julia

    author: Atsushi Sakai
"

using ProtoBuf

include("tutorial.jl")
include("addressbook_pb.jl")

function main()
    println(PROGRAM_FILE," start!!")

    address_book = AddressBook(
                               people=Person[]
                              )

    person1 = Person(
                     id = 1234,
                     name = "John Doe",
                     email = "jdoe@example.com",
                     phones = Person_PhoneNumber[]
                    )

    phone = Person_PhoneNumber(
                               number="555-4321",
                               _type = __enum_Person_PhoneType().HOME
                              )
    push!(person1.phones, phone)

    push!(address_book.people, person1)

    person2 = Person(
                     id = 4321,
                     name = "Tom Ranger",
                     email = "tranger@example.com",
                     phones = Person_PhoneNumber[]
                    )

    phone = Person_PhoneNumber(
                               number="555-4322",
                               _type = __enum_Person_PhoneType().WORK
                              )
    push!(person2.phones, phone)

    push!(address_book.people, person2)

    println(address_book)  # Human readable print

    iob = PipeBuffer();
    writeproto(iob, address_book)

    open( "pbdata_julia.dat", "w" ) do fp
        write( fp, iob )
    end

    println(PROGRAM_FILE," Done!!")
end

main()


text:
"""
    preprocessDenovoSTRs("infile.tsv"; window=100000)

A script to extract a region around a specified STR site
where a event of interest (e.g. mutation) may have occurred.

Options:

path    The directory containing the master vcf file(s) and
        and pedigree file(s) [default: current dir].
        The pedigree files should have a .ped extension (1463.ped)

window  The number of bp on each side of the STR site to construct the
        haplotype [default: 100000 bp].

Returns a list containing the extracted vcf, pedfile name,
and STR location for input into the STR_iht.jl script and a small
phased vcf of the extracted regions.
"""
function preprocessDenovoSTRs(infile; kwargs...)

outdat = []

if Sys.which("bcftools")  == nothing
    error("bcftools is required. Please add bcftools to your path.")
end

kw = Dict(kwargs)

#get path (or set current path to) directory with phased vcfs
path = get(kw, :path, pwd()*"/")

#set haplotype range (each side)
window = get(kw, :window, 100000)

        i = infile
        a = split(i, '\t')
        ped = a[1]
        vcf = a[2]
        pname = splitext(a[1])
        iid = a[3]
        site = a[4]
        (chr, pos) = split(a[4], ':')
        pos = parse(Int64, pos)
        start = pos - window
        stop  = pos + window
        range = join([chr, start, stop], ":", "-")

        (famids, tids) = split_trio_from_ped(ped, iid)

        f_outfile = join([pname[1], "_", "fam", "_", a[4], ".vcf.gz"], "")
        t_outfile = join([pname[1], "_", "trio", "_", a[4], ".vcf.gz"], "")

        if !isfile("$vcf.csi")
            println("INFO: indexing the vcf file $vcf")
            run(`bcftools index $vcf`)
        end

        rs_f = success(run(`bcftools view -s $famids -r $range --min-ac 3 -e'ALT="*" || QUAL < 100000 || FORMAT/DP < 10 || MQ < 30 || GQ < 30' $vcf -Oz -o $f_outfile`, wait=true))

        if rs_f == true
            run(`bcftools index -f $f_outfile`, wait=true)
        end

        run(pipeline(`bcftools view -H $f_outfile`, `cut -f1,2`, "famsites.txt"))

        t_tmp = success(run(`bcftools view -s $tids -R famsites.txt $vcf -Oz -o "triovcftmp.vcf.gz"`, wait=true) )

        t_tmp2 = success(run(`bcftools norm -d none triovcftmp.vcf.gz -Oz -o "triovcftmp2.vcf.gz"`))

        rs_t = success(run(`bcftools sort triovcftmp2.vcf.gz -Oz -o $t_outfile`))

        if rs_t == true
            run(`bcftools index -f $t_outfile`, wait=true)
        end

        rs_s = success(run(`bcftools view -s $tids -r $site $t_outfile -Oz -o $site.only.vcf.gz`, wait=true) )

        if rs_s == true
            run(`bcftools index -f $site.only.vcf.gz`, wait=true)
        end

        run(`bcftools filter -i 'FMT/DP > 99999999' -S . -r $site $site.only.vcf.gz -Oz -o missing.vcf.gz`, wait=true)

        function getSTRmut(iid)
            child = split(read(`bcftools view -H -s $iid $site.only.vcf.gz `, String), '\t')
            cs = Set([child[end][1], child[end][3]])
            cs_geno = join([ child[end][1], child[end][3] ], "/")
            par = split(read(`bcftools view -H -s ^$iid $site.only.vcf.gz `, String), '\t')
            ps_ids = split(chomp(read(`bash -c "bcftools view -h -s ^$iid $site.only.vcf.gz | tail -n1 | cut -f10-"`, String)), '\t')
            ps = Set( [ par[end][1], par[end][3], par[end-1][1], par[end-1][3] ])

            p1 = ps_ids[1]
            p2 = ps_ids[2]
            par_genos = (p1, par[end-1][1], par[end-1][3], p2, par[end][1], par[end][3] )

            mutSTR = collect(setdiff(cs, ps))

            raw_genos = join([ p1, ": ", par[end-1][1], "/", par[end-1][3], ",  ", p2, ": ", par[end][1], "/", par[end][3], ",  ", "Parent (child $p1 x $p2): ", cs_geno], "")

            if length(mutSTR) == 0
                error("no unique STR allele in child: $par_genos -> $cs_geno")
            end

            mutSTR = parse(Int, mutSTR[1])
            return mutSTR, par_genos, raw_genos
        end

        (mutSTR, par_genos, raw_genos) = getSTRmut(iid)   #child STR allele ∉ parents

        rs_ms = success(run(`cp missing.vcf.gz $site.only.vcf.gz`, wait=true) )

        if rs_ms == true
            run(`rm -f missing.vcf.gz`)
            run(`bcftools index -f $site.only.vcf.gz`)
        end

        #println("INFO: Phasing flanking SNPs genotypes")

        function micro_phaser(vcf, ped)

            if Sys.which("beagle.r1399.jar") == nothing
                error("beagle.r1399.jar is required in your path")
            else
                beagle = Sys.which("beagle.r1399.jar")
            end
            run(`bash -c "java -Xmx1g -jar $beagle gt=$vcf ped=$ped out=phased 1>log.out 2>error.out"`)
            run(`bcftools index -f phased.vcf.gz`)
            run(`mv phased.vcf.gz $vcf`)
            run(`mv phased.vcf.gz.csi $vcf.csi`)

        end

        famped = join([ped, "fam"], '.')
        trioped = join([ped, "trio"], '.')

        micro_phaser(f_outfile, famped)
        micro_phaser(t_outfile, trioped)

        tm = success(run(`bcftools concat $site.only.vcf.gz $t_outfile -Oz -o trio_merged.vcf.gz`) )

        tms = success(run(`bcftools sort trio_merged.vcf.gz -Oz -o trio_merged_sort.vcf.gz`) )

        if tms == true
            run(`bcftools index  -f trio_merged_sort.vcf.gz`)
        end

        run(`bash -c "mv trio_merged_sort.vcf.gz $t_outfile"`)
        run(`bcftools index -f $t_outfile`)

        #Need to rematch  and renorm the sites due to misinheritances
        #thrown out when phasing in some trios
        run(pipeline(`bcftools view -H $t_outfile`, `cut -f1,2`, "famsites_t.txt"))

        f_tmp = success(run(`bcftools view -s $famids -R famsites_t.txt $f_outfile -Oz -o fam_rematchedtmp.vcf.gz`, wait=true) )

        f_tmp2 = success(run(`bcftools norm -d none fam_rematchedtmp.vcf.gz -Oz -o fam_rematchedtmp2.vcf.gz`))

        rs_ft = success(run(`bcftools sort fam_rematchedtmp2.vcf.gz -Oz -o $f_outfile`))

        if rs_ft == true
            run(`bcftools index -f $f_outfile`)
        end

        run(`bash -c "rm -f trio_merged.vcf.gz $site.only.vcf.gz trio_merged_sort.vcf.gz.csi  $site.only.vcf.gz.csi famsites.txt phased.* famsites_t.txt *tmp*" `)

        printstyled("INFO: unphased de novo trio genotypes: ", raw_genos, "\n", color=:light_green)

        STR_location = a[4]

        push!(outdat, [f_outfile, famped, STR_location, iid, t_outfile, trioped, mutSTR, par_genos] )

        flines = strip(read(`bash -c "bcftools view -H $f_outfile | wc -l" `, String))
        tlines = strip(read(`bash -c "bcftools view -H $f_outfile | wc -l" `, String))

        if flines != tlines
            error("Varinats in vcfs not equal for $STR_location, got fam vcf=$flines, trio vcf=$tlines. Suggest removing $STR_location.")
            exit()
        end

    return outdat

end

max_stars_repo_name: ScottWatkins/STRdiff

max_issues_repo_name: ScottWatkins/STRdiff

max_forks_repo_name: ScottWatkins/STRdiff


text:
#This is a short-term solution. Options are replicating SparseArrays.sprand exactly
# or just import(sprand(...))
function sprand(
    r::AbstractRNG,
    m::Integer,
    n::Integer,
    density::AbstractFloat,
    rfn::Function,
    ::Type{T} = eltype(rfn(r, 1))
) where T
    m, n = Int(m), Int(n)
    (m <= 0 || n <= 0) && throw(ArgumentError("Invalid Array Dimensions"))
    0 <= density <= 1 || throw(ArgumentError("$density ∉ [0,1]"))
    I = randsubseq(r, 1:(m*n), density)
    Ix = similar(I)
    Jx = similar(I)
    for i ∈ 1:length(I)
        x, y = divrem(I[i], m)
        if y == 0
            Jx[i] = x
            Ix[i] = n
        else
            Jx[i] = x + 1
            Ix[i] = y
        end
    end
    print(I)
    print(Ix)
    print(Jx)
    return GBMatrix(Ix, Jx, rfn(r, length(I)); nrows = m, ncols = n)
end

function sprand(::Type{T}, m::Integer, n::Integer, density::AbstractFloat) where T
    sprand(default_rng(), m, n, density, (r, i) -> rand(r, T, i), T)
end


text:
using ChainLadder
using CSV
using Test
using DataFrames

raa = CSV.File("data/raa.csv") |> DataFrame
@testset "ChainLadder.jl" begin
    t = ClaimTriangle(raa,:origin,:development,:values,CumulativeTriangle())
    @test all(latest_diagonal(t) .== [18834.0,16704.0,23466.0,27067.0,26180.0,15852.0,12314.0,13112.0,5395.0,2063.0])

    lr1 = link_ratio(t.type,t.values[1])
    lrend =  link_ratio(t.type,t.values[end-1])
    @test all(lr1 .== [1.6498403830806065, 1.319022856451808, 1.0823324470523517, 1.1468869123252858, 1.1951399660240787, 1.1129720042024598, 1.0332611472041757, 1.002901977644024, 1.0092165898617511])
    @test all(lrend .== [1.7219917012448134])

    lr = link_ratio(t)

    @test all(lr1 .== lr[1])
    @test all(lrend .== lr[end])
end