text:
# point = Point(locaslID, x, y, left, right, flag_1, flag_2, nbhs, conn, nx, ny, prim, flux_res, q, dq, entropy, xpos_nbhs, xneg_nbhs, ypos_nbhs, yneg_nbhs, xpos_conn, xneg_conn, ypos_conn, yneg_conn, delta)

function setNormals(self::Point, n)
    self.nx = n[1]
    self.ny = n[2]
    return nothing
end

function getxy(self)
    return (self.x, self.y)
end

function setConnectivity(self, conn)
    self.xpos_conn = conn[1]
    self.xpos_nbhs = length(conn[1])
    self.xneg_conn = conn[2]
    self.xneg_nbhs = length(conn[2])
    self.ypos_conn = conn[3]
    self.ypos_nbhs = length(conn[3])
    self.yneg_conn = conn[4]
    self.yneg_nbhs = length(conn[4])
    return nothing
end

# function setSmallestPointDistance(self::Point, distance)
#     self.short_distance = distance
# end

max_stars_repo_name: TestSubjector/HybridMeshfreeSolver

max_issues_repo_name: TestSubjector/HybridMeshfreeSolver

max_forks_repo_name: TestSubjector/HybridMeshfreeSolver


text:
module SoftSurfaceDynamics
### Tools necessary to compute and integrate surface evolution

### Things which could belong to this package

# meshpincher(msh)
# meshmerger(msh1,msh2)
# patchmerger(msh1,msh2)
# curvature calculation [Done]
# fixtopology(msh)
# meshstabilizer

include("properties.jl")
include("velocity.jl")
include("meshes.jl")
include("kineticstabilizer.jl")

export unitsphere, meancurvatures, normals, surfacevolume, vertexareas, stokesvelocity
# export KineticStabilizer, stabilize!

end # module

ext: jl


text:
push!(LOAD_PATH, "./src")
using DelimitedFiles

using WriteVTK

using CommonUtils
using Basis1D
using Basis2DQuad
using UniformQuadMesh
using UnPack

using SetupDG
using SparseArrays

N = 2
K1D = 400
CFL = 0.9
Np = (N+1)*(N+1)

"Mesh related variables"
VX, VY, EToV = uniform_quad_mesh(2*K1D,K1D)
@. VX = (VX+1)/2
@. VY = (VY+1)/4
# @. VX = ((VX+1)/2)^(.25)
# @. VY = ((VY+1)/2)^(2)/2

rd = init_reference_quad(N,gauss_lobatto_quad(0,0,N))
md = init_mesh((VX,VY),EToV,rd)
@unpack x,y,mapP,rxJ,syJ,J,sJ,nxJ,nyJ = md;

@unpack VDM,Vf,LIFT,M,Dr,Ds = rd
droptol!(sparse(M),1e-16)
rp,sp = equi_nodes_2D(10)
Vp = vandermonde_2D(N,rp,sp)/VDM

x_vtk = []
y_vtk = []
for k = 1:Int(round(2*K1D))
    push!(x_vtk,x[1,k])
    push!(x_vtk,x[2,k])
    push!(x_vtk,x[3,k])
    # push!(x_vtk,x[4,k])
    # push!(x_vtk,x[5,k])
end
for k = 1:K1D
    # push!(y_vtk,y[1,1+(k-1)*2*K1D])
    # push!(y_vtk,y[5,1+(k-1)*2*K1D])
    # push!(y_vtk,y[9,1+(k-1)*2*K1D])
    # push!(y_vtk,y[13,1+(k-1)*2*K1D])
    # push!(y_vtk,y[1,1+(k-1)*2*K1D])
    # push!(y_vtk,y[6,1+(k-1)*2*K1D])
    # push!(y_vtk,y[11,1+(k-1)*2*K1D])
    # push!(y_vtk,y[16,1+(k-1)*2*K1D])
    # push!(y_vtk,y[21,1+(k-1)*2*K1D])
    push!(y_vtk,y[1,1+(k-1)*2*K1D])
    push!(y_vtk,y[4,1+(k-1)*2*K1D])
    push!(y_vtk,y[7,1+(k-1)*2*K1D])
    # push!(y_vtk,y[1,1+(k-1)*2*K1D])
    # push!(y_vtk,y[3,1+(k-1)*2*K1D])
end
x_vtk = x_vtk .* ones((N+1)*K1D,1)'
y_vtk = y_vtk' .* ones((N+1)*Int(round(2*K1D)),1)

rho_vtk,rhou_vtk,rhov_vtk,E_vtk,gradg_vtk,tmp_vtk = (zeros(size(x_vtk)) for i = 1:6)

vtk_grid("N=$N,K1D=$K1D,t=$t,CFL=$CFL",x_vtk,y_vtk) do vtk
    rho = readdlm("N=$N,K1D=$K1D,t=$t,CFL=$CFL,rho,shocktube.txt")
    rhou = readdlm("N=$N,K1D=$K1D,t=$t,CFL=$CFL,rhou,shocktube.txt")
    rhov = readdlm("N=$N,K1D=$K1D,t=$t,CFL=$CFL,rhov,shocktube.txt")
    E = readdlm("N=$N,K1D=$K1D,t=$t,CFL=$CFL,E,shocktube.txt")
    gradg = readdlm("N=$N,K1D=$K1D,t=$t,CFL=$CFL,gradg,shocktube.txt")

    # g   = sqrt.((rx.*(Dr*rho)).^2 .+ (sy.*(Ds*rho)).^2)
    # g_min = minimum(g)
    # g_max = maximum(g)
    # vv = @. exp(-10*(g-g_min)/(g_max-g_min))
    rx = rxJ./J
    sy = syJ./J
    rhof = Vf*rho
    rhoP = rhof[mapP]
    Dxrho = rx.*(Dr*rho) +.5*(1.0 ./J).*(LIFT*(nxJ.*(rhoP-rhof)))
    Dyrho = sy.*(Ds*rho) +.5*(1.0 ./J).*(LIFT*(nyJ.*(rhoP-rhof)))
    g = sqrt.(Dxrho.^2 .+ Dyrho.^2)
    g_min = minimum(g)
    g_max = maximum(g)
    vv = @. exp(-10*(g-g_min)/(g_max-g_min))

    for k = 1:Int(round(2*K1D))*K1D
        kx = mod1(k,Int(round(2*K1D)))
        ky = div(k-1,Int(round(2*K1D)))+1

        rho_vtk[(kx-1)*(N+1)+1:(kx-1)*(N+1)+N+1, (ky-1)*(N+1)+1:(ky-1)*(N+1)+N+1] = rho[:,k]
        rhou_vtk[(kx-1)*(N+1)+1:(kx-1)*(N+1)+N+1, (ky-1)*(N+1)+1:(ky-1)*(N+1)+N+1] = rhou[:,k]
        rhov_vtk[(kx-1)*(N+1)+1:(kx-1)*(N+1)+N+1, (ky-1)*(N+1)+1:(ky-1)*(N+1)+N+1] = rhov[:,k]
        E_vtk[(kx-1)*(N+1)+1:(kx-1)*(N+1)+N+1, (ky-1)*(N+1)+1:(ky-1)*(N+1)+N+1] = E[:,k]
        gradg_vtk[(kx-1)*(N+1)+1:(kx-1)*(N+1)+N+1, (ky-1)*(N+1)+1:(ky-1)*(N+1)+N+1] = gradg[:,k]
        tmp_vtk[(kx-1)*(N+1)+1:(kx-1)*(N+1)+N+1, (ky-1)*(N+1)+1:(ky-1)*(N+1)+N+1] = vv[:,k]
    end

    vtk["rho"]  = rho_vtk
    vtk["rhou"] = rhou_vtk
    vtk["rhov"] = rhov_vtk
    vtk["E"]    = E_vtk
    vtk["gradg"]    = gradg_vtk
    vtk["tmp"]    = tmp_vtk
end

max_stars_repo_name: yiminllin/ESDG-PosLimit

max_issues_repo_name: yiminllin/ESDG-PosLimit

max_forks_repo_name: yiminllin/ESDG-PosLimit


text:
"""
    core_number(g)

Return the core number for each vertex in graph `g`.

A k-core is a maximal subgraph that contains vertices of degree `k` or more.
The core number of a vertex is the largest value `k` of a k-core containing
that vertex.

### Implementation Notes
Not implemented for graphs with self loops.

### References
* An O(m) Algorithm for Cores Decomposition of Networks,
    Vladimir Batagelj and Matjaz Zaversnik, 2003.
    http://arxiv.org/abs/cs.DS/0310049

# Examples
```jldoctest
julia> using LightGraphs

julia> g = path_graph(5);

julia> add_vertex!(g);

julia> add_edge!(g, 5, 2);

julia> core_number(g)
6-element Array{Int64,1}:
 1
 2
 2
 2
 2
 0
```
"""
function core_number(g::AbstractGraph{T}) where T
    has_self_loops(g) && throw(ArgumentError("graph must not have self-loops"))
    n = nv(g)
    deg = T.(degree(g)) # this will contain core number for each vertex of graph
    maxdeg = maximum(deg) # maximum degree of a vertex in graph
    bin = zeros(T, maxdeg+1) # used for bin-sort and storing starting positions of bins
    vert = zeros(T, n) # contains the set of vertices, sorted by their degrees
    pos = zeros(T, n) # contains positions of vertices in array vert

    # count number of vertices will be in each bin
    for v = 1:n
        bin[deg[v]+1] += one(T)
    end
    # from bin sizes determine starting positions of bins in array vert
    start = one(T)
    for d = zero(T):maxdeg
        num = bin[d+1]
        bin[d+1] = start
        start += num
    end
    # sort the vertices in increasing order of their degrees and store in array vert
    for v in vertices(g)
        pos[v] = bin[deg[v]+1]
        vert[pos[v]] = v
        bin[deg[v]+1] += one(T)
    end

    # recover starting positions of the bins
    for d = maxdeg:-1:one(T)
       bin[d+1] = bin[d]
    end
    bin[1] = one(T)

    # cores decomposition
    for i = 1:n
        v = vert[i]
        # for each neighbor u of vertex v with higher degree we have to decrease its degree and move it for one bin to the left
        for u in outneighbors(g, v)
            if deg[u] > deg[v]
                du = deg[u]
                pu = pos[u]
                pw = bin[du+1]
                w = vert[pw]
                if u != w
                    pos[u] = pw
                    vert[pu] = w
                    pos[w] = pu
                    vert[pw] = u
                end
                bin[du+1] += one(T)
                deg[u] -= one(T)
            end
        end
        if is_directed(g)
	        for u in inneighbors(g, v)
	            if deg[u] > deg[v]
	                du = deg[u]
	                pu = pos[u]
	                pw = bin[du+1]
	                w = vert[pw]
	                if u != w
	                    pos[u] = pw
	                    vert[pu] = w
	                    pos[w] = pu
	                    vert[pw] = u
	                end
	                bin[du+1] += one(T)
	                deg[u] -= one(T)
	            end
	        end
	    end
    end

    return deg
end

"""
    k_core(g[, k]; corenum=core_number(g))

Return a vector of vertices in the k-core of graph `g`.
If `k` is not specified, return the core with the largest degree.

A k-core is a maximal subgraph that contains vertices of degree `k` or more.

### Implementation Notes
Not implemented for graphs with self loops.

### References
- An O(m) Algorithm for Cores Decomposition of Networks,
    Vladimir Batagelj and Matjaz Zaversnik, 2003.
    http://arxiv.org/abs/cs.DS/0310049

# Examples
```jldoctest
julia> using LightGraphs

julia> g = path_graph(5);

julia> add_vertex!(g);

julia> add_edge!(g, 5, 2);

julia> k_core(g, 1)
5-element Array{Int64,1}:
 1
 2
 3
 4
 5

julia> k_core(g, 2)
4-element Array{Int64,1}:
 2
 3
 4
 5
```
"""
function k_core(g::AbstractGraph, k=-1; corenum=core_number(g))
    if (k == -1)
        k = maximum(corenum) # max core
    end

    return findall(x -> x >= k, corenum)
end

"""
    k_shell(g[, k]; corenum=core_number(g))

Return a vector of vertices in the k-shell of `g`.
If `k` is not specified, return the shell of the core
with the largest degree.

The k-shell is the subgraph of vertices in the `k`-core but not in
the (`k+1`)-core. This is similar to `k_corona` but in that case
only neighbors in the k-core are considered.

### Implementation Notes
Not implemented for graphs with parallel edges or self loops.

### References
- A model of Internet topology using k-shell decomposition
   Shai Carmi, Shlomo Havlin, Scott Kirkpatrick, Yuval Shavitt,
   and Eran Shir, PNAS  July 3, 2007   vol. 104  no. 27  11150-11154
   http://www.pnas.org/content/104/27/11150.full

# Examples
```jldoctest
julia> using LightGraphs

julia> g = path_graph(5);

julia> add_vertex!(g);

julia> add_edge!(g, 5, 2);

julia> k_shell(g, 0)
1-element Array{Int64,1}:
 6

julia> k_shell(g, 1)
1-element Array{Int64,1}:
 1

julia> k_shell(g, 2)
4-element Array{Int64,1}:
 2
 3
 4
 5
```
"""
function k_shell(g::AbstractGraph, k=-1; corenum=core_number(g))
    if k == -1
        k = maximum(corenum)
    end
    return findall(x -> x == k, corenum)
end

"""
    k_crust(g[, k]; corenum=core_number(g))

Return a vector of vertices in the k-crust of `g`.
If `k` is not specified, return the crust of the core with
the largest degree.

The k-crust is the graph `g` with the [`k-core`](@ref k_core) removed.

### Implementation Notes
This definition of k-crust is different than the definition in References.
The k-crust in References is equivalent to the `k+1` crust of this algorithm.

Not implemented for graphs with self loops.

### References
- A model of Internet topology using k-shell decomposition
   Shai Carmi, Shlomo Havlin, Scott Kirkpatrick, Yuval Shavitt,
   and Eran Shir, PNAS  July 3, 2007   vol. 104  no. 27  11150-11154
   http://www.pnas.org/content/104/27/11150.full

# Examples
```jldoctest
julia> using LightGraphs

julia> g = path_graph(5);

julia> add_vertex!(g);

julia> add_edge!(g, 5, 2);

julia> k_crust(g, 0)
1-element Array{Int64,1}:
 6

julia> k_crust(g, 1)
2-element Array{Int64,1}:
 1
 6

julia> k_crust(g, 2)
6-element Array{Int64,1}:
 1
 2
 3
 4
 5
 6
```
"""
function k_crust(g, k=-1; corenum=core_number(g))
    if k == -1
        k = maximum(corenum) - 1
    end
    return findall(x -> x <= k, corenum)
end

"""
    k_corona(g, k; corenum=core_number(g))

Return a vector of vertices in the k-corona of `g`.

The k-corona is the subgraph of vertices in the [`k-core`](@ref k_core) which
have exactly `k` neighbors in the k-core.

### Implementation Notes
Not implemented for graphs with parallel edges or self loops.

### References

- k-core (bootstrap) percolation on complex networks:
   Critical phenomena and nonlocal effects,
   A. V. Goltsev, S. N. Dorogovtsev, and J. F. F. Mendes,
   Phys. Rev. E 73, 056101 (2006)
   http://link.aps.org/doi/10.1103/PhysRevE.73.056101

# Examples
```jldoctest
julia> using LightGraphs

julia> g = path_graph(5);

julia> add_vertex!(g);

julia> add_edge!(g, 5, 2);

julia> k_corona(g, 0)
1-element Array{Int64,1}:
 6

julia> k_corona(g, 1)
1-element Array{Int64,1}:
 1

julia> k_corona(g, 2)
4-element Array{Int64,1}:
 2
 3
 4
 5

julia> k_corona(g, 3)
0-element Array{Int64,1}
```
"""
function k_corona(g::AbstractGraph, k; corenum=core_number(g))
    kcore = k_core(g, k)
    kcoreg = g[kcore]
    kcoredeg = degree(kcoreg)

    return kcore[findall(x-> x == k, kcoredeg)]
end


text:
using Documenter, Gen

makedocs(
    format = :html,
    sitename = "Gen",
    pages = [
        "index.md",
        "documentation.md"
    ]
)

max_stars_repo_name: BoltzmannBrain/Gen

max_issues_repo_name: BoltzmannBrain/Gen

max_forks_repo_name: BoltzmannBrain/Gen


text:
using ThreeBodyTB

function example_run_dft()

    # In this example, we fit a simple model. A robust TB model would require much more data.

    #First, it is necessary to run the DFT calculations, for example, we could define
    #a crystal as

    A = [5.33955  5.33955  0.0;5.33955  0.0      5.33955;0.0      5.33955  5.33955] * 0.529177
    pos = [0 0 0; 0.25 0.25 0.25]
    names = ["Mg", "S"]

    c = makecrys(A, pos, names)

    # To run the dft calculation, first we have to tell the code where QE (quantum espresso) is.

    ThreeBodyTB.set_bin_dirs(qe="/home/kfg/codes/qe-6.6/bin/") # you must give the code your own QE !!!!

    # You may also want to include an MPI command like

    ThreeBodyTB.set_bin_dirs(mpi="mpirun -np ")

    # Lets create an output directory

    mkpath("dft_out")

    dft = missing

    try

        # Then we could run a job like

        dft = ThreeBodyTB.DFT.runSCF(c, directory="dft_out", tmpdir="dft_out")

        # if you add a variable nprocs = 8, it will run in parallel on 8 processors. This will take a minute or two on modern computers.

        # This returns a dft output object, which you could also load later with :

        dft2 = ThreeBodyTB.QE.loadXML("dft_out/qe.save/")

    catch

        # if you don't have QE installed, this won't work obviously. However, I already ran this calculation for you, we can load the results

        dft = ThreeBodyTB.QE.loadXML(ThreeBodyTB.TESTDIR * "/data_forces/znse.in_vnscf_vol_2/qe.save")

    end

    # To calculate the tight-binding k-space object, we can use
    tbck=missing

    try

        workd = "dft_out/"
        tbc, tbck, proj_warn = ThreeBodyTB.AtomicProj.projwfc_workf(dft, directory=workd, writefile="projham_K.xml", only_kspace = true)
        #this will take a minute or two as well, and can be run in parallel

    catch

        # using precalculated data

        workd = ThreeBodyTB.TESTDIR * "/data_forces/znse.in_vnscf_vol_2/"
        tbc, tbck, proj_warn = ThreeBodyTB.AtomicProj.projwfc_workf(dft, directory=workd, writefile="projham_K.xml", only_kspace = true)

    end

    #remove self-consistent terms from tbck, so we get the corrent answer back when we solve self-consistently
    tbck_scf = ThreeBodyTB.SCF.remove_scf_from_tbc(tbck)

    return dft
end

function do_fitting(dft_ref)

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

    # Now that we have seen how to prepare one dft calculation, lets load all the data we need
    # which is precalculated.

    TESTDIR = ThreeBodyTB.TESTDIR

    ft = open("$TESTDIR/data_forces/fil_MgS_znse", "r"); #the list of files we need.
    dirst = readlines(ft);
    close(ft);

    tbc_list = []
    dft_list = []

    #here we load the data
    for t in dirst
        tfull = "$TESTDIR/"*t
        try #try to load from xml files

            dft = ThreeBodyTB.QE.loadXML(tfull*"/qe.save")

            tbck = ThreeBodyTB.TB.read_tb_crys_kspace("projham_K.xml.gz", directory=tfull)

            tbck_scf = ThreeBodyTB.SCF.remove_scf_from_tbc(tbck)

            push!(dft_list, dft)
            push!(tbc_list, tbck_scf)

        catch
            println("missing data $tfull")
        end

    end

    # We only want to fit the Mg-S interactions, not the Mg-Mg or S-S. So we will give those to the fitting algorithm as the starting data, which is fixed.

    ThreeBodyTB.ManageDatabase.clear_database() #make sure nothing is pre-cached
    ThreeBodyTB.ManageDatabase.prepare_database(["Mg"])
    ThreeBodyTB.ManageDatabase.prepare_database(["S"])
    database_start = deepcopy(ThreeBodyTB.ManageDatabase.database_cached)
    ThreeBodyTB.ManageDatabase.clear_database() #make sure nothing is pre-cached

    #now we do the new fitting.

    database_new = ThreeBodyTB.FitTB.do_fitting_recursive(tbc_list, dft_list = dft_list, starting_database = database_start)

    #now we run an example calculation with the new database

    energy_tot, tbc, conv_flag = scf_energy(dft_ref.crys, database=database_new)

    println("We can compare our model energy $energy_tot with the DFT atomization energy ", dft_ref.atomize_energy)

    #println("note that this model is badly overfit and needs more data")

end

dft = example_run_dft()
do_fitting(dft)


text:
using TALib
using Base.Test

include("test_level0.jl")
include("test_level1.jl")
include("test_level2_dataframes.jl")
include("test_level2_timearrays.jl")

# write your own tests here
# @test 1 == 1


text:
"""
    struct ElementMatrix{T, TM <: AbstractMatrix{T}} <: AbstractMatrix{T}
        matrix::TM
        mask
        meandiag::T
    end

An element stiffness matrix. `matrix` is the unconstrained element stiffness matrix. `mask` is a `BitVector` where `mask[i]` is 1 iff the local degree of freedom `i` is not constrained by a Dirichlet boundary condition. `meandiag` is the mean of the diagonal of the unconstrained element stiffness matrix.
"""
@params struct ElementMatrix{T, TM <: AbstractMatrix{T}} <: AbstractMatrix{T}
    matrix::TM
    mask
    meandiag::T
end
ElementMatrix(matrix, mask) = ElementMatrix(matrix, mask, sumdiag(matrix)/size(matrix, 1))
Base.show(::IO, ::MIME{Symbol("text/plain")}, ::ElementMatrix) = println("TopOpt element matrix")

"""
    rawmatrix(m::ElementMatrix)

Returns the unconstrained element stiffness matrix `m.matrix`.
"""
rawmatrix(m::ElementMatrix) = m.matrix
rawmatrix(m::Symmetric{T, <:ElementMatrix{T}}) where {T} = Symmetric(m.data.matrix)

"""
    bcmatrix(m::ElementMatrix{T, TM}) where {dim, T, TM <: StaticMatrix{dim, dim, T}}

Returns the constrained element stiffness matrix where the elements in the rows and columns corresponding to any local degree of freedom with a Dirichlet boundary condition are replaced by 0.
"""
@generated function bcmatrix(m::ElementMatrix{T, TM}) where {dim, T, TM <: StaticMatrix{dim, dim, T}}
    expr = Expr(:tuple)
    for j in 1:dim, i in 1:dim
        push!(expr.args, :(ifelse(m.mask[$i] && m.mask[$j], m.matrix[$i,$j], zero(T))))
    end
    return :($(Expr(:meta, :inline)); $TM($expr))
end
@generated function bcmatrix(m::Symmetric{T, <:ElementMatrix{T, TM}}) where {dim, T, TM <: StaticMatrix{dim, dim, T}}
    expr = Expr(:tuple)
    for j in 1:dim, i in 1:dim
        push!(expr.args, :(ifelse(m.data.mask[$i] && m.data.mask[$j], m.data.matrix[$i,$j], zero(T))))
    end
    return :($(Expr(:meta, :inline)); Symmetric($TM($expr)))
end

Base.size(m::ElementMatrix) = size(m.matrix)
Base.getindex(m::ElementMatrix, i...) = m.matrix[i...]

"""
    convert(::Type{Vector{<:ElementMatrix}}, Kes::Vector{<:AbstractMatrix})

Converts the element stiffness matrices `Kes` from an abstract vector of matrices to a vector of instances of the type `ElementMatrix`.
"""
function Base.convert(
    ::Type{Vector{<:ElementMatrix}},
    Kes::Vector{TM};
    bc_dofs,
    dof_cells,
) where {
    N, T, TM <: StaticMatrix{N, N, T},
}
    fill_matrix = zero(TM)
    fill_mask = ones(SVector{N, Bool})
    element_Kes = fill(ElementMatrix(fill_matrix, fill_mask), length(Kes))
    for i in bc_dofs
        d_cells = dof_cells[i]
        for c in d_cells
            (cellid, localdof) = c
            Ke = element_Kes[cellid]
            new_Ke = @set Ke.mask[localdof] = false
            element_Kes[cellid] = Symmetric(new_Ke)
        end
    end
    for e in 1:length(element_Kes)
        Ke = element_Kes[e]
        matrix = Kes[e]
        Ke = @set Ke.matrix = matrix
        element_Kes[e] = @set Ke.meandiag = sumdiag(Ke.matrix)
    end
    return element_Kes
end
function Base.convert(
    ::Type{Vector{<:ElementMatrix}},
    Kes::Vector{Symmetric{T, TM}};
    bc_dofs,
    dof_cells,
) where {
    N, T, TM <: StaticMatrix{N, N, T},
}
    fill_matrix = zero(TM)
    fill_mask = ones(SVector{N, Bool})
    element_Kes = fill(Symmetric(ElementMatrix(fill_matrix, fill_mask)), length(Kes))
    for i in bc_dofs
        d_cells = dof_cells[i]
        for c in d_cells
            (cellid, localdof) = c
            Ke = element_Kes[cellid].data
            new_Ke = @set Ke.mask[localdof] = false
            element_Kes[cellid] = Symmetric(new_Ke)
        end
    end
    for e in 1:length(element_Kes)
        Ke = element_Kes[e].data
        matrix = Kes[e].data
        Ke = @set Ke.matrix = matrix
        element_Kes[e] = Symmetric(@set Ke.meandiag = sumdiag(Ke.matrix))
    end
    return element_Kes
end
function Base.convert(
    ::Type{Vector{<:ElementMatrix}},
    Kes::Vector{TM};
    bc_dofs,
    dof_cells,
) where {
    T, TM <: AbstractMatrix{T},
}
    N = size(Kes[1], 1)
    fill_matrix = zero(TM)
    fill_mask = ones(Bool, N)
    element_Kes = [deepcopy(ElementMatrix(fill_matrix, fill_mask)) for i in 1:length(Kes)]
    for i in bc_dofs
        d_cells = dof_cells[i]
        for c in d_cells
            (cellid, localdof) = c
            Ke = element_Kes[cellid]
            Ke.mask[localdof] = false
        end
    end
    return element_Kes
end
function Base.convert(
    ::Type{Vector{<:ElementMatrix}},
    Kes::Vector{Symmetric{T, TM}};
    bc_dofs,
    dof_cells,
) where {
    T, TM <: AbstractMatrix{T},
}
    N = size(Kes[1], 1)
    fill_matrix = zero(TM)
    fill_mask = ones(Bool, N)
    element_Kes = [
        Symmetric(deepcopy(ElementMatrix(fill_matrix, fill_mask))) for i in 1:length(Kes)
    ]
    for i in bc_dofs
        d_cells = dof_cells[i]
        for c in d_cells
            (cellid, localdof) = c
            Ke = element_Kes[cellid].data
            Ke.mask[localdof] = false
        end
    end
    return element_Kes
end

for TM in (:(StaticMatrix{m, m, T}), :(Symmetric{T, <:StaticMatrix{m, m, T}}))
    @eval begin
        @generated function sumdiag(K::$TM) where {m,T}
            return reduce((ex1,ex2) -> :($ex1 + $ex2), [:(K[$j,$j]) for j in 1:m])
        end
    end
end
@doc """
sumdiag(K::Union{StaticMatrix, Symmetric{<:Any, <:StaticMatrix}})

Computes the sum of the diagonal of the static matrix `K`.
""" sumdiag


text:
# This file includes methods for processing the foodweb dataset available here
#   https://snap.stanford.edu/data/Florida-bay.html
# and described in
#   Robert E. Ulanowicz, Cristina Bondavalli, and Michael S. Egnotovich, 1997, Network analysis of
#   trophic dynamics in South Florida ecosystems--The Florida Bay Ecosystem: Annual Report to the
#   U.S. Geological Survey, Biological Resources Division.
# and
#   Austin R. Benson, David F. Gleich, and Jure Leskovec.
#   "Higher-order Organization of Complex Networks." (2016). Science, 353.6295 (2016): 163–166.
using CSV
using DataFrames

META_FILENAME = "Florida-bay-meta.csv"
EDGELIST_FILENAME = "Florida-bay.txt"

"""
  writeFoodwebNetwork(foodwebDirectory)

Write the foodweb data files to the given directory.

The supplied directory must contain the extracted foodweb data files from
https://snap.stanford.edu/data/Florida-bay.html.

We drop vertices which are labeled detritus.
"""
function writeFoodwebNetwork(foodwebDirectory::String)
    # Start by writing the edgeslist file. This is quite straightforward. We will remove the
    # commented lines from the original file which might be unnecessary, but it could simplify
    # downstream processing.
    input_filename = joinpath(foodwebDirectory, EDGELIST_FILENAME)
    output_filename = joinpath(foodwebDirectory, "foodweb.edgelist")

    # Hardcode the detritus nodes. It turns out we can just ignore those above 124.
    detritus_nodes_above = 123

    edgelist_df = DataFrame(CSV.File(input_filename, comment="#", header=false))

    # We hardcode some vertices to ignore
    n = 128
    ignore_vertices = [12, 123, 124, 126]

    # Figure out how to correct each node index once we've ignored those above
    index_corrections = Dict()
    current_correction = 0
    for index = 1:n
        index_corrections[index] = index - current_correction
        if index in ignore_vertices
            current_correction += 1
        end
    end

    open(output_filename, "w") do f_out
        for row in eachrow(edgelist_df)
            if (row[1] + 1) ∉ ignore_vertices && (row[2] + 1) ∉ ignore_vertices
                write(f_out, repr(index_corrections[row[1] + 1]), " ",
                      repr(index_corrections[row[2] + 1]), "\n")
            end
        end
    end

    # Now, lets read in the rest of the data, and see what we can do with it
    input_filename = joinpath(foodwebDirectory, META_FILENAME)
    meta_df = DataFrame(CSV.File(input_filename))

    # The first thing we can do is save the vertex names
    output_filename = joinpath(foodwebDirectory, "foodweb.vertices")
    open(output_filename, "w") do f_out
        for row in eachrow(meta_df)
            if (row["node_id"] + 1) ∉ ignore_vertices
                write(f_out, row["name"], "\n")
            end
        end
    end

    # We can now construct a list of cluster names, and then a dictionary mapping them to individual
    # indices.
    cluster_names = unique(meta_df[:, "group"])
    filter!(e -> e !== missing, cluster_names)
    cluster_dictionary = Dict(cluster => index for (index, cluster) in enumerate(cluster_names))

    # Now, we can write the ground truth clusters file
    output_filename = joinpath(foodwebDirectory, "foodweb.gt")
    open(output_filename, "w") do f_out
        for row in eachrow(meta_df)
            if (row["node_id"] + 1) ∉ ignore_vertices
                if row["group"] === missing
                    write(f_out, "0\n")
                else
                    write(f_out, repr(cluster_dictionary[row["group"]]), "\n")
                end
            end
        end
    end

    # And finally, we can write the cluster labels file
    output_filename = joinpath(foodwebDirectory, "foodweb.clusters")
    open(output_filename, "w") do f_out
        for name in cluster_names
            write(f_out, name, "\n")
        end
    end
end

"""
  writeFoodwebHypergraph(foodwebDirectory)

Construct the motif-based hypergraph from the foodweb network.

This constructed hypergraph has been used in the following papers.

Li, Pan, and Olgica Milenkovic. "Inhomogeneous Hypergraph Clustering with Applications." NIPS. 2017.

Fountoulakis, Kimon, Pan Li, and Shenghao Yang. "Local Hyper-flow Diffusion."
arXiv preprint arXiv:2102.07945 (2021).
"""
function writeFoodwebHypergraph(foodwebDirectory::String)
    # Start by writing the ordinary graph information.
    writeFoodwebNetwork(foodwebDirectory)

    # Construct two edgelists - one of 'out' edges and one of 'in' edges
    out_edgelist = Dict()
    in_edgelist = Dict()
    edges_df = DataFrame(CSV.File(joinpath(foodwebDirectory, "foodweb.edgelist"), header=false))
    for row in eachrow(edges_df)
        # Add this edge to the out-edge dict
        if row[1] ∈ keys(out_edgelist)
            if row[2] ∉ out_edgelist[row[1]]
                push!(out_edgelist[row[1]], row[2])
            end
        else
            out_edgelist[row[1]] = [row[2]]
        end

        # Add this edge to the in-edge dict
        if row[2] ∈ keys(in_edgelist)
            if row[1] ∉ in_edgelist[row[2]]
                push!(in_edgelist[row[2]], row[1])
            end
        else
            in_edgelist[row[2]] = [row[1]]
        end
    end

    # We will now add a single extra file with the hypergraph edgelist.
    output_filename = joinpath(foodwebDirectory, "foodweb_hypergraph.edgelist")
    open(output_filename, "w") do f_out
        # To find all of the motifs, we first loop over all vertices, checking if this node is prey
        for prey1 in 1:max(maximum(keys(out_edgelist)), maximum(keys(in_edgelist)))
            if !haskey(out_edgelist, prey1)
                continue
            end
            # Check each pair of 'out' edges - let these be the predators
            for pred1_idx in 1:length(out_edgelist[prey1])
                for pred2_idx in (pred1_idx + 1):length(out_edgelist[prey1])
                    predator1 = out_edgelist[prey1][pred1_idx]
                    predator2 = out_edgelist[prey1][pred2_idx]

                    # Now, look for a second prey node which has the same predators.
                    for prey2 in (prey1 + 1):max(maximum(keys(out_edgelist)),
                                                 maximum(keys(in_edgelist)))
                        if haskey(out_edgelist, prey2)
                            if predator1 ∈ out_edgelist[prey2] && predator2 ∈ out_edgelist[prey2]
                                # We have found a motif!
                                write(f_out, repr(prey1), " ", repr(prey2), " ", repr(predator1),
                                     " ", repr(predator2), "\n")
                            end
                        end
                    end
                end
            end
        end
    end
end

max_stars_repo_name: pmacg/graph-data-processing

max_issues_repo_name: pmacg/graph-data-processing

max_forks_repo_name: pmacg/graph-data-processing


text:
# Use baremodule to shave off a few KB from the serialized `.ji` file
baremodule GMP_jll
using Base
using Base: UUID
import JLLWrappers

JLLWrappers.@generate_main_file_header("GMP")
JLLWrappers.@generate_main_file("GMP", UUID("781609d7-10c4-51f6-84f2-b8444358ff6d"))
end  # module GMP_jll


text:
function plot_basic_state(y, dQdy, U, Ψ, Ly, file)

    p1 = plot(
        y,
        Ψ,
        linewidth = 3,
        label = "Ψ",
        xlabel = "y",
        title = "Streamfunction",
        xlims = (-Ly/2, Ly/2)
        )

    p2 = plot(
        y,
        U,
        linewidth = 3,
        label = "U",
        title = "Velocity",
        xlims = (-Ly/2, Ly/2)
        )

    p3 = plot(
        y,
        dQdy,
        linewidth = 3,
        label = "dQ/dy",
        xlabel = "y",
        title = "dQ/dy",
        xlims = (-Ly/2, Ly/2)
        )

    plt1 = plot(p1, p2, p3, layout = (3,1))
    savefig(plt1, file)

end

function plot_growth_rates(ks, σ, Nmodes, file)

    titles = ["1st mode", "2nd mode"]
    plt2 = plot()
    for cnt in 1:Nmodes
        plot!(plt2,
        ks,
        σ[cnt,:],
        linewidth = 3,
        label=titles[cnt],
        title="Growth Rates of QG Model",
        xlabel="k",
        xlims=(ks[1], ks[end]),
        xticks=(0:0.25:ks[end]),
        gridlinewidth=2.0
        )
    end

    savefig(plt2,file)

end

function plot_1D_streamfunction(k_index, k, Ny, y, σmodes, mode_number, file)

      Ly = params.Ly
      Lx = 2*pi/k;
      Nx = Ny;
      dx = Lx/Nx;
       x = collect(0:dx:Lx);
    X, Y = meshgrid(x,y)

    # Divide eigenvector matrix into specified spaces: u,v,eta.
    ψvec = σmodes[:, mode_number, k_index];

    plt = plot(
        y,
        real(ψvec),
        linewidth = 3,
        label = "real",
        xlabel = "y",
        title = "Streamfunction",
        xlims = (-Ly/2, Ly/2)
        )
    plot!(
        plt,
        y,
        linewidth = 3,
        imag(ψvec),
        label = "imag")
    savefig(plt, file)

end

function plot_2D_streamfunction(k_index, k, Ny, y, σmodes, mode_number, file)

    Ly = params.Ly
    Lx = 2*pi/k;
    Nx = Ny;
    dx = Lx/Nx;
     x = collect(0:dx:Lx+dx/2);
  X, Y = meshgrid(x,y[end:-1:1])

    ψvec = σmodes[1:Ny+1,        mode_number, k_index];

    ψ = repeat(real(ψvec),1,Nx+1).*cos.(k*X) - repeat(imag(ψvec),1,Nx+1).*sin.(k*X);

    kwargs = (
        xlabel = "x",
        ylabel = "y",
          fill = true,
        levels = 20,
     linewidth = 0,
         color = :balance,
      colorbar = true,
          xlim = (    0, Lx),
         ylim =  (-Ly/2, Ly/2)
    )

    plt = contour(x, y[end:-1:1], ψ[:, end:-1:1], title="ψ"; kwargs...)

    savefig(plt, file)

end

function plot_2D_vorticity(k_index, k, Ny, y, Dy2, σmodes, mode_number, file)

    Ly = params.Ly
    Lx = 2*pi/k;
    Nx = Ny;
    dx = Lx/Nx;
     x = collect(0:dx:Lx+dx/2);
  X, Y = meshgrid(x,y[end:-1:1])

    ψvec = σmodes[1:Ny+1,        mode_number, k_index];

    ζvec = Dy2*ψvec - k*k*ψvec

    ζ = repeat(real(ζvec),1,Nx+1).*cos.(k*X) - repeat(imag(ζvec),1,Nx+1).*sin.(k*X);

    kwargs = (
        xlabel = "x",
        ylabel = "y",
          fill = true,
        levels = 20,
     linewidth = 0,
         color = :balance,
      colorbar = true,
          xlim = (    0, Lx),
         ylim =  (-Ly/2, Ly/2)
    )

    plt = contour(x, y[end:-1:1], ζ[:, end:-1:1], title="ζ"; kwargs...)

    savefig(plt, file)

end


text:
"""
QTL parameters.
- **pos**: QTL location indices of the SNPs
- **effect**: effects of allele `1`, of each QTL
"""
struct QTL
    pos
    effect
end


text:
using SpeedyWeather
using Test

include("spectral_transform.jl")
include("diffusion.jl")
include("time_stepping.jl")


text:
using ChaosTools, DynamicalSystemsBase, Test

println("\nTesting fixed points...")

@testset "Fixed points" begin
    @testset "Henon map" begin
        ds = Systems.henon()
        x = -1.5..1.5
        y = -0.5..0.5
        box = x × y

        fp, eigs, stable = fixedpoints(ds, box)

        # henon fixed points analytically
        hmfp(a, b) = (x = -(1-b)/2a - sqrt((1-b)^2 + 4a)/2a; return SVector(x, b*x))
        henon_fp = hmfp(ds.p[1], ds.p[2])

        @test size(fp) == (2,2)
        @test stable == [false, false]
        @test (henon_fp ≈ fp[1]) || (henon_fp ≈ fp[2])
    end

    @testset "standard map" begin
        ds = Systems.standardmap()
        x = 0.0..(2π - 100eps())
        box = x × x

        fp, eigs, stable = fixedpoints(ds, box)

        for (i, e) in enumerate(fp)
            if isapprox(e, SVector(0,0); atol = 1e-8)
                @test !stable[i]
            elseif e ≈ SVector(π, 0)
                @test stable[i]
            else
                @test false
            end
        end
    end

    @testset "Lorenz system" begin
        x = -20..20
        y = -20..20
        z = 0.0..40
        box = x × y × z
        σ = 10.0
        β = 8/3
        lorenzfp(ρ,β) = [
            SVector(0,0,0.0),
            SVector(sqrt(β*(ρ-1)), sqrt(β*(ρ-1)), ρ-1),
            SVector(-sqrt(β*(ρ-1)), -sqrt(β*(ρ-1)), ρ-1),
        ]

        stabil(σ, β) = σ*(σ+β+3)/(σ-β-1)

        @testset "ρ = $(ρ)" for (i, ρ) in enumerate((22, 28))
            ds = Systems.lorenz(; ρ, β, σ)
            afps = lorenzfp(ρ,β)
            fp, eigs, stable = fixedpoints(ds, box)
            fp = unique(fp.data)
            @test length(fp) == 3
            for p in fp
                @test any(w -> isapprox(w, p; atol = 1e-8), afps)
            end
            @test count(stable) == (i == 1 ? 2 : 0)
        end
    end
end


text:
#Blegh. Despite reasonable prior googling, I somehow missed this:
#https://github.com/hng/BiomolecularStructures.jl/blob/master/src/WebBLAST/ncbi_blast.jl
#Some bits of that are nice, and some are inconvenient.
#Their restrictive assumptions are:
#the PDB is always the target.
#Sequences are always amino acids.
#You only ever search with one query
#Still, it would have been much better to start with that and adapt...
#Also, now the name WebBLAST is taken. Should I still call the package WebBlast.jl? Ja, why not.

module WebBlast
    using HTTP, EzXML, DataFrames
    include("functions.jl")
end


text:
using Dates
using Printf

export pcap_t, bpf_program, pcap_pkthdr,
       pcap_lookupdev, pcap_open_live, pcap_compile, pcap_setfilter, pcap_next_ex, pcap_inject

PCAP_ERRBUF_SIZE = 256
PCAP_NETMASK_UNKNOWN = 0xffffffff

mutable struct pcap_t
end

mutable struct bpf_insn
end

mutable struct bpf_program
    bpf_len::Cuint
    bf_insns::Ptr{bpf_insn}

    function bpf_program()
        new(0, 0)
    end
end

mutable struct pcap_pkthdr
    tv_sec::Clong
    tv_usec::Clong
    caplen::UInt32
    len::UInt32

    function pcap_pkthdr()
        new(0, 0, 0, 0)
    end
end

Base.show(io::IO, hdr::pcap_pkthdr) = print(io, hdr)
Base.print(io::IO, hdr::pcap_pkthdr) = print(io, @sprintf("(timestamp => %s, caplen => %u, len => %u)", Dates.unix2datetime(hdr.tv_sec + hdr.tv_usec / 1000000), hdr.caplen, hdr.len))

#----------
# lookup default device
#----------
function pcap_lookupdev()
    dev = ccall((:pcap_lookupdev, :libpcap),
                Ptr{UInt8},
                ())
    if dev == C_NULL
        throw(ErrorException("pcap_lookupdev: $(pcap_geterr(handle))"))
    else
        unsafe_string(dev)
    end
end # function pcap_lookupdev

#----------
# get libpcap error message text
#----------
function pcap_geterr(handle)
    errptr = ccall((:pcap_geterr, :libpcap),
                   Cstring,
                   (Ptr{pcap_t},),
                   handle)
    unsafe_string(errptr)
end # function pcap_geterr

#----------
# open a device for capturing
#----------
function pcap_open_live(device, snaplen, promisc, to_ms)
    errbuf = Vector{UInt8}(undef, PCAP_ERRBUF_SIZE)
    handle = ccall((:pcap_open_live, :libpcap),
                   Ptr{pcap_t},
                   (Cstring, Cint, Cint, Cint, Ref{UInt8}),
                   device, snaplen, promisc, to_ms, errbuf)
    if handle == C_NULL
        errbuf[end] = 0
        throw(ErrorException("pcap_open_live: $(unsafe_string(pointer(errbuf)))"))
    else
        handle
    end
end # function pcap_open_live

#----------
# compile a filter expression
#----------
function pcap_compile(handle, str; optimize=0, netmask=PCAP_NETMASK_UNKNOWN)
    program = bpf_program()
    result = ccall((:pcap_compile, :libpcap),
                   Cint,
                   (Ptr{pcap_t}, Ref{bpf_program}, Cstring, Cint, UInt32),
                   handle, program, str, optimize, netmask)
    if result == 0
        program
    else
        throw(ErrorException("pcap_compile: $(pcap_geterr(handle))"))
    end
end # function pcap_compile

#----------
# set the filter
#----------
function pcap_setfilter(handle, program)
    result = ccall((:pcap_setfilter, :libpcap),
                   Cint,
                   (Ptr{pcap_t}, Ref{bpf_program}),
                   handle, program)
    if result != 0
        throw(ErrorException("pcap_setfilter: $(pcap_geterr(handle))"))
    end
end # function pcap_setfilter

#----------
# read the next packet from a pcap_t
#----------
function pcap_next_ex(handle)
    pkt_header = Array{Ptr{pcap_pkthdr}}(undef, 1)
    pkt_data = Array{Ptr{UInt8}}(undef, 1)
    result = ccall((:pcap_next_ex, :libpcap),
                   Cint,
                   (Ptr{pcap_t}, Ptr{Ptr{pcap_pkthdr}}, Ptr{Ptr{UInt8}}),
                   handle, pkt_header, pkt_data)
    if result == -1
        throw(ErrorException("pcap_next_ex: $(pcap_geterr(handle))"))
    end

    if result == 1
        header = unsafe_load(pkt_header[1])
        data = unsafe_wrap(Array, pkt_data[1], header.caplen)
        (result, header, data)
    else
        (result, nothing, nothing)
    end
end # function pcap_next_ex

#----------
# transmit a packet
#----------
function pcap_inject(handle, pkt_data)
    result = ccall((:pcap_inject, :libpcap),
                   Cint,
                   (Ptr{pcap_t}, Ptr{UInt8}, Csize_t),
                   handle, pkt_data, length(pkt_data))
    if result == -1
        throw(ErrorException("pcap_inject: $(pcap_geterr(handle))"))
    else
        result
    end
end


text:
function clearance_travel_time(i::Int, j::Int, v::Int, w::Int, bj_dict::Dict{Int, Array{Int,1}}, CTS::Constants)
    delta = (CTS.delta + 1)*abs(v-w)
    li = bj_dict[i][v]
    lj = bj_dict[j][w]
    if (v < w) && (i != j) && (li > lj - delta)
        return((li - lj + delta)*CTS.tt)
    elseif (v > w) && (i != j) && (li < lj + delta)
        return((lj - li + delta)*CTS.tt)
    else
        return(0)
    end
end

function update_math_ls(LS::LoadingSequence, t::NamedTuple{(:start_time, :pos, :next_pos, :qc),Tuple{Int64,Int64,Int64,Int64}}, sol_w::Dict{Int, Int}, CTS::Constants)
    if t.pos != 0
        LS.len += 1
        LS.tasks_left -= 1
        push!(LS.filled_pos, t.pos)
        push!(LS.loaded_cont, sol_w[t.pos])
    end
    push!(LS.order, (task=LTask(t.pos, bj_dict[t.pos][t.qc], sol_w[t.pos], JuMP.value.(t_task)[t.pos]), start_time=t.start_time, qc=t.qc))
end

function get_math_ls(sol_x::Dict{Int, Array}, sol_w::Dict{Int, Int}, CTS::Constants)
    #init Loading Sequence and Quay Cranes
    LS = init_ls(CTS)
    QC = init_qc(CTS)

    #update loading sequence with model solution
    while LS.tasks_left > 0
        task = [(start_time=CTS.H+1,pos=0,next_pos=0,qc=0)]
        for q=1:Q
            if length(sol_x[q])>0 && sol_x[q][1].start_time < task[1].start_time
                task = [sol_x[q][1]]
            elseif length(sol_x[q])>0 && sol_x[q][1].start_time == task[1].start_time
                push!(task, sol_x[q][1])
            end
        end

        for t in task
            update_math_ls(LS, t, sol_w, CTS)
            if sol_x[t.qc][1] == t
                deleteat!(sol_x[t.qc], 1)
            end
        end
    end
    return(LS)
end

max_stars_repo_licenses: Zlib MIT

max_issues_repo_licenses: Zlib MIT

max_forks_repo_licenses: Zlib MIT


text:
# SizedMemory
# ===========

struct SizedMemory
    ptr::Ptr{UInt8}
    len::UInt
end

"""
    SizedMemory(data)

Create a `SizedMemory` object from `data`.

`data` must implement `Automa.pointerstart` and `Automa.pointerend` methods.
These are used to get the range of the contiguous data memory of `data`.  These
have default methods which uses `Base.pointer` and `Base.sizeof` methods.  For
example, `String` and `Vector{UInt8}` support these `Base` methods.

Note that it is user's responsibility to keep the `data` object alive during
`SizedMemory`'s lifetime because it does not have a reference to the object.
"""
function SizedMemory(data, len::Integer=(pointerend(data) + 1) - pointerstart(data))
    return SizedMemory(pointerstart(data), len)
end

"""
    pointerstart(data)::Ptr{UInt8}

Return the start position of `data`.

The default implementation is `convert(Ptr{UInt8}, pointer(data))`.
"""
function pointerstart(data)::Ptr{UInt8}
    return convert(Ptr{UInt8}, pointer(data))
end

"""
    pointerend(data)::Ptr{UInt8}

Return the end position of `data`.

The default implementation is `Automa.pointerstart(data) + sizeof(data) - 1`.
"""
function pointerend(data)::Ptr{UInt8}
    return pointerstart(data) + sizeof(data) - 1
end

function Base.checkbounds(mem::SizedMemory, i::Integer)
    if 1 ≤ i ≤ mem.len
        return
    end
    throw(BoundsError(i))
end

function Base.getindex(mem::SizedMemory, i::Integer)
    @boundscheck checkbounds(mem, i)
    return unsafe_load(mem.ptr, i)
end

function Base.lastindex(mem::SizedMemory)
    return Int(mem.len)
end

function Base.length(mem::SizedMemory)
    return Int(mem.len)
end


text:
# This file is a part of Julia. License is MIT: https://julialang.org/license

import REPL
using REPL.TerminalMenus
using Test

function simulate_input(menu::TerminalMenus.AbstractMenu, keys...; kwargs...)
    keydict =  Dict(:up => "\e[A",
                    :down => "\e[B",
                    :enter => "\r")

    new_stdin = Base.BufferStream()
    for key in keys
        if isa(key, Symbol)
            write(new_stdin, keydict[key])
        else
            write(new_stdin, "$key")
        end
    end
    TerminalMenus.terminal.in_stream = new_stdin

    return request(menu; suppress_output=true, kwargs...)
end

include("radio_menu.jl")
include("multiselect_menu.jl")
include("dynamic_menu.jl")
include("multiselect_with_skip_menu.jl")
include("pager.jl")

# Legacy tests
include("legacytests/old_radio_menu.jl")
include("legacytests/old_multiselect_menu.jl")
include("legacytests/config.jl")

max_stars_repo_name: SmiteWindows/julia

max_issues_repo_name: SmiteWindows/julia

max_forks_repo_name: SmiteWindows/julia


text:
using Shoco
using Base.Test

s = "What's up, doc?"
c = compress(s)
@test 0 < sizeof(c) < sizeof(s)
@test decompress(c) == s

@test compress("") == ""
@test decompress("") == ""

s = "؉'s ⎨<g"
d = decompress(s)
@test sizeof(d) > sizeof(s)


text:
# Test MonteCarlo functions

using TrajOptSOCPs
using Test

@testset "Feasible" begin

    # Define the polyhedron
    A = [4 5; -4 5; 0 -1]
    b = [20; 30; 1]

    # Test a point in the feasible region (true)
    @test TrajOptSOCPs.isFeasiblePolyHedron(A, b, [-1; 0.5])

    # Test three points outside the feasible region (false)
    @test !TrajOptSOCPs.isFeasiblePolyHedron(A, b, [-10; 0.5])
    @test !TrajOptSOCPs.isFeasiblePolyHedron(A, b, [-1; 10])
    @test !TrajOptSOCPs.isFeasiblePolyHedron(A, b, [-1; -10])
end

@testset "MonteCarlo" begin

    # Generating a 3D point
    pt1 = TrajOptSOCPs.getPoint([3; 2; -5], [10; 100; 0.5])

    # Checking that the point is in the bounds
    @test (10 > pt1[1] > 3)
    @test (100 > pt1[2] > 2)
    @test (0.5 > pt1[3] > -5)

    # Generating 3 Random 4D Points
    numpts = 3
    pts = TrajOptSOCPs.montecarlo([3; 2; -5; -0.01],
                                  [10; 100; 0.5; 0.01],
                                  numpts)

    @test size(pts, 1) == numpts

    # Check that the points are indeed 4D
    @test size(pts[1], 1) == 4
    @test size(pts[numpts], 1) == 4

    # Generating 2 Random Points in a smaller [0, 1] box:
    pts2 = TrajOptSOCPs.montecarlo([-20; -20], [20; 20], 2, TrajOptSOCPs.inBox)

    @test size(pts2, 1) == 2

    # Check that the points are indeed 2D
    @test size(pts2[1], 1) == 2
    @test size(pts2[2], 1) == 2

end

max_stars_repo_name: danineamati/TrajOptSOCPs


text:
# -*- coding: utf-8 -*-
# ---
# jupyter:
#   jupytext:
#     formats: ipynb,jl:hydrogen
#     text_representation:
#       extension: .jl
#       format_name: hydrogen
#       format_version: '1.3'
#       jupytext_version: 1.11.2
#   kernelspec:
#     display_name: Julia 1.8.0-DEV
#     language: julia
#     name: julia-1.8
# ---

# %%
using Plots

function randunitdisk()
    y, x = sincospi(2rand())
    r = √rand()
    r*x, r*y
end

randunitdisk(n) = [randunitdisk() for _ in 1:n]

# %%
scatter(randunitdisk(2^12); legend=false, msw=0, ms=3, alpha=0.5, size=(500, 500))

# %%
scatter(randunitdisk(2^14); legend=false, msw=0, ms=1.5, alpha=0.5, size=(500, 500))

# %%

max_stars_repo_path: 0012/uniform distribution on the unit disk.jl

max_stars_repo_name: genkuroki/public

max_issues_repo_name: genkuroki/public

max_forks_repo_name: genkuroki/public


text:
# This file is a part of SimilaritySearch.jl
# License is Apache 2.0: https://www.apache.org/licenses/LICENSE-2.0.txt

using Random
export TIHCSearch

struct TIHCSearch <: LocalSearchAlgorithm
    ssize::Int32 # sample size
    restarts::Int32
    use_local_improvement::Bool
    TIHCSearch() = new(1, 1, false)
    TIHCSearch(ssize, restarts; use_local_improvement=false) = new(Int32(ssize), Int32(restarts), use_local_improvement)
 end

function randomsearch(index::SearchGraph{T}, dist::Function, q::T, res::KnnResult, best::KnnResult, navigation_state, ssize::Integer) where T
    n = length(index.db)
    ssize = min(n, max(maxlength(res), ssize))
    range = 1:n
    @inbounds for i in 1:ssize
        # while abs(prev_dist - last(res).dist) < rs.tol
        objID = rand(range)
        S = get(navigation_state, objID, UNKNOWN)
        if S == UNKNOWN
            navigation_state[objID] = VISITED
            d = convert(Float32, dist(q, index.db[objID]))
            push!(res, objID, d)
            push!(best, objID, d)
        end
    end

    res
end

function search(isearch::TIHCSearch, index::SearchGraph{T}, dist::Function, q::T, res::KnnResult, navigation_state, hints=EMPTY_INT_VECTOR) where T
    n = length(index.db)
    restarts = min(isearch.restarts, n)
    best = KnnResult(1)
    # if length(hints) == 0 hints = rand(1:n, bs.bsize) end

    @inbounds for i in 1:restarts
        empty!(best)
        randomsearch(index, dist, q, res, best, navigation_state, isearch.ssize)
        length(best) == 0 && break  # all items in the neighborhood were visited
        # @show i, restarts, isearch, best, length(best)
        start_point = first(best).objID
        navigation_state[start_point] = EXPLORED
        d = convert(Float32, dist(q, index.db[start_point]))
        push!(res, start_point, d)
        hill_climbing(index, dist, q, res, navigation_state, start_point, isearch.use_local_improvement)
    end

    res
end

function opt_expand_neighborhood(fun, algo::TIHCSearch, n::Integer, iter::Integer, probes::Integer)
    f_(w) = ceil(Int, w * (rand() - 0.5))
    f(x, w) = max(1, x + f_(w))
    logn = ceil(Int, log(2, n+1))
    w = 1
    # probes = probes == 0 ? logn : probes
    while w <= logn  ## log log n
        #TIHCSearch(min(200, n), 1, use_local_improvement=true) |> fun
        TIHCSearch(algo.ssize, f(algo.restarts, w)) |> fun
        TIHCSearch(f(algo.ssize, w), algo.restarts) |> fun
        w += w
    end
end


text:
using Test
using DandelionWebSockets: OPCODE_PONG, masking!, CLOSE_STATUS_PROTOCOL_ERROR, protocolstate

function textframe_from_server(text::String; final_frame=true)
    Frame(final_frame, OPCODE_TEXT, false, length(text), 0, Vector{UInt8}(), unsafe_wrap(Vector{UInt8}, text))
end

function binaryframe_from_server(data::AbstractVector{UInt8}; final_frame=true)
    Frame(final_frame, OPCODE_BINARY, false, length(data), 0, Vector{UInt8}(), data)
end

function continuation_textframe_from_server(text::String; final_frame=true)
    Frame(final_frame, OPCODE_CONTINUATION, false, length(text), 0, Vector{UInt8}(), unsafe_wrap(Vector{UInt8}, text))
end

function continuation_binaryframe_from_server(data::AbstractVector{UInt8}; final_frame=true)
    Frame(final_frame, OPCODE_CONTINUATION, false, length(data), 0, Vector{UInt8}(), data)
end

function pingframe_from_server(; payload=Vector{UInt8}(), final_frame=true)
    Frame(final_frame, OPCODE_PING, false, 0, 0, Vector{UInt8}(), payload)
end

function pongframe_from_server(; payload=Vector{UInt8}(), final_frame=true)
    Frame(final_frame, OPCODE_PONG, false, 0, 0, Vector{UInt8}(), payload)
end

@testset "Server to client       " begin
    @testset "single frame text message; handler receives message" begin
        # Requirement
        # @6_2-4 Message has been received, single frame

        # Arrange
        logic, handler, writer = makeclientlogic()

        frame = textframe_from_server("Hello")

        # Act
        handle(logic, FrameFromServer(frame))

        # Assert
        @test getsingletext(handler) == "Hello"
    end

    @testset "two single frame text messages; handler receives both messages" begin
        # Arrange
        logic, handler, writer = makeclientlogic()

        frame1 = textframe_from_server("Hello")
        frame2 = textframe_from_server("world")

        # Act
        handle(logic, FrameFromServer(frame1))
        handle(logic, FrameFromServer(frame2))

        # Assert
        @test gettextat(handler, 1) == "Hello"
        @test gettextat(handler, 2) == "world"
    end

    @testset "two messages, both in two frames; handler receives both messages" begin
        # Requirement
        # @6_2-5 Message has been received, multi-frame

        logic, handler, writer = makeclientlogic()

        frame1_1 = textframe_from_server("Hel"; final_frame=false)
        frame1_2 = continuation_textframe_from_server("lo";  final_frame=true)
        frame2_1 = textframe_from_server("wo";  final_frame=false)
        frame2_2 = continuation_textframe_from_server("rld"; final_frame=true)

        handle(logic, FrameFromServer(frame1_1))
        handle(logic, FrameFromServer(frame1_2))
        handle(logic, FrameFromServer(frame2_1))
        handle(logic, FrameFromServer(frame2_2))

        @test gettextat(handler, 1) == "Hello"
        @test gettextat(handler, 2) == "world"
    end

    @testset "a ping request is received between two fragments; pong reply is sent" begin
        # Requirement
        # @5_4-3 Control frames in a fragment sequence
        # @5_4-7 Handling control frames in fragment sequences
        # @5_5_2-2 Pong response
        # @5_5_2-3 Pong response time

        logic, handler, writer = makeclientlogic()

        frame1 = textframe_from_server("Hel"; final_frame=false)
        frame2 = continuation_textframe_from_server("lo";  final_frame=true)
        ping_frame = pingframe_from_server()

        handle(logic, FrameFromServer(frame1))
        handle(logic, FrameFromServer(ping_frame))
        handle(logic, FrameFromServer(frame2))

        written_frame = getframe(writer, 1)
        @test written_frame.opcode == OPCODE_PONG
    end

    @testset "a ping request is received between two fragments; message is still delivered" begin
        # Requirement
        # @5_4-3 Control frames in a fragment sequence
        # @5_4-7 Handling control frames in fragment sequences

        logic, handler, writer = makeclientlogic()

        frame1 = textframe_from_server("Hel"; final_frame=false)
        frame2 = continuation_textframe_from_server("lo";  final_frame=true)
        ping_frame = pingframe_from_server()

        handle(logic, FrameFromServer(frame1))
        handle(logic, FrameFromServer(ping_frame))
        handle(logic, FrameFromServer(frame2))

        @test gettextat(handler, 1) == "Hello"
    end

    @testset "a ping with a payload is received; a pong with the same payload is sent" begin
        # Requirement
        # @5_5_3-1 Pong frame Application data

        mask = b"\x01\x02\x03\x04"
        logic, handler, writer = makeclientlogic(mask=mask)

        ping_frame = pingframe_from_server(payload=b"Some payload")

        handle(logic, FrameFromServer(ping_frame))

        written_frame = getframeunmasked(writer, 1, mask)
        @test written_frame.payload == b"Some payload"
    end

    @testset "a binary single-frame message is received; handler receives message" begin
        # Arrange
        logic, handler, writer = makeclientlogic()

        frame = binaryframe_from_server(b"Hello")

        # Act
        handle(logic, FrameFromServer(frame))

        # Assert
        @test getbinaryat(handler, 1) == b"Hello"
    end

    @testset "two binary fragments are received; full message is delivered" begin
        logic, handler, writer = makeclientlogic()

        frame1 = binaryframe_from_server(b"Hel"; final_frame=false)
        frame2 = continuation_binaryframe_from_server(b"lo";  final_frame=true)

        handle(logic, FrameFromServer(frame1))
        handle(logic, FrameFromServer(frame2))

        @test getbinaryat(handler, 1) == b"Hello"
    end

    @testset "a pong is received from the server; ponger is made aware" begin
        logic, handler, writer, ponger = makeclientlogic()

        pong_frame = pongframe_from_server()

        handle(logic, FrameFromServer(pong_frame))

        @test ponger.no_of_pongs == 1
    end

    @testset "Invalid UTF-8" begin
        @testset "A single-frame message with invalid UTF-8 is received; Connection is failed" begin
            # Requirement
            # @8_1

            logic, handler, writer = makeclientlogic()

            invalidutf8 = b"\xe2"
            invalidframe = Frame(true, OPCODE_TEXT, false, length(invalidutf8), 0, Vector{UInt8}(), invalidutf8)

            handle(logic, FrameFromServer(invalidframe))

            frame = getframe(writer, 1)
            @test frame.opcode == OPCODE_CLOSE
            @test writer.isopen == false
        end

        @testset "A single-frame message with invalid UTF-8 is received; Handler does not receive text" begin
            # Requirement
            # @8_1

            logic, handler, writer = makeclientlogic()

            invalidutf8 = b"\xe2"
            invalidframe = Frame(true, OPCODE_TEXT, false, length(invalidutf8), 0, Vector{UInt8}(), invalidutf8)

            handle(logic, FrameFromServer(invalidframe))

            @test length(handler.texts) == 0
        end

        @testset "A multi-frame message with invalid UTF-8 is received; Connection is failed" begin
            # Requirement
            # @5_6-2 Message has a complete UTF-8 sequence

            logic, handler, writer = makeclientlogic()

            invalidutf8 = b"\xe2"
            frame1 = Frame(false, OPCODE_TEXT, false, length(invalidutf8), 0, Vector{UInt8}(), invalidutf8)
            frame2 = Frame(true, OPCODE_CONTINUATION, false, length(invalidutf8), 0, Vector{UInt8}(), invalidutf8)

            handle(logic, FrameFromServer(frame1))
            handle(logic, FrameFromServer(frame2))

            frame = getframe(writer, 1)
            @test frame.opcode == OPCODE_CLOSE
            @test writer.isopen == false
        end

        @testset "A single-frame message with invalid UTF-8 is received; Handler does not receive text" begin
            logic, handler, writer = makeclientlogic()

            invalidutf8 = b"\xe2"
            frame1 = Frame(false, OPCODE_TEXT, false, length(invalidutf8), 0, Vector{UInt8}(), invalidutf8)
            frame2 = Frame(true, OPCODE_CONTINUATION, false, length(invalidutf8), 0, Vector{UInt8}(), invalidutf8)

            handle(logic, FrameFromServer(frame1))
            handle(logic, FrameFromServer(frame2))

            @test length(handler.texts) == 0
        end
    end

    @testset "Client receives a masked frame from the server" begin
        # Requirement
        # @5_1-5 Client closes connection on masked frame
        # @5_1-6 Client closes connection on masked frame, status code

        @testset "Client receives a masked frame from the server; Client fails the connection" begin
            # Arrange
            logic, handler, writer = makeclientlogic()

            payload = b"Hello"
            frame = Frame(true, OPCODE_TEXT, true, length(payload), 0, b"\x01\x02\x03\x04", payload)

            # Act
            handle(logic, FrameFromServer(frame))

            # Assert
            sentframe = getframe(writer, 1)
            @test sentframe.opcode == OPCODE_CLOSE
            @test writer.isopen == false
        end

        @testset "Client receives a masked frame from the server; Close status is PROTOCOL ERROR" begin
            # Arrange
            mask = b"\x01\x02\x03\x04"
            logic, handler, writer = makeclientlogic(mask=mask)

            payload = b"Hello"
            frame = Frame(true, OPCODE_TEXT, true, length(payload), 0, b"\x01\x02\x03\x04", payload)

            # Act
            handle(logic, FrameFromServer(frame))

            # Assert
            sentframe = getframeunmasked(writer, 1, mask)
            payload = IOBuffer(sentframe.payload)
            @test read(payload, UInt16) == hton(CLOSE_STATUS_PROTOCOL_ERROR.code)
        end

        @testset "Client receives a masked frame from the server; Message is not sent to the handler" begin
            # Arrange
            logic, handler, writer = makeclientlogic()

            payload = b"Hello"
            frame = Frame(true, OPCODE_TEXT, true, length(payload), 0, b"\x01\x02\x03\x04", payload)

            # Act
            handle(logic, FrameFromServer(frame))

            # Assert
            @test length(handler.texts) == 0
        end
    end

    @testset "Client receives a frame with a reserved bit set" begin
        # Requirement
        # @5_2-2 Reserved bits RSV1, RSV2, RSV3, no extension
        @testset "RSV1 bit is set in a frame; Client fails the connection" begin
            # Arrange
            logic, handler, writer = makeclientlogic()

            payload = b"Hello"
            rsv1 = true
            rsv2 = false
            rsv3 = false
            frame = Frame(true, rsv1, rsv2, rsv3, OPCODE_TEXT, false, length(payload), 0, b"", payload)

            # Act
            handle(logic, FrameFromServer(frame))

            # Assert
            sentframe = getframe(writer, 1)
            @test sentframe.opcode == OPCODE_CLOSE
            @test writer.isopen == false
        end

        @testset "RSV1 bit is set in a frame; Message is not sent to handler" begin
            # Arrange
            logic, handler, writer = makeclientlogic()

            payload = b"Hello"
            rsv1 = true
            rsv2 = false
            rsv3 = false
            frame = Frame(true, rsv1, rsv2, rsv3, OPCODE_TEXT, false, length(payload), 0, b"", payload)

            # Act
            handle(logic, FrameFromServer(frame))

            # Assert
            @test length(handler.texts) == 0
        end

        @testset "RSV2 bit is set in a frame; Client fails the connection" begin
            # Arrange
            logic, handler, writer = makeclientlogic()

            payload = b"Hello"
            rsv1 = false
            rsv2 = true
            rsv3 = false
            frame = Frame(true, rsv1, rsv2, rsv3, OPCODE_TEXT, false, length(payload), 0, b"", payload)

            # Act
            handle(logic, FrameFromServer(frame))

            # Assert
            sentframe = getframe(writer, 1)
            @test sentframe.opcode == OPCODE_CLOSE
            @test writer.isopen == false
        end

        @testset "RSV3 bit is set in a frame; Client fails the connection" begin
            # Arrange
            logic, handler, writer = makeclientlogic()

            payload = b"Hello"
            rsv1 = false
            rsv2 = false
            rsv3 = true
            frame = Frame(true, rsv1, rsv2, rsv3, OPCODE_TEXT, false, length(payload), 0, b"", payload)

            # Act
            handle(logic, FrameFromServer(frame))

            # Assert
            sentframe = getframe(writer, 1)
            @test sentframe.opcode == OPCODE_CLOSE
            @test writer.isopen == false
        end
    end

    @testset "Client receives a fragmented control frame" begin
        # Requirement
        # @5_4-4 Control frames are not fragmented

        @testset "Client receives a fragmented CLOSE frame; Client fails the connection" begin
            logic, handler, writer = makeclientlogic()

            # Create a fragmented close frame
            frame = closeframe_from_server(; final_frame=false)
            handle(logic, FrameFromServer(frame))

            @test protocolstate(logic) == STATE_CLOSED
            @test writer.isopen == false
        end

        @testset "Client receives a fragmented PING frame; Client fails the connection" begin
            logic, handler, writer = makeclientlogic()

            # Create a fragmented ping frame
            frame = pingframe_from_server(; final_frame=false)
            handle(logic, FrameFromServer(frame))

            @test protocolstate(logic) == STATE_CLOSED
            @test writer.isopen == false
        end

        @testset "Client receives a fragmented PONG frame; Client fails the connection" begin
            logic, handler, writer = makeclientlogic()

            # Create a fragmented pong frame
            frame = pongframe_from_server(; final_frame=false)
            handle(logic, FrameFromServer(frame))

            @test protocolstate(logic) == STATE_CLOSED
            @test writer.isopen == false
        end
    end

    @testset "Client receives a control frame with too large payload" begin
        # Requirement
        # @5_5-1 Control frame length

        @testset "Client receives a CLOSE frame with payload 126 bytes; Client fails the connection" begin
            logic, handler, writer = makeclientlogic()

            payload = zeros(UInt8, 126)
            frame = closeframe_from_server(; payload=payload)
            handle(logic, FrameFromServer(frame))

            @test protocolstate(logic) == STATE_CLOSED
            @test writer.isopen == false
        end

        @testset "Client receives a CLOSE frame with payload 127 bytes; Client fails the connection" begin
            logic, handler, writer = makeclientlogic()

            payload = zeros(UInt8, 127)
            frame = closeframe_from_server(; payload=payload)
            handle(logic, FrameFromServer(frame))

            @test protocolstate(logic) == STATE_CLOSED
            @test writer.isopen == false
        end

        @testset "Client receives a PING frame with too large payload; Client fails the connection" begin
            logic, handler, writer = makeclientlogic()

            payload = zeros(UInt8, 127)
            frame = pingframe_from_server(; payload=payload)
            handle(logic, FrameFromServer(frame))

            @test protocolstate(logic) == STATE_CLOSED
            @test writer.isopen == false
        end

        @testset "Client receives a PONG frame with too large payload; Client fails the connection" begin
            logic, handler, writer = makeclientlogic()

            payload = zeros(UInt8, 127)
            frame = pongframe_from_server(; payload=payload)
            handle(logic, FrameFromServer(frame))

            @test protocolstate(logic) == STATE_CLOSED
            @test writer.isopen == false
        end
    end
end


text:
function generate_inputdata2d(u, data, polydeg, datatyp::String)
    f(x, y) = u(x, y)
    h = polydeg +1
    a = data[:, 1, 1]
    b = data[:, end, end]
    modal = zeros(1, h, h)
    modal_tmp1 = zeros(1, h, h)
    indicator = zeros(1, h, h)
    a1 = a[1]
    b1 = b[1]
    a2 = a[2]
    b2 = b[2]

    n,_ = gauss_lobatto_nodes_weights(h)
    _, inverse_vandermonde_legendre = vandermonde_legendre(n)

    #Transformation: [-1,1] to [a,b]
    nab=zeros(h)
    nab2=zeros(h)

    for j = 1:h
        #x
        nab[j]=(b1-a1)/2*n[j]+(a1+b1)/2
        #y
        nab2[j]=(b2-a2)/2*n[j]+(a2+b2)/2
    end

    for i in 1:h
        for j in 1:h
            indicator[1,i,j] = u(nab[i],nab2[j])
        end
    end

    if datatyp == "NNPP"
        multiply_dimensionwise!(modal, inverse_vandermonde_legendre, indicator,modal_tmp1)

        total_energy  = 0.0
        for j in 1:h, i in 1:h
            total_energy  += modal[1, i, j]^2
        end
        total_energy_clip1 = 0.0
        for j in 1:(h-1), i in 1:(h-1)
            total_energy_clip1 += modal[1, i, j]^2
        end
        total_energy_clip2 = 0.0
        for j in 1:(h-2), i in 1:(h-2)
            total_energy_clip2 += modal[1, i, j]^2
        end
        total_energy_clip3 = 0.0
        for j in 1:(h-3), i in 1:(h-3)
            total_energy_clip3 += modal[1, i, j]^2
        end

        x1 = (total_energy - total_energy_clip1)/total_energy
        x2 = (total_energy_clip1 - total_energy_clip2)/total_energy_clip1
        x3 = (total_energy_clip2 - total_energy_clip3)/total_energy_clip2

        return x1, x2, x3, h

    elseif datatyp == "NNRH"

        multiply_dimensionwise!(modal, inverse_vandermonde_legendre, indicator,modal_tmp1)

        return modal[1,1,1], modal[1,1,2], modal[1,2,1]

    elseif datatyp == "CNN"
        n_out = 4
        cnnnodes,_ = gauss_lobatto_nodes_weights(n_out)
        vandermonde = polynomial_interpolation_matrix(n, cnnnodes)
        data_out = zeros(n_out,n_out)
        for j in 1:n_out, i in 1:n_out
            acc = 0
            for jj in 1:h, ii in 1:h
                acc += vandermonde[i,ii] * indicator[1,ii,jj] * vandermonde[j,jj]
            end
            data_out[i,j] = acc
        end

        return data_out
    end

end

function generate_inputXi2d(element_id, input_data, c2e, mesh, datatyp)
    if datatyp == "NNPP"

        return input_data[:, element_id]

    elseif datatyp == "NNRH"
        leaf_cell_ids = leaf_cells(mesh.tree)
        dirshuffle = collect(1:4)
        dirshuffle = shuffle!(dirshuffle)
        cell_id = leaf_cell_ids[element_id]
        neighbor_ids = 0
        neighbor_ids2 = 0
        neighbor_ids3 = 0
        neighbor_ids4 = 0
        Xi = zeros(15,1)

        for direction in 1:4
            # if no neighbor exists and current cell is not small
            if !has_any_neighbor(mesh.tree, cell_id, direction)
                continue
            end
            if direction == 1 # -x direction 4
                dir = dirshuffle[1]
            elseif direction == 2 # +x direction 1
                dir = dirshuffle[2]
            elseif direction == 3 # -y direction 3
                dir = dirshuffle[3]
            elseif direction == 4 # +y direction 2
                dir = dirshuffle[4]#2
            end
            #Get Input data from neighbors
            if has_neighbor(mesh.tree, cell_id, direction)
                neighbor_cell_id = mesh.tree.neighbor_ids[direction, cell_id]
                if has_children(mesh.tree, neighbor_cell_id) # Cell has small neighbor_cell_id
                    neighbor_ids  = c2e[mesh.tree.child_ids[1, neighbor_cell_id]]
                    neighbor_ids2 = c2e[mesh.tree.child_ids[2, neighbor_cell_id]]
                    neighbor_ids3 = c2e[mesh.tree.child_ids[3, neighbor_cell_id]]
                    neighbor_ids4 = c2e[mesh.tree.child_ids[4, neighbor_cell_id]]

                    Xi[3*dir+1] = (input_data[1,neighbor_ids] + input_data[1,neighbor_ids2]+input_data[1,neighbor_ids3]+input_data[1,neighbor_ids4])/4
                    Xi[3*dir+2] = (input_data[2,neighbor_ids] + input_data[2,neighbor_ids2]+input_data[2,neighbor_ids3]+input_data[2,neighbor_ids4])/4
                    Xi[3*dir+3] = (input_data[3,neighbor_ids] + input_data[3,neighbor_ids2]+input_data[3,neighbor_ids3]+input_data[3,neighbor_ids4])/4

                else # Cell has same refinement level neighbor
                    neighbor_ids = c2e[neighbor_cell_id]

                    Xi[3*dir+1]=input_data[1,neighbor_ids]
                    Xi[3*dir+2]=input_data[2,neighbor_ids]
                    Xi[3*dir+3]=input_data[3,neighbor_ids]
                end
            else # Cell is small and has large neighbor
                parent_id = mesh.tree.parent_ids[cell_id]
                neighbor_ids = c2e[mesh.tree.neighbor_ids[direction, parent_id]]

                Xi[3*dir+1]=input_data[1,neighbor_ids]
                Xi[3*dir+2]=input_data[2,neighbor_ids]
                Xi[3*dir+3]=input_data[3,neighbor_ids]

            end
        end
        Xi[1]=input_data[1,element_id]
        Xi[2]=input_data[2,element_id]
        Xi[3]=input_data[3,element_id]

        return Xi
    elseif datatyp == "CNN"
        return input_data[:, :, element_id]
    end
end


text:
### A Pluto.jl notebook ###
# v0.16.1

using Markdown
using InteractiveUtils

# ╔═╡ 82b07d30-0faf-11eb-3b48-2dccf08d0545
using ResumableFunctions

# ╔═╡ 0ba3d880-0fb0-11eb-3508-d55bfc20056c
using SimJulia

# ╔═╡ 3ca57832-0fb0-11eb-1853-a947bdd4ebc1
using Logging

# ╔═╡ 1546ff80-0faf-11eb-2e03-a3ed4337a0df
md"""# SimJulia
## Basic Concepts

Simjulia is a discrete-event simulation library. The behavior of active components (like vehicles, customers or messages) is modeled with processes. All processes live in an environment. They interact with the environment and with each other via events.

Processes are described by `@resumable` functions. You can call them process function. During their lifetime, they create events and `@yield` them in order to wait for them to be triggered."""

# ╔═╡ 3689b520-0faf-11eb-3743-95fd62f74574
#using Pkg

# ╔═╡ 7926ee20-0faf-11eb-0b72-990ad61c08ea
#pkg"add ResumableFunctions"

# ╔═╡ 57765b80-0faf-11eb-2e25-f9d8a95128be
@resumable function fibonacci(n::Int) :: Int
    a = 0
    b = 1
    for i in 1:n
        @yield a
        a, b = b, a+b
    end
end

# ╔═╡ 996923b0-0faf-11eb-0b98-b9c64f28e5c0
fib = fibonacci(5);

# ╔═╡ a83919e2-0faf-11eb-17ef-a3eac492c533
fib()

# ╔═╡ a3a70ea2-0faf-11eb-33c8-dd40db996416
fib()

# ╔═╡ abd7c470-0faf-11eb-071e-4535258ede59
fib()

# ╔═╡ ad4f4940-0faf-11eb-22b9-0b324557463d
fib()

# ╔═╡ aebda650-0faf-11eb-0ee5-074a408638d7
let
	io = IOBuffer()
	for fib in fibonacci(10)
		print(io, fib, " ")
	end
	String(take!(io))
end

# ╔═╡ e85462f0-0faf-11eb-0d54-e52e8c1e9b26
md"""When a process yields an event, the process gets suspended. SimJulia resumes the process, when the event occurs (we say that the event is triggered). Multiple processes can wait for the same event. SimJulia resumes them in the same order in which they yielded that event.

An important event type is the `timeout`. Events of this type are scheduled after a certain amount of (simulated) time has passed. They allow a process to sleep (or hold its state) for the given time. A `timeout` and all other events can be created by calling a constructor having the environment as first argument."""

# ╔═╡ 0153c520-0fb0-11eb-1253-0bd7e9dd04ee
md"""## Our First Process

Our first example will be a car process. The car will alternately drive and park for a while. When it starts driving (or parking), it will print the current simulation time.

So let’s start:"""

# ╔═╡ 105133ee-0fb0-11eb-1eba-238a216c5182
@resumable function car(env::Environment)
    while true
        @info("Start parking at $(now(env))")
        parking_duration = 5
        @yield timeout(env, parking_duration)
        @info("Start driving at $(now(env))")
        trip_duration = 2
        @yield timeout(env, trip_duration)
    end
end

# ╔═╡ 18ba5ee0-0fb0-11eb-1c6d-e1ced026d640
md"""Our car process requires a reference to an `Environment` in order to create new events. The car‘s behavior is described in an infinite loop. Remember, the car function is a `@resumable function`. Though it will never terminate, it will pass the control flow back to the simulation once a `@yield` statement is reached. Once the yielded event is triggered (“it occurs”), the simulation will resume the function at this statement.

As said before, our car switches between the states parking and driving. It announces its new state by printing a message and the current simulation time (as returned by the function call `now`). It then calls the constructor `timeout` to create a timeout event. This event describes the point in time the car is done parking (or driving, respectively). By yielding the event, it signals the simulation that it wants to wait for the event to occur.

Now that the behavior of our car has been modeled, lets create an instance of it and see how it behaves:"""

# ╔═╡ 2326d3e2-0fb0-11eb-1827-6d08b4032c34
let sim = Simulation()
	@process car(sim)
	run(sim, 15)
end

# ╔═╡ 31d8458e-0fb0-11eb-0fe5-0b2a1a5d56c3
md"""The first thing we need to do is to create an environment, e.g. an instance of `Simulation`. The macro `@process` having as argument a car process function call creates a process that is initialised and added to the environment automatically.

Note, that at this time, none of the code of our process function is being executed. Its execution is merely scheduled at the current simulation time.

The `Process` returned by the `@process` macro can be used for process interactions.

Finally, we start the simulation by calling run and passing an end time to it."""

# ╔═╡ b106b67e-0fb0-11eb-04f2-a734c4fa2e3b
md"""## Process Interaction

The `Process` instance that is returned by `@process` macro can be utilized for process interactions. The two most common examples for this are to wait for another process to finish and to interrupt another process while it is waiting for an event.

### Waiting for a Process

As it happens, a SimJulia `Process` can be used like an event. If you yield it, you are resumed once the process has finished. Imagine a car-wash simulation where cars enter the car-wash and wait for the washing process to finish, or an airport simulation where passengers have to wait until a security check finishes.

Lets assume that the car from our last example is an electric vehicle. Electric vehicles usually take a lot of time charging their batteries after a trip. They have to wait until their battery is charged before they can start driving again.

We can model this with an additional charge process for our car. Therefore, we redefine our car process function and add a charge process function.

A new charge process is started every time the vehicle starts parking. By yielding the `Process` instance that the `@process` macro returns, the run process starts waiting for it to finish:"""

# ╔═╡ c5df5262-0fb0-11eb-2125-755ecf44ff81
@resumable function charge(env::Environment, duration::Number)
    @yield timeout(env, duration)
end

# ╔═╡ d80b92f0-0fb0-11eb-04f5-1d40f00d07b8
@resumable function car2(env::Environment)
    while true
        @info("Start parking and charging at $(now(env))")
        charge_duration = 5
        charge_process = @process charge(env, charge_duration)
        @yield charge_process
        println("Start driving at $(now(env))")
        trip_duration = 2
        @yield timeout(env, trip_duration)
    end
end

# ╔═╡ bc5dbd20-0fb1-11eb-0bda-c3e4c7877daa

# ╔═╡ eda6bb80-0fb0-11eb-2f87-d586f0b69f26
md"""Starting the simulation is straightforward again: We create a `Simulation`, one (or more) cars and finally call `run`."""

# ╔═╡ f67c3cce-0fb0-11eb-3349-4181800dde90
let sim = Simulation()
	@process car2(sim)
	run(sim, 15)
end;

# ╔═╡ 061cc970-0fb1-11eb-0210-d7d0f215be77
md"""### Interrupting Another Process

Imagine, you don’t want to wait until your electric vehicle is fully charged but want to interrupt the charging process and just start driving instead.

SimJulia allows you to interrupt a running process by calling the `interrupt` function:"""

# ╔═╡ 16770920-0fb1-11eb-1551-67668809b19a
@resumable function driver(env::Environment, car_process::Process)
    @yield timeout(env, 3)
    @yield interrupt(car_process)
end

# ╔═╡ 32c0db60-0fb1-11eb-3d75-f1a189baf482
md"""The driver process has a reference to the car process. After waiting for 3 time steps, it interrupts that process.

Interrupts are thrown into process functions as `Interrupt` exceptions that can (should) be handled by the interrupted process. The process can then decide what to do next (e.g., continuing to wait for the original event or yielding a new event):"""

# ╔═╡ ce847f70-0fb1-11eb-144b-6b9542b72e9b
@resumable function car3(env::Environment)
    while true
        @info("Start parking and charging at $(now(env))")
        charge_duration = 5
        charge_process = @process charge(env, charge_duration)
        try
            @yield charge_process
        catch
            @info("Was interrupted. Hopefully, the battery is full enough ...")
        end
        @info("Start driving at $(now(env))")
        trip_duration = 2
        @yield timeout(env, trip_duration)
    end
end

# ╔═╡ f8b8f0ee-0fb1-11eb-13d6-571cad22a19a
md"""When you compare the output of this simulation with the previous example, you’ll notice that the car now starts driving at time 3 instead of 5:"""

# ╔═╡ 05760cb2-0fb2-11eb-2bc4-dd2a2bfde126
let sim = Simulation(), car_process = @process car3(sim)
	@process driver(sim, car_process)
	run(sim, 15)
end;

# ╔═╡ 1d92d712-0fb2-11eb-23fd-4554371e8a3b
md"""## Shared Resources

SimJulia offers three types of resources that help you modeling problems, where multiple processes want to use a resource of limited capacity (e.g., cars at a fuel station with a limited number of fuel pumps) or classical producer-consumer problems.

In this section, we’ll briefly introduce SimJulia’s Resource class.

### Basic Resource Usage

We’ll slightly modify our electric vehicle process car that we introduced in the last sections.

The car will now drive to a battery charging station (BCS) and request one of its two charging spots. If both of these spots are currently in use, it waits until one of them becomes available again. It then starts charging its battery and leaves the station afterwards:"""

# ╔═╡ 3778c8b0-0fb2-11eb-2c8f-379bf1d61719
@resumable function car4(env::Environment, name::Int, bcs::Resource, driving_time::Number, charge_duration::Number)
    @yield timeout(env, driving_time)
    @info("$name arriving at $(now(env))")
    @yield request(bcs)
    @info("$name starting to charge at $(now(env))")
    @yield timeout(env, charge_duration)
    @info("$name leaving the bcs at $(now(env))")
    @yield release(bcs)
end

# ╔═╡ 6e3a9360-0fb2-11eb-11dc-af7b71bd4184
md"""The resource’s `request` function generates an event that lets you wait until the resource becomes available again. If you are resumed, you “own” the resource until you release it.

You are responsible to call release once you are done using the resource. When you `release` a resource, the next waiting process is resumed and now “owns” one of the resource’s slots. The basic Resource sorts waiting processes in a FIFO (first in—first out) way.

A resource needs a reference to an `Environment` and a capacity when it is created.

We can now create the car processes and pass a reference to our resource as well as some additional parameters to them.

Finally, we can start the simulation. Since the car processes all terminate on their own in this simulation, we don’t need to specify an until time — the simulation will automatically stop when there are no more events left:"""

# ╔═╡ 7845ae80-0fb2-11eb-195b-4d0d4ffca60b
let sim = Simulation(), bcs = Resource(sim, 2)
	for i in 1:4
		@process car4(sim, i, bcs, 2i, 5)
	end
	run(sim)
end

# ╔═╡ 9a77cd30-0fb2-11eb-1196-df634baf199d
md"""### Priority resource

As you may know from the real world, not every one is equally important. To map that to SimJulia, the methods `request(res, priority=priority)` and `release(res, priority=priority)` lets requesting and releasing processes provide a priority for each request/release. More important requests/releases will gain access to the resource earlier than less important ones. Priority is expressed by integer numbers; smaller numbers mean a higher priority:"""

# ╔═╡ c8dbb78e-0fb2-11eb-1ed5-554d10df71a8
@resumable function resource_user(sim::Simulation, name::Int, res::Resource, wait::Float64, prio::Int)
  @yield timeout(sim, wait)
  @info("$name Requesting at $(now(sim)) with priority=$prio")
  @yield request(res, priority=prio)
  @info("$name got resource at $(now(sim))")
  @yield timeout(sim, 3.0)
  @yield release(res)
end

# ╔═╡ d683334e-0fb2-11eb-3dc4-4be3043674a7
let sim = Simulation(), res = Resource(sim, 1)
	@process resource_user(sim, 1, res, 0.0, 0)
	@process resource_user(sim, 2, res, 1.0, 0)
	@process resource_user(sim, 3, res, 2.0, -1)
	run(sim)
end

# ╔═╡ eff30a90-0fb2-11eb-01c6-c3a35033923d
md"""Although the third process requested the resource later than the second, it could use it earlier because its priority was higher."""

# ╔═╡ 066d6f8e-0fb3-11eb-0979-ab193faf5653
md"""### Containers

Containers help you modelling the production and consumption of a homogeneous, undifferentiated bulk. It may either be continuous (like water) or discrete (like apples).

You can use this, for example, to model the gas / petrol tank of a gas station. Tankers increase the amount of gasoline in the tank while cars decrease it.

The following example is a very simple model of a gas station with a limited number of fuel dispensers (modeled as `Resource`) and a tank modeled as `Container`:"""

# ╔═╡ 0a431330-0fb4-11eb-2795-2194b90087ee
struct GasStation
  fuel_dispensers :: Resource
  gas_tank :: Container{Float64}
  function GasStation(env::Environment)
    gs = new(Resource(env, 2), Container(env, 1000.0, level=100.0))
    return gs
  end
end

# ╔═╡ c3526920-0fb4-11eb-09cb-c320ebe70780
@resumable function monitor_tank(env::Environment, gs::GasStation)
  while true
    if gs.gas_tank.level < 100.0
      @info("Calling tanker at $(now(env))")
      @process tanker(env, gs)
    end
    @yield timeout(env, 15.0)
  end
end

# ╔═╡ fa9830e0-0fb4-11eb-0098-5d09cf3ae3e2
@resumable function tanker(env::Environment, gs::GasStation)
  @yield timeout(env, 10.0)
  @info("Tanker arriving at $(now(env))")
  amount = gs.gas_tank.capacity - gs.gas_tank.level
  @yield put(gs.gas_tank, amount)
end

# ╔═╡ 8c905050-0fb4-11eb-3218-ad71581a62e9
@resumable function car5(env::Environment, name::Int, gs::GasStation)
  @info("Car $name arriving at $(now(env))")
  @yield request(gs.fuel_dispensers)
  @info("Car $name starts refueling at $(now(env))")
  @yield get(gs.gas_tank, 40.0)
  @yield timeout(env, 15.0)
  @yield release(gs.fuel_dispensers)
  @info("Car $name done refueling at $(now(env))")
end

# ╔═╡ 214e781e-0fb5-11eb-10fe-2d8c3f9ce347
@resumable function car_generator(env::Environment, gs::GasStation)
  for i = 0:3
    @process car5(env, i, gs)
    @yield timeout(env, 5.0)
  end
end

# ╔═╡ 13ba2120-0fb3-11eb-0599-831b085542c8
let sim = Simulation()
	gs = GasStation(sim)
	@process car_generator(sim, gs)
	@process monitor_tank(sim, gs)
	run(sim, 55.0)
end

# ╔═╡ 461ec14e-0fb5-11eb-38f0-61ad30ab4e1e
md"""Priorities can be given to a `put` or a `get` event by setting the named argument priority."""

# ╔═╡ 5d04b960-0fb5-11eb-01fe-fd0ff58627f6
md"""### Stores

Using a `Store` you can model the production and consumption of concrete objects (in contrast to the rather abstract “amount” stored in a Container). A single `Store` can even contain multiple types of objects.

A custom function can also be used to filter the objects you get out of the `store`.

Here is a simple example modelling a generic producer/consumer scenario:"""

# ╔═╡ 4047da00-0fb5-11eb-23a2-19f13af4fac6
@resumable function producer(env::Environment, sto::Store)
  for i = 1:100
    @yield timeout(env, 2.0)
    @yield put(sto, "spam $i")
    @info("Produced spam at $(now(env))")
  end
end

# ╔═╡ 5824f8c0-0fb4-11eb-0073-15bcb8f48aec
@resumable function consumer(env::Environment, name::Int, sto::Store)
  while true
    @yield timeout(env, 1.0)
    @info("$name requesting spam at $(now(env))")
    item = @yield get(sto)
    @info("$name got $item at $(now(env))")
  end
end

# ╔═╡ 23885800-0fb4-11eb-0378-1191e7ec5ca8
let sim = Simulation()
	sto = Store{String}(sim, capacity=UInt(2))
	@process producer(sim, sto)
	consumers = [@process consumer(sim, i, sto) for i=1:2]
	run(sim, 5.0)
end

# ╔═╡ 835bf0b0-0fb5-11eb-2a68-275326c4e73c
md"""A `Store` with a filter on the `get` event can, for example, be used to model machine shops where machines have varying attributes. This can be useful if the homogeneous slots of a` Resource` are not what you need:"""

# ╔═╡ a2c77550-0fb5-11eb-10b3-151670af6203
struct Machine
  size :: Int
  duration :: Float64
end

# ╔═╡ ab861340-0fb5-11eb-29ff-45bc893e6e6f
@resumable function user(env::Environment, name::Int, sto::Store, size::Int)
  machine = @yield get(sto, (mach::Machine)->mach.size == size)
  @info("$name got $machine at $(now(env))")
  @yield timeout(env, machine.duration)
  @yield put(sto, machine)
  @info("$name released $machine at $(now(env))")
end

# ╔═╡ aff2bc30-0fb5-11eb-365f-7b96cdbce30e
@resumable function machineshop(env::Environment, sto::Store)
  m1 = Machine(1, 2.0)
  m2 = Machine(2, 1.0)
  @yield put(sto, m1)
  @yield put(sto, m2)
end

# ╔═╡ b54c3620-0fb5-11eb-2348-b9f57946f679
let sim = Simulation()
	sto = Store{Machine}(sim, capacity=UInt(2))
	ms = @process machineshop(sim, sto)
	users = [@process user(sim, i, sto, (i % 2) + 1) for i=0:2]
	run(sim)
end

# ╔═╡ 00000000-0000-0000-0000-000000000001
PLUTO_PROJECT_TOML_CONTENTS = """
[deps]
Logging = "56ddb016-857b-54e1-b83d-db4d58db5568"
ResumableFunctions = "c5292f4c-5179-55e1-98c5-05642aab7184"
SimJulia = "428bdadb-6287-5aa5-874b-9969638295fd"

[compat]
ResumableFunctions = "~0.6.1"
SimJulia = "~0.8.2"
"""

# ╔═╡ 00000000-0000-0000-0000-000000000002
PLUTO_MANIFEST_TOML_CONTENTS = """
# This file is machine-generated - editing it directly is not advised

[[ArgTools]]
uuid = "0dad84c5-d112-42e6-8d28-ef12dabb789f"

[[Artifacts]]
uuid = "56f22d72-fd6d-98f1-02f0-08ddc0907c33"

[[Base64]]
uuid = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f"

[[Compat]]
deps = ["Base64", "Dates", "DelimitedFiles", "Distributed", "InteractiveUtils", "LibGit2", "Libdl", "LinearAlgebra", "Markdown", "Mmap", "Pkg", "Printf", "REPL", "Random", "SHA", "Serialization", "SharedArrays", "Sockets", "SparseArrays", "Statistics", "Test", "UUIDs", "Unicode"]
git-tree-sha1 = "31d0151f5716b655421d9d75b7fa74cc4e744df2"
uuid = "34da2185-b29b-5c13-b0c7-acf172513d20"
version = "3.39.0"

[[DataStructures]]
deps = ["Compat", "InteractiveUtils", "OrderedCollections"]
git-tree-sha1 = "7d9d316f04214f7efdbb6398d545446e246eff02"
uuid = "864edb3b-99cc-5e75-8d2d-829cb0a9cfe8"
version = "0.18.10"

[[Dates]]
deps = ["Printf"]
uuid = "ade2ca70-3891-5945-98fb-dc099432e06a"

[[DelimitedFiles]]
deps = ["Mmap"]
uuid = "8bb1440f-4735-579b-a4ab-409b98df4dab"

[[Distributed]]
deps = ["Random", "Serialization", "Sockets"]
uuid = "8ba89e20-285c-5b6f-9357-94700520ee1b"

[[Downloads]]
deps = ["ArgTools", "LibCURL", "NetworkOptions"]
uuid = "f43a241f-c20a-4ad4-852c-f6b1247861c6"

[[InteractiveUtils]]
deps = ["Markdown"]
uuid = "b77e0a4c-d291-57a0-90e8-8db25a27a240"

[[LibCURL]]
deps = ["LibCURL_jll", "MozillaCACerts_jll"]
uuid = "b27032c2-a3e7-50c8-80cd-2d36dbcbfd21"

[[LibCURL_jll]]
deps = ["Artifacts", "LibSSH2_jll", "Libdl", "MbedTLS_jll", "Zlib_jll", "nghttp2_jll"]
uuid = "deac9b47-8bc7-5906-a0fe-35ac56dc84c0"

[[LibGit2]]
deps = ["Base64", "NetworkOptions", "Printf", "SHA"]
uuid = "76f85450-5226-5b5a-8eaa-529ad045b433"

[[LibSSH2_jll]]
deps = ["Artifacts", "Libdl", "MbedTLS_jll"]
uuid = "29816b5a-b9ab-546f-933c-edad1886dfa8"

[[Libdl]]
uuid = "8f399da3-3557-5675-b5ff-fb832c97cbdb"

[[LinearAlgebra]]
deps = ["Libdl"]
uuid = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e"

[[Logging]]
uuid = "56ddb016-857b-54e1-b83d-db4d58db5568"

[[MacroTools]]
deps = ["Markdown", "Random"]
git-tree-sha1 = "5a5bc6bf062f0f95e62d0fe0a2d99699fed82dd9"
uuid = "1914dd2f-81c6-5fcd-8719-6d5c9610ff09"
version = "0.5.8"

[[Markdown]]
deps = ["Base64"]
uuid = "d6f4376e-aef5-505a-96c1-9c027394607a"

[[MbedTLS_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "c8ffd9c3-330d-5841-b78e-0817d7145fa1"

[[Mmap]]
uuid = "a63ad114-7e13-5084-954f-fe012c677804"

[[MozillaCACerts_jll]]
uuid = "14a3606d-f60d-562e-9121-12d972cd8159"

[[NetworkOptions]]
uuid = "ca575930-c2e3-43a9-ace4-1e988b2c1908"

[[OrderedCollections]]
git-tree-sha1 = "85f8e6578bf1f9ee0d11e7bb1b1456435479d47c"
uuid = "bac558e1-5e72-5ebc-8fee-abe8a469f55d"
version = "1.4.1"

[[Pkg]]
deps = ["Artifacts", "Dates", "Downloads", "LibGit2", "Libdl", "Logging", "Markdown", "Printf", "REPL", "Random", "SHA", "Serialization", "TOML", "Tar", "UUIDs", "p7zip_jll"]
uuid = "44cfe95a-1eb2-52ea-b672-e2afdf69b78f"

[[Printf]]
deps = ["Unicode"]
uuid = "de0858da-6303-5e67-8744-51eddeeeb8d7"

[[REPL]]
deps = ["InteractiveUtils", "Markdown", "Sockets", "Unicode"]
uuid = "3fa0cd96-eef1-5676-8a61-b3b8758bbffb"

[[Random]]
deps = ["Serialization"]
uuid = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c"

[[ResumableFunctions]]
deps = ["MacroTools"]
git-tree-sha1 = "b198ee5bb6762423d3c61caacbdd43e640be265a"
uuid = "c5292f4c-5179-55e1-98c5-05642aab7184"
version = "0.6.1"

[[SHA]]
uuid = "ea8e919c-243c-51af-8825-aaa63cd721ce"

[[Serialization]]
uuid = "9e88b42a-f829-5b0c-bbe9-9e923198166b"

[[SharedArrays]]
deps = ["Distributed", "Mmap", "Random", "Serialization"]
uuid = "1a1011a3-84de-559e-8e89-a11a2f7dc383"

[[SimJulia]]
deps = ["DataStructures", "Dates", "ResumableFunctions"]
git-tree-sha1 = "ee1b863b5c9913ba40df8cd3bd7bb58837fb24c2"
uuid = "428bdadb-6287-5aa5-874b-9969638295fd"
version = "0.8.2"

[[Sockets]]
uuid = "6462fe0b-24de-5631-8697-dd941f90decc"

[[SparseArrays]]
deps = ["LinearAlgebra", "Random"]
uuid = "2f01184e-e22b-5df5-ae63-d93ebab69eaf"

[[Statistics]]
deps = ["LinearAlgebra", "SparseArrays"]
uuid = "10745b16-79ce-11e8-11f9-7d13ad32a3b2"

[[TOML]]
deps = ["Dates"]
uuid = "fa267f1f-6049-4f14-aa54-33bafae1ed76"

[[Tar]]
deps = ["ArgTools", "SHA"]
uuid = "a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e"

[[Test]]
deps = ["InteractiveUtils", "Logging", "Random", "Serialization"]
uuid = "8dfed614-e22c-5e08-85e1-65c5234f0b40"

[[UUIDs]]
deps = ["Random", "SHA"]
uuid = "cf7118a7-6976-5b1a-9a39-7adc72f591a4"

[[Unicode]]
uuid = "4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5"

[[Zlib_jll]]
deps = ["Libdl"]
uuid = "83775a58-1f1d-513f-b197-d71354ab007a"

[[nghttp2_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "8e850ede-7688-5339-a07c-302acd2aaf8d"

[[p7zip_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "3f19e933-33d8-53b3-aaab-bd5110c3b7a0"
"""

# ╔═╡ Cell order:
# ╟─1546ff80-0faf-11eb-2e03-a3ed4337a0df
# ╠═3689b520-0faf-11eb-3743-95fd62f74574
# ╠═7926ee20-0faf-11eb-0b72-990ad61c08ea
# ╠═82b07d30-0faf-11eb-3b48-2dccf08d0545
# ╠═57765b80-0faf-11eb-2e25-f9d8a95128be
# ╠═996923b0-0faf-11eb-0b98-b9c64f28e5c0
# ╠═a83919e2-0faf-11eb-17ef-a3eac492c533
# ╠═a3a70ea2-0faf-11eb-33c8-dd40db996416
# ╠═abd7c470-0faf-11eb-071e-4535258ede59
# ╠═ad4f4940-0faf-11eb-22b9-0b324557463d
# ╠═aebda650-0faf-11eb-0ee5-074a408638d7
# ╟─e85462f0-0faf-11eb-0d54-e52e8c1e9b26
# ╟─0153c520-0fb0-11eb-1253-0bd7e9dd04ee
# ╠═0ba3d880-0fb0-11eb-3508-d55bfc20056c
# ╠═3ca57832-0fb0-11eb-1853-a947bdd4ebc1
# ╠═105133ee-0fb0-11eb-1eba-238a216c5182
# ╟─18ba5ee0-0fb0-11eb-1c6d-e1ced026d640
# ╠═2326d3e2-0fb0-11eb-1827-6d08b4032c34
# ╟─31d8458e-0fb0-11eb-0fe5-0b2a1a5d56c3
# ╟─b106b67e-0fb0-11eb-04f2-a734c4fa2e3b
# ╠═c5df5262-0fb0-11eb-2125-755ecf44ff81
# ╠═d80b92f0-0fb0-11eb-04f5-1d40f00d07b8
# ╠═bc5dbd20-0fb1-11eb-0bda-c3e4c7877daa
# ╟─eda6bb80-0fb0-11eb-2f87-d586f0b69f26
# ╠═f67c3cce-0fb0-11eb-3349-4181800dde90
# ╟─061cc970-0fb1-11eb-0210-d7d0f215be77
# ╠═16770920-0fb1-11eb-1551-67668809b19a
# ╟─32c0db60-0fb1-11eb-3d75-f1a189baf482
# ╠═ce847f70-0fb1-11eb-144b-6b9542b72e9b
# ╟─f8b8f0ee-0fb1-11eb-13d6-571cad22a19a
# ╠═05760cb2-0fb2-11eb-2bc4-dd2a2bfde126
# ╟─1d92d712-0fb2-11eb-23fd-4554371e8a3b
# ╠═3778c8b0-0fb2-11eb-2c8f-379bf1d61719
# ╟─6e3a9360-0fb2-11eb-11dc-af7b71bd4184
# ╠═7845ae80-0fb2-11eb-195b-4d0d4ffca60b
# ╟─9a77cd30-0fb2-11eb-1196-df634baf199d
# ╠═c8dbb78e-0fb2-11eb-1ed5-554d10df71a8
# ╠═d683334e-0fb2-11eb-3dc4-4be3043674a7
# ╟─eff30a90-0fb2-11eb-01c6-c3a35033923d
# ╟─066d6f8e-0fb3-11eb-0979-ab193faf5653
# ╠═0a431330-0fb4-11eb-2795-2194b90087ee
# ╠═c3526920-0fb4-11eb-09cb-c320ebe70780
# ╠═fa9830e0-0fb4-11eb-0098-5d09cf3ae3e2
# ╠═8c905050-0fb4-11eb-3218-ad71581a62e9
# ╠═214e781e-0fb5-11eb-10fe-2d8c3f9ce347
# ╠═13ba2120-0fb3-11eb-0599-831b085542c8
# ╟─461ec14e-0fb5-11eb-38f0-61ad30ab4e1e
# ╟─5d04b960-0fb5-11eb-01fe-fd0ff58627f6
# ╠═4047da00-0fb5-11eb-23a2-19f13af4fac6
# ╠═5824f8c0-0fb4-11eb-0073-15bcb8f48aec
# ╠═23885800-0fb4-11eb-0378-1191e7ec5ca8
# ╟─835bf0b0-0fb5-11eb-2a68-275326c4e73c
# ╠═a2c77550-0fb5-11eb-10b3-151670af6203
# ╠═ab861340-0fb5-11eb-29ff-45bc893e6e6f
# ╠═aff2bc30-0fb5-11eb-365f-7b96cdbce30e
# ╠═b54c3620-0fb5-11eb-2348-b9f57946f679
# ╟─00000000-0000-0000-0000-000000000001
# ╟─00000000-0000-0000-0000-000000000002


text:
using Test
import XSBenchThreads
import ArgParse

@testset "inputs" begin
    args::Array{String,1} = ["-g", "32000", "-m", "event"]
    inputs = XSBenchThreads.read_CLI(args)
    @test inputs.n_gridpoints == 32_000
end

@testset "inputs_exception" begin
    args::Array{String,1} = ["-g", "0", "-m", "this_method"]
    @test_throws ArgParse.ArgParseError("out of range input for -g: 0") XSBenchThreads.read_CLI(
        args,
    )
end


text: Dict{String,Any}("slash" => Dict{String,Any}("value" => "This string has a \\/ slash character.","type" => "string"),"formfeed" => Dict{String,Any}("value" => "This string has a \\f form feed character.","type" => "string"),"backslash" => Dict{String,Any}("value" => "This string has a \\\\ backslash character.","type" => "string"),"newline" => Dict{String,Any}("value" => "This string has a \\n new line character.","type" => "string"),"carriage" => Dict{String,Any}("value" => "This string has a \\r carriage return character.","type" => "string"),"backspace" => Dict{String,Any}("value" => "This string has a \\b backspace character.","type" => "string"),"tab" => Dict{String,Any}("value" => "This string has a \\t tab character.","type" => "string"))

max_stars_repo_name: vanillajonathan/julia

max_issues_repo_name: vanillajonathan/julia

max_forks_repo_name: vanillajonathan/julia