text:
using Makie
using Observables

growth(🐇, 🥕) = 🐇 * 🥕 * (1.0 - 🐇)
 function orbitdiagram(growth, r1, r2, n = 500, a = zeros(1000, n); T = 1000)
     rs = range(r1, stop = r2, length = 1000)
     for (j, r) in enumerate(rs)
         x = 0.5
         for _ in 1:T; x = growth(x, r); end
         for i in 1:n
             x = growth(x, r)
             @inbounds a[j, i] = x
         end
     end
     rs, a
 end
 r1 = slider(0:0.001:4, raw = true, camera=campixel!, start = 0.0)
 r2 = slider(0:0.001:4, raw = true, camera=campixel!, start = 4)
 n1 = 500; n2 = 1000; a = zeros(n2, n1)
 positions = Vector{Point2f0}(undef, n1 * n2)
 r1node, r2node = r1[end][:value], r2[end][:value]
 r1r2=lift(tuple, r1node, r2node)
 pos = lift(r1r2) do (r1, r2,)
     global a
     rs, a = orbitdiagram(growth, r1, r2, size(a, 2), a)
     dim = size(a, 2)
     for (i, r) in enumerate(rs)
         positions[((i-1)*dim) + 1 : (i*dim)] .= Point2f0.(r, view(a, i, :))
     end
     positions
 end
 p = scatter(
     pos, markersize = 0.006, color = (:black, 0.2),
     show_axis = false
 )
 onany(pos) do pos
     # faster to give the boundingbox ourselves, since otherwise we'll need to
     # loop over pos!
     #AbstractPlotting.update_limits!(p) # <- would calculate bb
     AbstractPlotting.update_limits!(p, FRect(r1node[], 0, r2node[] - r1node[], 1))
     AbstractPlotting.update!(p)
 end
 scene = hbox(
     p,
     vbox(r1, r2)
 )
 RecordEvents(scene, "output")

max_stars_repo_name: terasakisatoshi/juliaExer

max_issues_repo_name: terasakisatoshi/juliaExer

max_forks_repo_name: terasakisatoshi/juliaExer


text:
seed!(12345)

function testSortedUniforms(low, high, h, N)
  function cdf(x::Float64)
    return x
  end
  samples = sampleSortedUniforms(N)
  ## check that they are sorted first
  for j in 2:N
    if samples[j] < samples[j-1]
      return 0.0
    end
  end
  i::Int64 = 0
  function sampler()
    i = i + 1
    return samples[i]
  end
  return testGOFContinuous(cdf, sampler, low, high, h, N)
end

@test testSortedUniforms(0.01, 0.99, 0.01, 2^21) > 0.01
@test testSortedUniforms(0.02, 0.98, 0.02, 2^10) > 0.01

ext: jl


text:
using RvSpectMLBase
using Test

#=
 This only tests functions from src/utils that don't depend on data structures.
 test/data_structure.jl should test functions that depend on the data structure.
 Functions using multiple data structures should be tested in the more complex data structure's file.
=#

@testset "Computer Science Algorithms" begin

    @testset "allequal" begin
    @test RvSpectMLBase.allequal([1,1,1,1])
    @test !RvSpectMLBase.allequal([1,2,3,4])
    end

    @testset "findargminmax" begin
        res = RvSpectMLBase.findargminmax([10.0, 30.0, -20.0, 40.0])
        @test res.min == -20.0
        @test res.max ==  40.0
        @test res.argmin ==  3
        @test res.argmax == 4
    end
    @testset "searchsortednearest" begin
        @test RvSpectMLBase.searchsortednearest(-cos.(π*(1:16)./16), 0.0) == 8
    end
end

max_stars_repo_name: RvSpectML/RvSpectMLTemplate

max_issues_repo_name: RvSpectML/RvSpectMLTemplate

max_forks_repo_name: RvSpectML/RvSpectMLTemplate


text:
"""
$(TYPEDEF)

Base for types defining stochastic bath object.
"""
abstract type StochasticBath <: AbstractBath end

build_correlation(bath::AbstractBath) =
    SingleFunctionMatrix((t₁, t₂) -> correlation(t₁ - t₂, bath))
build_spectrum(bath::AbstractBath) = (ω) -> spectrum(ω, bath)

"""
$(SIGNATURES)

Calculate the Lamb shift of `bath`. All the keyword arguments of `quadgk` function is supported.
"""
S(w, bath::AbstractBath; kwargs...) = lambshift(w, (ω) -> spectrum(ω, bath); kwargs...)

"""
$(SIGNATURES)

Calculate spectral density ``γ(ω)`` of `bath`.
"""
γ(ω, bath::AbstractBath) = spectrum(ω, bath)

function build_lambshift(ω_range::AbstractVector, turn_on::Bool, bath::AbstractBath, ::Nothing)
    if turn_on == true
        if isempty(ω_range)
            S_loc = (ω) -> S(ω, bath)
        else
            s_list = [S(ω, bath) for ω in ω_range]
            S_loc = construct_interpolations(ω_range, s_list)
        end
    else
        S_loc = (ω) -> 0.0
    end
    S_loc
end

function build_lambshift(ω_range::AbstractVector, ::Bool, bath::AbstractBath, lambshift_S::Dict)
    if isempty(ω_range)
        S_loc = (ω) -> S(ω, bath)
    else
        s_list = [S(ω, bath; lambshift_S...) for ω in ω_range]
        S_loc = construct_interpolations(ω_range, s_list)
    end
end

build_lambshift(::AbstractVector, ::Bool, ::AbstractBath, lambshift_S) = lambshift_S

"""
$(SIGNATURES)

Calculate the two point correlation function ``C(t1, t2)`` of `bath`. Fall back to `correlation(t1-t2, bath)` unless otherwise defined.
"""
@inline correlation(t1, t2, bath::AbstractBath) = correlation(t1 - t2, bath)

"""
$(SIGNATURES)

Calculate the bath time scale ``τ_{SB}`` from the bath correlation function `cfun`. ``τ_{SB}`` is defined as ``1/τ_{SB}=∫_0^∞ |C(τ)|dτ``. The upper limit of the integration can be modified using keyword `lim`. `atol` and `rtol` are the absolute and relative error tolerance of the integration.
"""
function τ_SB(cfun; lim=Inf, rtol=sqrt(eps()), atol=0)
    res, err = quadgk((x) -> abs(cfun(x)), 0, lim, rtol=rtol, atol=atol)
    1 / res, err / abs2(res)
end

"""
$(SIGNATURES)

Calculate the bath time scale ``τ_{SB}`` for the `bath` object.
"""
τ_SB(bath::AbstractBath; lim=Inf, rtol=sqrt(eps()), atol=0) =
    τ_SB((t) -> correlation(t, bath), lim=lim, rtol=rtol, atol=atol)

"""
$(SIGNATURES)

Calculate the bath time scale ``τ_B`` from the correlation function `cfun`. ``τ_B`` is defined as ``τ_B/τ_{SB} = ∫_0^T τ|C(τ)|dτ``. The upper limit of the integration ``T`` is specified by `lim`. `τsb` is the other bath time scale ``1/τ_{SB}=∫_0^∞ |C(τ)|dτ``. `atol` and `rtol` are the absolute and relative error tolerance for the integration.
"""
function τ_B(cfun, lim, τsb; rtol=sqrt(eps()), atol=0)
    res, err = quadgk((x) -> x * abs(cfun(x)), 0, lim, rtol=rtol, atol=atol)
    res * τsb, err * τsb
end

"""
$(SIGNATURES)

Calculate the bath time scale ``τ_B`` for the `bath` object.
"""
τ_B(bath::AbstractBath, lim, τsb; rtol=sqrt(eps()), atol=0) =
    τ_B((t) -> correlation(t, bath), lim, τsb; rtol=rtol, atol=atol)

function coarse_grain_timescale(cfun, lim; rtol=sqrt(eps()), atol=0)
    τsb, err_sb = τ_SB(cfun, rtol=rtol, atol=atol)
    τb, err_b = τ_B(cfun, lim, τsb, rtol=rtol, atol=atol)
    sqrt(τsb * τb / 5), (err_sb * τb + τsb * err_b) / 10 / sqrt(τsb * τb / 5)
end

"""
$(SIGNATURES)

Calculate the optimal coarse grain time scale ``T_a=√{τ_{SB}τ_B/5}`` for a total evolution time `lim`. `atol` and `rtol` are the absolute and relative error for the integration.
"""
function coarse_grain_timescale(
    bath::AbstractBath,
    lim;
    rtol=sqrt(eps()),
    atol=0,
)
    τsb, err_sb = τ_SB(bath, rtol=rtol, atol=atol)
    τb, err_b = τ_B(bath, lim, τsb, rtol=rtol, atol=atol)
    sqrt(τsb * τb / 5), (err_sb * τb + τsb * err_b) / 10 / sqrt(τsb * τb / 5)
end


text:
using MPI: MPI, Comm, Win
using Test

"""
Create a shared array, allocated by process with rank `owner_rank` on the
node_comm provided (i.e. when `MPI.Comm_rank(node_comm) == owner_rank`). Assumes all
processes on the node_comm are on the same node, or, more precisely that they
can create/access a shared mem block between them.

usage:
nrows, ncols = 100, 11
const arr = mpi_shared_array(MPI.COMM_WORLD, Int, (nrows, nworkers_node), owner_rank=0)
"""
function mpi_shared_array(node_comm::Comm, ::Type{T}, sz::Tuple{Vararg{Int}}; owner_rank=0) where T
    node_rank = MPI.Comm_rank(node_comm)
    len_to_alloc = MPI.Comm_rank(node_comm) == owner_rank ? prod(sz) : 0
    if node_rank == owner_rank
        win, array = MPI.Win_allocate_shared(Array{T}, sz, node_comm)
    else
        win, array = MPI.Win_allocate_shared(Array{T}, 0, node_comm)
    end
    if node_rank != owner_rank
        array = MPI.Win_shared_query(Array{T}, sz, win, owner_rank)
    end
    win, array
end

function main()
    MPI.Init()

    global_comm = MPI.COMM_WORLD

    if MPI.Comm_size(global_comm) > 1

        group_comm_id = 1
        node_rank = MPI.Comm_rank(global_comm) # do this differently in real code
        node_comm = MPI.Comm_split(global_comm, group_comm_id, node_rank)
        owner_rank = 1

        win, shared_arr =
            mpi_shared_array(node_comm, Float32, (100, 2); owner_rank=owner_rank)

        if node_rank == 0
            shared_arr[:, 1] .= 1:100
        elseif node_rank == 1
            shared_arr[:, 2] .= 901:1000
        end

        MPI.Barrier(node_comm) # finish writing before reading
        # check you can see those values on all processes
        @test all(shared_arr[:, 1] .== 1:100)
        @test all(shared_arr[:, 2] .== 901:1000)
        if node_rank <= 1
            len, elsize_bytes, baseptr = MPI.Win_shared_query(Ptr{Float32}, win, owner_rank)
            @test elsize_bytes == sizeof(Float32)
            @test len == sizeof(shared_arr)
            @test baseptr == pointer(shared_arr)
        end
        MPI.free(win)

    end

    MPI.Finalize()
end

# run with `mpirun -np 3 julia --project test_shared_win.jl`
main()
GC.gc()

@test MPI.Finalized()


text:
struct extended_function
    fmin::Function
    spline::Function
    fmax::Function
    xmin::Float64
    xmax::Float64
end

function extend_func(k, Pk, kmin, kmax) # Needs serious modification, Log/Lin??, slope eval != kmin/kmax
    filt = (k .>= kmin) .&  (k .<= kmax) .& (Pk .> 0)
    spl = Spline1D(log.(k[filt]), log.(Pk[filt]), k=2)
    splf = x -> exp(spl(log(x)))

    smin = derivative(spl, log(kmin))
    smax = derivative(spl, log(kmax))

    fmin = x -> splf(kmin) * (x/kmin)^smin
    fmax = x -> splf(kmax) * (x/kmax)^smax

    return extended_function(fmin, splf, fmax, kmin, kmax)
end

function eval_extend_func(Pkfunc, x)
    if x < Pkfunc.xmin
        Pkfunc.fmin(x)
    elseif x < Pkfunc.xmax
        Pkfunc.spline(x)
    else
        Pkfunc.fmax(x)
    end
end

(pk::extended_function)(x) = eval_extend_func(pk,x)

max_stars_repo_name: JosephTomlinson/GeneralBiasPk

max_issues_repo_name: JosephTomlinson/GeneralBiasPk

max_forks_repo_name: JosephTomlinson/GeneralBiasPk


text:
using NMRSpectraSimulator
using Test

@testset "NMRSpectraSimulator.jl" begin
    # Write your tests here.
end


text:
##########################
#Wrapper Stheno GP modeles
##########################
####
#output structs
####
#=
struct Hyperparmeter{T} <: AbstractVector{T}
        parm::Vector{T}
end

Base.length(p::Hyperparmeter) = length(p.parm)
Base.size(p::Hyperparmeter) = (length(p.parm),1)
Base.getindex(p::Hyperparmeter,i) = p.parm[i]
=#
"""
        GPModel{T <: Any}

Struct to store fitted model f̂ with given Kernel K and hyperparmeters θ
"""
struct GPModel{Tf <: Any, Ts <: Any}
        f̂::Tf
        K::Kernel
        θ::Dict{String,Ts}
end

"""
        GPpredict{Tf <: Any,Tx<: Any}

Struct to store precitions, f̂_pred of the model en used test points,x_test
"""
struct GPpredict{Tf <: Any,Tx<: Any}
        f̂_pred::Tf
        x_test::Tx
end

#####
#Fit and Predict
#####

"""
   fit_gp(x_train,y_train,k::Kernel,mod::GroupMod; θ = [1], σ²_n = 10^-6,optimise = false)

  Fit a Gaussian process with kernel `k` to the given training data `x_train`,`y_train`.
  Respectively the input constructs a corresponding activity values.
  Theta is the vector containing the hyperparameters of the model.
  If only one hyperparameter is needed, it still should be in a vector.
  Two kwarg are given:
  `σ²_n::`  which is the variance on the data points, default =``10^-6`` .
  `optimise::` Set to true if hyperparameters need to be optimised based
   on maximum likelihood estimation, default = false.

"""
function fit_gp(x_train,y_train,k::Kernel,mod::GroupMod; θ = [1], σ²_n = 10^-6,optimise = false)
        v_train = transform_data(x_train,mod::GroupMod,k)
        #set Gaussian procces in Stheno framework
        if optimise
                θ = gp_optimised(v_train,y_train,k,σ²_n)
        end
        # one
        fGP,θ_save = _creatGP(k,θ)
        push!(θ_save, "σ²_n" => σ²_n)
        f_posterior = fGP | Obs( fGP(v_train,σ²_n), y_train)
        #calculate f_postirior based on training data and the prior f
        return GPModel(f_posterior,k,θ_save)
end

"""
    fit_gp_graph(x_train,y_train::Vector,k::Kernel,parm)

  Fit a Gaussian process using a kernel on a graph.

  A weighted graph is build up using the full design space ,`S`, as nodes.
  The edge rule determines the weight on the edges.

  Base on the graph, the whole kernel is precomputed.
  As a result, the model requires the **indexes** of the training data in vector x_train,
  and not the construct.
  The y_train vector contains the activity values for the training data.
  Theta is the vector containing the hyperparameters of the model.
  If only one hyperparameter is needed, it still should be in a vector.
  Two kwarg are given:
  σ²_n::  which is the variance on the data points, default =``10^-6`` .
  optimise:: Set to true if hyperparameters
  need to be optimised based on maximum likelihood estimation, default = false.

  returns a GPModel with the posterior of the gp, the kernel, used hyperparameters
"""
function fit_gp_graph(S,x_train,y_train,k::KernelGraph,edgerule::EdgeRule;θ = [1,1],σ²_n = 10^-5,optimise = false)
        @assert eltype(x_train) == Int "The Kernel graphs requiers the indexes as input"
        n_laplace = setupgraph(S,edgerule)
        #set Gaussian procces in Stheno framework
        if optimise
                θ = gp_optimised(n_laplace,x_train,y_train,k,σ²_n)
        end
        fGP,θ_save = _creatGP(n_laplace,k,θ)
        push!(θ_save, "σ²_n" => σ²_n)
        f_posterior = fGP | Obs( fGP(x_train,σ²_n), y_train)
        #calculate f_postirior based on training data and the prior f
        return GPModel(f_posterior,k,θ_save)
end

function fit_gp_graph(x_train,y_train,k::KernelGraph,n_laplace;θ = [1],σ²_n = 10^-5,optimise = false)
        @assert eltype(x_train) == Int "The Kernel graphs requiers the indexes as input"
        #set Gaussian procces in Stheno framework
        if optimise
                θ = gp_optimised(n_laplace,x_train,y_train,k,σ²_n)
        end
        fGP,θ_save = _creatGP(n_laplace,k,θ)
        push!(θ_save, "σ²_n" => σ²_n)
        f_posterior = fGP | Obs( fGP(x_train,σ²_n), y_train)
        #calculate f_postirior based on training data and the prior f
        return GPModel(f_posterior,k,θ_save)
end

"""
        predict(x_test,model::GPModel,mod::GroupMod; σ²_test = true)
predicts the value from the unseen datapoints `x_test` using the given GPmodel object.
The use module are needed to transform the data in the proper format.

σ²_test = set the noise for the predictions.
By default is set to -1 and the mean value of the training noise is use.
"""
function predict_gp(x_test,model::GPModel,mod::GroupMod; σ²_test = -1 )
         v_test = transform_data(x_test,mod::GroupMod,model.K)
         if σ²_test == -1
                 σ²_test = mean(model.θ["σ²_n"])
         else
                 σ²_test = mean(σ²_test)
         end

         if isa(model.K,KernelGraph)
                 @assert eltype(x_test) == Int  "for kernel on a graph the index of the given combinations are required x_test"
        end
         return  GPpredict(model.f̂(v_test,σ²_test),x_test)
end

"""
        predict_gp(S,x_train,model::GPModel,mod::GroupMod; σ²_test = -1)
Fitlers first all seen data point out S and than predict values for the unseen datapoints

"""
function predict_gp(S,x_train,model::GPModel,mod::GroupMod; σ²_test = -1)
         x_test = filter(x-> !(x in x_train) ,S)
        return predict_gp(x_test,model::GPModel,mod::GroupMod; σ²_test = σ²_test)
end

######
#auxilary fit
######
"""
        _creatGP(k::Kernel, α)
Retuns an Stheno GP  model wiht a given kernel which is scaled with the parameter `α`.
"""
function _creatGP(k::Kernel, θ)
        @assert length(θ) == 1 " Kernel has only one hyperparamter, α"
        α = θ[1]
        fGP = α*GP(k, GPC())
        return (fGP,Dict{String,Any}("α"=>θ[1]))
end

"""
        _creatGP(k::Kernel, θ)
Retuns an Stheno GP  model with a diffusion kernel and hyperparameters θ.
"""
function _creatGP(n_laplace,gk::DiffusionKernel,θ)
        α = θ[1]
        β = 1
        k = Precomputed(kernelgraph(n_laplace,gk,β))
        fGP = α* GP(k, GPC())
        return (fGP,Dict{String,Any}("α"=>α,"β"=>β))
end

"""
        _creatGP(k::Kernel, α)
Retuns an Stheno GP  model with a p-randomwalk kernel and hyperparameters θ.
"""
function _creatGP(n_laplace,gk::PRandomKernel,θ)
        α = θ[1]
        a = 2 # makes sure a > 2
        k = Precomputed(kernelgraph(n_laplace,gk,a))
        fGP =  α*GP(k, GPC())
        return (fGP,Dict{String,Any}("α"=>α,"a"=>a,"p" => gk.p))
end

###############
# Hyperparmeter optimisation
# all optimisation is done with the Optim package
# https://github.com/JuliaNLSolvers/Optim.jl
###############

"""
     nlml_stheno(parm, x_train, y_train, k::Kernel, σ²_n = 1e-6)

 Calculates the negative log marginal likelihood for GP model, with given Kernel `k` and hyperparatmeters θ
 The model is trained with the given datapoints x_train and corresponding values y_train
 Adds a small offset ,`σ²_n`, is the variance added to the model.
"""
function nlml_stheno(θ_temp, x_train, y_train, k::Kernel, σ²_n)
    θ_exp = exp.(θ_temp) .+ 10^-6
    f,_ = _creatGP(k,θ_exp)
    return -logpdf(f(x_train,σ²_n), y_train)
end

"""
     nlml_stheno(parm, x_train, y_train, k::Kernel, σ²_n = 1e-6)

 Calculates the negative log marginal likelihood for GP model, with given Kernel `k` and hyperparatmeters θ
 The model is trained with the given datapoints x_train and corresponding values y_train
 Adds a small offset ,`σ²_n`, is the variance added to the model.
"""
function nlml_stheno(θ_temp,n_laplace,x_train, y_train, k::KernelGraph, σ²_n)
    θ_exp = exp.(θ_temp) .+ 1e-6
    f,_ = _creatGP(n_laplace,k,θ_exp)
    return -logpdf(f(x_train,σ²_n), y_train)
end

######
# gp_optimised 1 hyperparameter
#
######
"""
     gp_optimised(x_train,y_train,k::Kernel,σ²_n;min = -0.01, max = 100.0)

 Returns optimise a gp_model with a single hyperparameter
 with given input argument x_train,y_train,k,σ²_n
 The parameters are obtained by log maximum-likelihood estimation.
 The model uses the Goldensection algorithm  from Optim.jl,
 min and max are respectively the lower and upper
 initial boundary of the algorithm

"""
function gp_optimised(x_train,y_train,k::Kernel,σ²_n;min = -5, max = 8.0)
#do perform optimisation
results = Optim.optimize(θ_temp->nlml_stheno(θ_temp,x_train,y_train,k,σ²_n),min,max,
              GoldenSection())
#get optimal hyperparameters
        α_opt = exp.(Optim.minimizer(results)) .+ 10^-6
        return α_opt
end

"""
     gp_optimised(n_laplace,x_train,y_train,k::Kernel,σ²_n;θ₀=[0.0,0.0])

 Returns optimise a gp_model for a kernel on a graph with two hyperparameters
 with given input argument n_laplace, x_train, y_train, k, σ²_n
 The parameters are obtained by maximum-likelihood estimation.
 The model uses the NelderMead() algorithm  from Optim.jl,
 θ₀ is the initial starting point of the algoritme
"""
function gp_optimised(n_laplace,x_train,y_train,k::KernelGraph,σ²_n,min = -5, max = 10.0)
        results = Optim.optimize(θ_temp->nlml_stheno(θ_temp,n_laplace,x_train,y_train,k,σ²_n),min,max,
                      GoldenSection())
        #get optimal hyperparameters
                  θ_opt = exp.(Optim.minimizer(results)) .+ 10^-6
                return  θ_opt
end

######
# transform_data
######

"""
        transform_data(x_in,mod::GroupMod,::Linear)
 Current implementation opt Stheno linear model requires spacial data input.
 Function transforms the vector of constructs into the vector embedding
 and then transforms the data into `ColVecs` type to fit linear model
"""
function transform_data(x_in,mod::GroupMod,::Linear)
        # get vector embedding
        v_out = map(x -> _word2vec(x,mod),x_in)
        #transform to ColVecs
        return hcat(v_out...) |> ColVecs
end

"""
        transform_data(x_in,mod::GroupMod,::Kernel)
dummy tranform data, for non-stheno kernels

"""
transform_data(x_in,mod::GroupMod,::Kernel) = x_in

"""
        transform_data(x_in,mod::GroupMod,::Linear)
 Current implementation opt Stheno linear model requires spacial data input.
 Function transforms the vector of constructs into the vector embedding
 and then transforms the data into `ColVecs` type to fit linear model
"""

function transform_data(x_in,mod::GroupMod,::BaseKernel)
        # get vector embedding
        v_out = map(x -> _word2vec(x,mod),x_in)
        #transform to ColVecs
        return hcat(v_out...)
end

#=
"""
        _creatGP(k::Kernel, α)
Retuns an Stheno GP  model wiht a given kernel which is scaled with the parameter `α`.
"""

function _creatGP(k::EditDistancesKernel,θ)
        fGP =  θ[1]* GP(k, GPC())
        return (fGP,Dict{String,Any}("α"=>α,"β"=>β))
end

####
#linear
# think gradient is litte over the top....
####

"""
     gp_optimised(x_train,y_train::Vector,k::Linear,σ²_n; θ₀= [0])

 Returns the optimal hyperparameter for al linear kernel
"""

function gp_optimised(x_train,y_train,k::Linear,σ²_n; θ₀=[1.0])
        results = Optim.optimize(θ_temp->nlml_stheno(θ_temp,x_train,y_train,k,σ²_n),
                θ_temp->gradient(t -> nlml_stheno(t,x_train,y_train,k,σ²_n),θ_temp)[1],θ₀,
                BFGS(); inplace=false)
#get optimal hyperparameters
        α_opt = exp.(Optim.minimizer(results)) .+ 10^-6
        return α_opt
end

"""
     gp_optimised(n_laplace,x_train,y_train,k::Kernel,σ²_n;θ₀=[0.0,0.0])

 Returns optimise a gp_model for a kernel on a graph with two hyperparameters
 with given input argument n_laplace, x_train, y_train, k, σ²_n
 The parameters are obtained by maximum-likelihood estimation.
 The model uses the NelderMead() algorithm  from Optim.jl,
 θ₀ is the initial starting point of the algoritme
"""
function gp_optimised(n_laplace,x_train,y_train,k::PRandomKernel,σ²_n,θ₀=[1.0,1.0])
        results = Optim.optimize(θ_temp->nlml_stheno(θ_temp,n_laplace,x_train,y_train,k,σ²_n),θ₀,
                      NelderMead())
        #get optimal hyperparameters
                  θ_opt = exp.(Optim.minimizer(results)) .+ 10^-6
                return  θ_opt
end

=#

max_stars_repo_name: SamDier/BOMoD

max_issues_repo_name: SamDier/BOMoD

max_forks_repo_name: SamDier/BOMoD


text:
# ============================================================
# Structs of Cell Interface
# compatible with control volume structs
# ============================================================

# ------------------------------------------------------------
# General
# ------------------------------------------------------------

"""
$(TYPEDEF)

Cell interface with no distribution function

# Fields

$(FIELDS)
"""
mutable struct Interface{T,ND} <: AbstractInterface
    fw::T
end

function Interface(fw)
    n = size(fw, 1) - 2
    return Interface{typeof(fw),n}(fw)
end

"""
$(TYPEDEF)

Cell interface with no distribution function

# Fields

$(FIELDS)
"""
struct Interface1F{T1,T2,ND} <: AbstractInterface
    fw::T1
    ff::T2
end

function Interface1F(fw, ff)
    n = size(fw, 1) - 2
    return Interface1F{typeof(fw),typeof(ff),n}(fw, ff)
end

"""
$(TYPEDEF)

Cell interface with no distribution function

# Fields

$(FIELDS)
"""
struct Interface2F{T1,T2,ND} <: AbstractInterface
    fw::T1
    fh::T2
    fb::T2
end

function Interface2F(fw, fh, fb)
    n = size(fw, 1) - 2
    return Interface2F{typeof(fw),typeof(fh),n}(fw, fh, fb)
end

struct Interface3F{T1,T2,ND} <: AbstractInterface end

struct Interface4F{T1,T2,ND} <: AbstractInterface end

"""
$(SIGNATURES)

Construct cell interface
"""
function Interface(W, ND::Integer)
    fw = zero(W)

    return Interface{typeof(fw),ND}(fw)
end

"""
$(SIGNATURES)
"""
function Interface(W, F, ND::Integer)
    fw = zero(W)
    ff = zero(F)

    return Interface1F{typeof(fw),typeof(ff),ND}(fw, ff)
end

"""
$(SIGNATURES)
"""
function Interface(W, H, B, ND::Integer)
    fw = deepcopy(W)
    fh = zero(H)
    fb = zero(B)

    return Interface2F{typeof(fw),typeof(fh),ND}(fw, fh, fb)
end

# ------------------------------------------------------------
# The dimension-dependent structures are in archive mode only
# ------------------------------------------------------------
# 1D
# ------------------------------------------------------------

"""
    mutable struct Interface1D{A<:Union{Real,AA}} <: AbstractInterface1D
        fw::A
    end

1D cell interface with no distribution function
Note that deepcopy constructor is needed to work with StructArrays

"""
mutable struct Interface1D{A<:Union{Real,AA}} <: AbstractInterface1D
    fw::A
end

function Base.show(io::IO, ctr::Interface1D{A}) where {A}
    print(io, "Interface1D{$A}\n", "conservative fluxes: $(ctr.fw)\n")
end

"""
    mutable struct Interface1D1F{A,B} <: AbstractInterface1D
        fw::A
        ff::B
    end

1D cell interface with 1 distribution function
Note that deepcopy constructor is needed to work with StructArrays

"""
mutable struct Interface1D1F{A,B<:AA} <: AbstractInterface1D
    fw::A
    ff::B
end

function Base.show(io::IO, ctr::Interface1D1F{A,B}) where {A,B}
    print(
        io,
        "Interface1D1F{$A,$B}\n",
        "conservative fluxes: $(ctr.fw)\n",
        "pdf fluxes: ff\n",
    )
end

"""
    struct Interface1D2F{A,B} <: AbstractInterface1D
        fw::A
        fh::B
        fb::B

        function Interface1D2F(w::AA, f::AA)
            fw = zero(w)
            fh = zero(f)
            fb = zero(f)

            new{typeof(fw),typeof(fh)}(fw, fh, fb)
        end
    end

1D cell interface with 2 distribution functions

"""
struct Interface1D2F{A,B<:AA} <: AbstractInterface1D
    fw::A
    fh::B
    fb::B
end

function Interface1D2F(w, f::AA)
    fw = zero(w)
    fh = zero(f)
    fb = zero(f)

    return Interface1D2F(fw, fh, fb)
end

function Base.show(io::IO, ctr::Interface1D2F{A,B}) where {A,B}
    print(
        io,
        "Interface1D2F{$A,$B}\n",
        "conservative fluxes: $(ctr.fw)\n",
        "pdf fluxes: fh, fb\n",
    )
end

"""
    struct Interface1D3F{A,B,C} <: AbstractInterface1D
        fw::A
        fh0::B
        fh1::B
        fh2::B
        femL::C
        femR::C
    end

1D cell interface with 3 distribution functions

"""
struct Interface1D3F{A,B,C} <: AbstractInterface1D
    fw::A
    fh0::B
    fh1::B
    fh2::B
    femL::C
    femR::C
end

# deterministic
function Interface1D3F(w::AA, f::AA, E::AA{<:Real,1})
    fw = zeros(eltype(w), axes(w))
    fh0 = zeros(eltype(f), axes(f))
    fh1 = zeros(eltype(f), axes(f))
    fh2 = zeros(eltype(f), axes(f))
    femL = zeros(eltype(E), 8)
    femR = zeros(eltype(E), 8)

    return Interface1D3F(fw, fh0, fh1, fh2, femL, femR)
end

# stochastic
function Interface1D3F(w::AA, f::AA, E::AA{<:Real,2})
    fw = zeros(eltype(w), axes(w))
    fh0 = zeros(eltype(f), axes(f))
    fh1 = zeros(eltype(f), axes(f))
    fh2 = zeros(eltype(f), axes(f))
    femL = zeros(eltype(E), 8, axes(E, 2))
    femR = zeros(eltype(E), 8, axes(E, 2))

    return Interface1D3F(fw, fh0, fh1, fh2, femL, femR)
end

# Rykov
function Interface1D3F(w::AA, f::AA)
    fw = zero(w)
    fh0 = zero(f)
    fh1 = zero(f)
    fh2 = zero(f)
    femL = nothing
    femR = nothing

    return Interface1D3F(fw, fh0, fh1, fh2, femL, femR)
end

function Base.show(io::IO, ctr::Interface1D3F{A,B,C}) where {A,B,C}
    print(
        io,
        "Interface1D3F{$A,$B,$C}\n",
        "conservative fluxes: $(ctr.fw)\n",
        "pdf fluxes: fh0, fh1, fh2\n",
        "electromagnetic fluxes: femL, femR\n",
    )
end

"""
    struct Interface1D4F{A,B,C} <: AbstractInterface1D
        fw::A
        fh0::B
        fh1::B
        fh2::B
        fh3::B
        femL::C
        femR::C
    end

1D cell interface with 4 distribution functions

"""
struct Interface1D4F{A,B,C} <: AbstractInterface1D
    fw::A
    fh0::B
    fh1::B
    fh2::B
    fh3::B
    femL::C
    femR::C
end

# deterministic
function Interface1D4F(w::AA, f::AA, E::AA{<:Real,1})
    fw = zeros(eltype(w), axes(w))
    fh0 = zeros(eltype(f), axes(f))
    fh1 = zeros(eltype(f), axes(f))
    fh2 = zeros(eltype(f), axes(f))
    fh3 = zeros(eltype(f), axes(f))
    femL = zeros(eltype(E), 8)
    femR = zeros(eltype(E), 8)

    return Interface1D4F(fw, fh0, fh1, fh2, fh3, femL, femR)
end

# stochastic
function Interface1D4F(w::AA, f::AA, E::AA{<:Real,2})
    fw = zeros(eltype(w), axes(w))
    fh0 = zeros(eltype(f), axes(f))
    fh1 = zeros(eltype(f), axes(f))
    fh2 = zeros(eltype(f), axes(f))
    fh3 = zeros(eltype(f), axes(f))
    femL = zeros(eltype(E), 8, axes(E, 2))
    femR = zeros(eltype(E), 8, axes(E, 2))

    return Interface1D4F(fw, fh0, fh1, fh2, fh3, femL, femR)
end

function Base.show(io::IO, ctr::Interface1D4F{A,B,C}) where {A,B,C}
    print(
        io,
        "Interface1D4F{$A,$B,$C}\n",
        "conservative fluxes: $(ctr.fw)\n",
        "pdf fluxes: fh0, fh1, fh2, fh3\n",
        "electromagnetic fluxes: femL, femR\n",
    )
end

# ------------------------------------------------------------
# 2D
# ------------------------------------------------------------

"""
    mutable struct Interface2D{A,B,C} <: AbstractInterface2D
        len::A
        n::B
        fw::C

        function Interface2D(L::Real, C::Real, S::Real, w::AA)
            len = L
            n = [C, S]

            fw = zero(w)

            new{typeof(len),typeof(n),typeof(fw)}(len, n, fw)
        end
    end

2D cell interface with no distribution function

"""
mutable struct Interface2D{A,B,C} <: AbstractInterface2D
    len::A
    n::B
    fw::C
end

function Interface2D(L::Real, C::Real, S::Real, w::AA)
    len = L
    n = [C, S]

    fw = zero(w)

    return Interface2D(len, n, fw)
end

function Base.show(io::IO, ctr::Interface2D{A,B,C}) where {A,B,C}
    print(
        io,
        "Interface2D{$A,$B,$C}\n",
        "length: $(ctr.len)\n",
        "normal vector: ($(ctr.n[1]),$(ctr.n[2]))\n",
        "conservative fluxes: $(ctr.fw)\n",
    )
end

"""
    mutable struct Interface2D1F{A,B,C,D} <: AbstractInterface2D
        len::A
        n::B
        fw::C
        ff::D

        function Interface2D1F(L::Real, C::Real, S::Real, w::AA, f::AA)
            len = L
            n = [C, S]

            fw = zero(w)
            ff = zero(f)

            new{typeof(len),typeof(n),typeof(fw),typeof(ff)}(len, n, fw, ff)
        end
    end

2D cell interface with 1 distribution function

"""
mutable struct Interface2D1F{A,B,C,D} <: AbstractInterface2D
    len::A
    n::B
    fw::C
    ff::D
end

function Interface2D1F(L::Real, C::Real, S::Real, w, f::AA)
    len = L
    n = [C, S]

    fw = zero(w)
    ff = zero(f)

    return Interface2D1F(len, n, fw, ff)
end

function Base.show(io::IO, ctr::Interface2D1F{A,B,C,D}) where {A,B,C,D}
    print(
        io,
        "Interface2D1F{$A,$B,$C}\n",
        "length: $(ctr.len)\n",
        "normal vector: ($(ctr.n[1]),$(ctr.n[2]))\n",
        "conservative fluxes: $(ctr.fw)\n",
        "pdf fluxes: ff",
    )
end

"""
    struct Interface2D2F{A,B,C,D} <: AbstractInterface2D
        len::A
        n::B
        fw::C
        fh::D
        fb::D

        function Interface2D2F(L::Real, C::Real, S::Real, w::AA, f::AA)
            len = L
            n = [C, S]

            fw = zeros(eltype(w), axes(w))
            fh = zeros(eltype(f), axes(f))
            fb = zeros(eltype(f), axes(f))

            new{typeof(len),typeof(n),typeof(fw),typeof(fh)}(len, n, fw, fh, fb)
        end
    end

2D cell interface with 2 distribution functions

"""
struct Interface2D2F{A,B<:AV,C,D} <: AbstractInterface2D
    len::A
    n::B
    fw::C
    fh::D
    fb::D
end

function Interface2D2F(L::Real, C::Real, S::Real, w::AA, f::AA)
    len = L
    n = @SArray [C, S]

    fw = zero(w)
    fh = zero(f)
    fb = zero(f)

    return Interface2D2F(len, n, fw, fh, fb)
end

function Base.show(io::IO, ctr::Interface2D2F{A,B,C,D}) where {A,B,C,D}
    print(
        io,
        "Interface2D2F{$A,$B,$C}\n",
        "length: $(ctr.len)\n",
        "normal vector: ($(ctr.n[1]),$(ctr.n[2]))\n",
        "conservative fluxes: $(ctr.fw)\n",
        "pdf fluxes: fh, fb",
    )
end

"""
    struct Interface2D3F{A,B,C,D,E} <: AbstractInterface2D
        len::A
        n::B
        fw::C
        fh0::D
        fh1::D
        fh2::D
        femL::E
        femR::E
        femLU::E
        femLD::E
        femRU::E
        femRD::E
    end

2D cell interface with 3 distribution functions

"""
struct Interface2D3F{A,B,C,D,E} <: AbstractInterface2D
    len::A
    n::B
    fw::C
    fh0::D
    fh1::D
    fh2::D
    femL::E
    femR::E
    femLU::E
    femLD::E
    femRU::E
    femRD::E
end

function Interface2D3F(L::Real, C::Real, S::Real, w::AA, f::AA, E::AA{<:Real,1})
    len = L
    n = @SArray [C, S]

    fw = zero(w)
    fh0 = zero(f)
    fh1 = zero(f)
    fh2 = zero(f)

    femL = zeros(eltype(E), 8)
    femR = zeros(eltype(E), 8)
    femLU = zeros(eltype(E), 8)
    femLD = zeros(eltype(E), 8)
    femRU = zeros(eltype(E), 8)
    femRD = zeros(eltype(E), 8)

    return Interface2D3F(len, n, fw, fh0, fh1, fh2, femL, femR, femLU, femLD, femRU, femRD)
end

function Interface2D3F(L::Real, C::Real, S::Real, w::AA, f::AA, E::AA{<:Real,2})
    len = L
    n = [C, S]

    fw = zero(w)
    fh0 = zero(f)
    fh1 = zero(f)
    fh2 = zero(f)

    femL = zeros(eltype(E), 8, axes(E, 2))
    femR = zeros(eltype(E), 8, axes(E, 2))
    femLU = zeros(eltype(E), 8, axes(E, 2))
    femLD = zeros(eltype(E), 8, axes(E, 2))
    femRU = zeros(eltype(E), 8, axes(E, 2))
    femRD = zeros(eltype(E), 8, axes(E, 2))

    return Interface2D3F(len, n, fw, fh0, fh1, fh2, femL, femR, femLU, femLD, femRU, femRD)
end

# Rykov
function Interface2D3F(L::Real, C::Real, S::Real, w::AA, f::AA)
    len = L
    n = [C, S]

    fw = zero(w)
    fh0 = zero(f)
    fh1 = zero(f)
    fh2 = zero(f)

    femL = nothing
    femR = nothing
    femLU = nothing
    femLD = nothing
    femRU = nothing
    femRD = nothing

    return Interface2D3F(len, n, fw, fh0, fh1, fh2, femL, femR, femLU, femLD, femRU, femRD)
end

function Base.show(io::IO, ctr::Interface2D3F{A,B,C,D,E}) where {A,B,C,D,E}
    print(
        io,
        "Interface2D3F{$A,$B,$C}\n",
        "length: $(ctr.len)\n",
        "normal vector: ($(ctr.n[1]),$(ctr.n[2]))\n",
        "conservative fluxes: $(ctr.fw)\n",
        "pdf fluxes: fh0, fh1, fh2\n",
        "electromagnetic fluxes: femL, femR, femLU, femLD, femRU, femRD\n",
    )
end


text:
@testset "Get jobs" begin
    Pkg.activate("./")
    cluster_name = ENV["BANYAN_CLUSTER_NAME"]

    job_id = create_job()
    running_jobs = get_running_jobs(cluster_name)
    destroy_job(job_id)
    jobs = get_jobs(cluster_name)

    @test all(j -> j[2]["status"] == "running", running_jobs)
    @test any(j -> j[1] == job_id, running_jobs)
    @test any(j -> (j[1] == job_id && j[2]["status"] == "completed"), jobs)
end

@testset "Create jobs with nowait=$nowait" for
        nowait in [true, false]
    Pkg.activate("envs/DataAnalysisProject/")
    cluster_name = ENV["BANYAN_CLUSTER_NAME"]

    job_id = create_job(
        cluster_name=cluster_name,
        nworkers=2,
        nowait=nowait
    )

    job_status = get_job_status(job_id)
    if !nowait
        @test job_status == "running"
    else
        @test job_status == "creating"
        while job_status == "creating"
            sleep(20)
            job_status = get_job_status(job_id)
        end
        @test job_status == "running"
    end

    destroy_job(job_id)
end

@testset "Create jobs where store_logs_in_s3=$store_logs_in_s3" for
        store_logs_in_s3 in [true, false]
    Pkg.activate("./")
    cluster_name = ENV["BANYAN_CLUSTER_NAME"]

    job_id = create_job(
        cluster_name=cluster_name,
        store_logs_in_s3=store_logs_in_s3,
    )
    destroy_job(job_id)
    sleep(10)

    log_file = "banyan-log-for-job-$job_id"
    println("s3://$(get_cluster_s3_bucket_name(cluster_name))/$(log_file)")
    @test store_logs_in_s3 == isfile(
        S3Path("s3://$(get_cluster_s3_bucket_name(cluster_name))/$(log_file)",
        config=Banyan.get_aws_config())
    )
end

@testset "Create jobs using $env_type environment" for env_type in ["local", "remote"]
    cluster_name = ENV["BANYAN_CLUSTER_NAME"]

    if env_type == "remote"
        Pkg.activate("./")

        # Create job
        job_id = create_job(
            cluster_name = cluster_name,
            nworkers = 2,
            pf_dispatch_table = "https://raw.githubusercontent.com/banyan-team/banyan-julia/v0.1.3/Banyan/res/pf_dispatch_table.json",
            url = "https://github.com/banyan-team/banyan-julia.git",
            branch = "v0.1.3",
            directory = "banyan-julia/BanyanDataFrames/test",
            dev_paths = [
                "banyan-julia/Banyan",
                "banyan-julia/BanyanDataFrames",
            ],
            force_clone = true,
            force_pull = true,
            force_install = true,
        )

        job_status = get_job_status(job_id)
        @test job_status == "running"

        # Destroy job
        destroy_job(job_id)

    elseif env_type == "envs"
        # Activate environment
        Pkg.activate("envs/DataAnalysisProject/")

        # Import packages
        using Distributions
        using Statistics

        # Test environment detection
        env_dir = get_julia_environment_dir()
        loaded_packages = get_loaded_packages()

        @test abspath(env_dir) == abspath("envs/DataAnalysisProject/")
        @test "Distributions" in loaded_packages && "Statistics" in loaded_packages

        # Create job
        job_id = create_job(
            cluster_name=cluster_name,
            print_logs=false,
            store_logs_in_s3=false,
            store_logs_on_cluster=false,
            job_name="testjob2",
            files=["data/iris.csv"],
            code_files=["envs/DataAnalysisProject/analysis.jl"],
            force_update_files=true,
        )

        # Destroy job
        destroy_job(job_id)
    end

end

max_stars_repo_name: banyan-team/banyan-julia

max_issues_repo_name: banyan-team/banyan-julia

max_forks_repo_name: banyan-team/banyan-julia


text:
module Godunov
export NumFlux
# Godunov flux:
function NumFlux(F,a::Float64,b::Float64)
    a<=b ? F.minf(a,b):  F.maxf(b,a)
    #ifelse(a<=b,F.minf(a,b),F.maxf(b,a))# same computing time
end
end

max_stars_repo_name: danielcort/benchmarks-python-julia-c

max_issues_repo_name: danielcort/benchmarks-python-julia-c

max_forks_repo_name: danielcort/benchmarks-python-julia-c


text:
module Variants

import Base: convert, show, isequal, hash, isless
export VariantException, Variant
export convert, lefttype, righttype
export isleft, isright, getleft, getright, getleft_null, getright_null, show
export isequal, hash, isless
export variant, lefts, rights, partition_variants

# Type definitions

immutable VariantException <: Exception end

# Idea:
# Define wrapper types Left{T} and Right{T},
# and the say typealias Variant{L,R} Union{Left{L}, Right{R}}

immutable Variant{L,R}
    isleft::Bool
    value::Union{L,R}

    function Variant(value::L, isleft::Type{Val{true}})
        new(true, value)
    end
    function Variant(value::R, isleft::Type{Val{false}})
        new(false, value)
    end
    #=
    function Variant(value::Union{L,R}, isleft::Bool)
        if !(isleft ? isa(value, L) : isa(value, R))
            throw(VariantException())
        end
        new(isleft, value)
    end
    function Variant(value::Union{L,R})
        isleft = isa(value, L)
        isright = isa(value, R)
        if isleft && isright
            throw(VariantException())
        end
        new(isleft, value)
    end
    =#
end

function convert{L,R}(::Type{Variant{L,R}}, value, isleft::Bool)
    if isleft
        Variant{L,R}(value::L, Val{true})
    else
        Variant{L,R}(value::R, Val{false})
    end
end

function convert{L,R}(::Type{Variant{L,R}}, value)
    isleft = isa(value, L)
    isright = isa(value, R)
    if isleft == isright
        throw(VariantException())
    end
    # Variant{L,R}(value, isleft)
    if isleft
        Variant{L,R}(value::L, Val{true})
    else
        Variant{L,R}(value::R, Val{false})
    end
end

convert{L,R}(::Type{Variant{L,R}}, x::Variant{L,R}) = x

lefttype{L,R}(::Type{Variant{L,R}}) = L
righttype{L,R}(::Type{Variant{L,R}}) = R

# Low-level accessors

isleft(x::Variant) = x.isleft
isright(x::Variant) = !x.isleft

getleft{L,R}(x::Variant{L,R}) = !x.isleft ? throw(VariantException()) : x.value::L
getright{L,R}(x::Variant{L,R}) = x.isleft ? throw(VariantException()) : x.value::R

getleft{L,R}(x::Variant{L,R}, y) = !x.isleft ? convert(L, y) : x.value::L
getright{L,R}(x::Variant{L,R}, y) = x.isleft ? convert(R, y) : x.value::R

getleft_null{L,R}(x::Variant{L,R}) = !x.isleft ? Nullable{L}() : Nullable{L}(x.value::L)
getright_null{L,R}(x::Variant{L,R}) = x.isleft ? Nullable{R}() : Nullable{R}(x.value::R)

# High-level accessors

function isequal{L,R}(x::Variant{L,R}, y::Variant{L,R})
    if isleft(x) != isleft(y)
        false
    elseif isleft(x)
        getleft(x) == getleft(y)
    else
        getright(x) == getright(y)
    end
end

const variant_hashseed_left = UInt(typemax(UInt) & 0xa30e411403dcb935)
const variant_hashseed_right = UInt(typemax(UInt) & 0x5fe656f0e4d6e72d)
function hash{L,R}(x::Variant{L,R}, h::UInt)
    if isleft(x)
        hash(getleft(x), h + variant_hashseed_left)
    else
        hash(getright(x), h + variant_hashseed_right)
    end
end

function isless{L,R}(x::Variant{L,R}, y::Variant{L,R})
    if isleft(x)
        if isleft(y)
            isless(getleft(x), getleft(y))
        else
            true
        end
    else
        if isleft(y)
            false
        else
            isless(getright(x), getright(y))
        end
    end
end

function show{L,R}(io::IO, x::Variant{L,R})
    print(io, "Variant{")
    show(io, L)
    print(io, ",")
    show(io, R)
    print(io, "}(", isleft(x) ? "left" : "right", ":")
    if x.isleft
        show(io, getleft(x))
    else
        show(io, getright(x))
    end
    print(io, ")")
end

# Higher order functions

variant(x::Variant) = isleft(x) ? getleft(x) : getright(x)
variant(f, g, x::Variant) = isleft(x) ? f(getleft(x)) : g(getright(x))

function lefts{L,R}(xs::Array{Variant{L,R}})
    ls = L[]
    for x in xs
        if isleft(x)
            push!(ls, getleft(x))
        end
    end
    ls
end

function rights{L,R}(xs::Array{Variant{L,R}})
    rs = R[]
    for x in xs
        if isright(x)
            push!(rs, getright(x))
        end
    end
    rs
end

function partition_variants{L,R}(xs::Array{Variant{L,R}})
    ls = L[]
    rs = R[]
    for x in xs
        if isleft(x)
            push!(ls, getleft(x))
        else
            push!(rs, getright(x))
        end
    end
    ls, rs
end

end # module


text:
# ---
# title: 443. String Compression
# id: problem443
# author: Tian Jun
# date: 2020-10-31
# difficulty: Medium
# categories: String
# link: <https://leetcode.com/problems/string-compression/description/>
# hidden: true
# ---
#
# Given an array of characters `chars`, compress it using the following
# algorithm:
#
# Begin with an empty string `s`. For each group of **consecutive repeating
# characters** in `chars`:
#
#   * If the group's length is 1, append the character to `s`.
#   * Otherwise, append the character followed by the group's length.
#
# The compressed string `s` **should not be returned separately** , but instead
# be stored  **in the input character array  `chars`**. Note that group lengths
# that are 10 or longer will be split into multiple characters in `chars`.
#
# After you are done **modifying the input array** , return _the new length of
# the array_.
#
#
#
# **Follow up:**
# Could you solve it using only `O(1)` extra space?
#
#
#
# **Example 1:**
#
#
#
#     Input: chars = ["a","a","b","b","c","c","c"]
#     Output: Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"]
#     Explanation:  The groups are "aa", "bb", and "ccc". This compresses to "a2b2c3".
#
#
# **Example 2:**
#
#
#
#     Input: chars = ["a"]
#     Output: Return 1, and the first character of the input array should be: ["a"]
#     Explanation:  The only group is "a", which remains uncompressed since it's a single character.
#
#
# **Example 3:**
#
#
#
#     Input: chars = ["a","b","b","b","b","b","b","b","b","b","b","b","b"]
#     Output: Return 4, and the first 4 characters of the input array should be: ["a","b","1","2"].
#     Explanation:  The groups are "a" and "bbbbbbbbbbbb". This compresses to "ab12".
#
# **Example 4:**
#
#
#
#     Input: chars = ["a","a","a","b","b","a","a"]
#     Output: Return 6, and the first 6 characters of the input array should be: ["a","3","b","2","a","2"].
#     Explanation:  The groups are "aaa", "bb", and "aa". This compresses to "a3b2a2". Note that each group is independent even if two groups have the same character.
#
#
#
#
# **Constraints:**
#
#   * `1 <= chars.length <= 2000`
#   * `chars[i]` is a lower-case English letter, upper-case English letter, digit, or symbol.
#
#
## @lc code=start
using LeetCode

## add your code here:
## @lc code=end


text:
using SparseArrays

export complete_graph_Ad, star_graph_Ad
"""
    complete_graph_Ad(N)

Returns a sparse adjacency matrix for the complete graph with `N` nodes.

```jldoctest
julia> Matrix(complete_graph_Ad(N))
3×3 Array{Float64,2}:
 0.0  1.0  1.0
 1.0  0.0  1.0
 1.0  1.0  0.0
```
"""
function complete_graph_Ad(N)
    return dropzeros(1. .- sparse(1.0I, N, N))
end;

"""
    star_graph_Ad(N)

Returns a sparse adjacency matrix for the complete graph with `N` nodes.

```jldoctest
julia> Matrix(star_graph_Ad(3))
3×3 Array{Float64,2}:
 0.0  1.0  1.0
 1.0  0.0  0.0
 1.0  0.0  0.0
```
"""
function star_graph_Ad(N)
    V = Array{Int64}(undef, 2N-2)
    U = Array{Int64}(undef, 2N-2)
    L = Array{Float64}(undef, 2N-2)

    for i=1:N-1
        V[i]=1
        U[i]=i+1
        L[i]=1.
    end

    for i=1:N-1
        V[i+N-1]=i+1
        U[i+N-1]=1
        L[i+N-1]=1.
    end

    return sparse(V,U,L)
end

"""
    discLapl(adj::SparseMatrixCSC)

Return the Laplacian matrix corresponding to the adjacency matrix `adj`.

```jldoctest
julia> Matrix(discLapl(star_graph_Ad(3)))
3×3 Array{Float64,2}:
  2.0  -1.0  -1.0
 -1.0   1.0   0.0
 -1.0   0.0   1.0
```
"""
function discLapl(adj::SparseMatrixCSC)

    temp = spzeros(maximum(adj.rowval), maximum(adj.rowval))

    for i=1:maximum(adj.rowval)
        temp[i,i]=adj.colptr[i+1]-adj.colptr[i]
        for j=adj.colptr[i]:(adj.colptr[i+1]-1)
            temp[adj.rowval[j],i]=-adj[adj.rowval[j],i]
        end
    end

    return temp
end

max_stars_repo_name: matteoacrossi/QuantumSpatialSearch

max_issues_repo_name: matteoacrossi/QuantumSpatialSearch

max_forks_repo_name: matteoacrossi/QuantumSpatialSearch


text:
import Pkg; Pkg.activate(".")
using Revise

import Tokenize
const TM = Tokenize
const TS = Tokenize.Tokens

using Caesar

#%%
env = Caesar.SchemeEnvironment()
Caesar.init_env!(env)
open("scheme\\ex03.scm", "r") do io
   code = read(io, String)
   @show pt = tokenize(code) |> parse
   Caesar.interp!(env, pt)
end


text:
refs = Array(RemoteRef, ec2_num_workers)
responses = Array(Int, ec2_num_workers)

println("Testing newly added workers")

tic()
for (i,p) in enumerate(workers())
    refs[i] = remotecall(p, myid)
end

@sync begin
    for i in 1:ec2_num_workers
        @async begin
            responses[i] = take!(refs[i])
        end
    end
end

println("responses:")
for r in responses
    print("$r ")
end
println()

println("Time taken : ", toq())

assert(responses[1] == 2)
assert(responses[ec2_num_workers] == ec2_num_workers+1)


text:
"""
    gen_ref_dirs(dimension, n_paritions)
Generates Das and Dennis's structured reference points. `dimension` could be
the number of objective functions in multi-objective functions.
"""
function gen_ref_dirs(dimension, n_paritions)
    return  gen_weights(dimension, n_paritions)
end

function gen_weights(a, b)
    nobj = a;
    H    = b;
    a    = zeros(nobj);
    d    = H;
    w    = [];
    produce_weight!(a, 1, d, H, nobj, w)
    return Array.(w)
end

function  produce_weight!(a, i, d, H, nobj, w)
    for k=0:d
        if i<nobj
            a[i] = k;
            d2   = d - k;
            produce_weight!(a, i+1, d2, H, nobj, w);
        else
            a[i] = d;
            push!(w, a/H)
            break;
        end
    end
end

"""
    ideal(points)

Computes the ideal point from a provided array of `Vector`s or a population or row vectors
in a `Matrix`.
"""
function ideal(points::Array{Vector{T}}) where T <: Real

    isempty(points) && isempty(points[1]) && return zeros(0)

    ideal = points[1]

    for point in points
        ideal = min.(ideal, point)
    end

    return ideal

end

"""
    nadir(points)

Computes the nadir point from a provided array of `Vector`s or a population or row vectors
in a `Matrix`.
"""
function nadir(points::Array{Vector{T}})  where T <: Real

    isempty(points) && isempty(points[1]) && return zeros(0)

    nadir = points[1]

    for point in points
        nadir = max.(nadir, point)
    end

    return nadir
end

function ideal(population::Array{xFgh_indiv})
    mask = sum_violations.(population) .== 0

    ideal(fval.(population[mask]))
end
ideal(A::Matrix) = ideal([A[i,:]  for i in 1:size(A,1)])

function nadir(population::Array{xFgh_indiv})
    mask = sum_violations.(population) .== 0

    nadir(fval.(population[mask]))
end

nadir(A::Matrix) = nadir([A[i,:]  for i in 1:size(A,1)])


text:
"""
we already converted source array to booleans now we know the number of false positives; false negatives and
min,max x,y,z of part of data where we have any intreasting maxresultPoints

Now we need to:
    -populate metadata
        -mark also whether the block is active, foll or neither - from both perspectives of both masks
        -we can set the min,max dims of data block
    -as we already loaded data from global memory - what is supposedly most expensive part - we can do the first dilatation step
    -we prepare rudamentary work plan for  next step

Toexperiment
    reducePaddingPlane   #to be experimented is it better to reduce to varyiong y or x

"""
module FirstHouseDorffPass
using CUDA, ..CUDAGpuUtils, Logging,StaticArrays

"""
prepare first pass of Housedorff kernel run
datablockDim - the edge length of cube describing the block of data we are working on  - defoult is 32 - which would produce blocks of size 32x32x32
"""
function executefirstHouseDorffPassKernel(datablockDim,metaData)

    threadsNum = (datablockDim,datablockDim)
    blocksNum = size(metaData)

end#executefirstHouseDorffPassKernel
"""

main kernel of muodule it will get 4 data arrays -   reducedGoldA,reducedSegmA,reducedGoldB,reducedSegmB
    we work on all simultaneously

    initializes work queue (invoked only in first pass)
    basically we need to add to the one dimensional queue all of the  active blocks we find in first pass- crerating basic queue that will be processed by normals passes
        -we will make one block to be responsible for one slice  - and we will run this without cooperative threads limitation ...
        -hence we will have double loop of all data blocks metadata  iterating over x and y dimension with z dimension constant
        -now every time when block is empty or full we will update its metadata
        -every time the block is active we will add it to the end of mainWorkQueeue - we will use mainQuesCounter for it
        -in the end of first pass or at the bigining of second we need to set  mainActiveCounterNow= mainQuesCounter

    reducedArrays =  [reducedSegmA,reducedGoldB,reducedGoldA,reducedSegmB]
        - list of 3 dimensional boolean arrays with main data that we will work on

    metaData - basic data about data blocks - stored in 3 dimensional array
    metadataDims - dimensions of metaData array
    resArrays = [resArrayA, resArrayB]- 3 dimensional array of size of reduced source array where entry will be in place where we had covered the voxel, and value will mark in which itwration
        - we have two result arrays separate for each pass
        - when we will cover some point  we need to report it in the resArray

    datablockDim - the edge length  describing the block of data we are working on  - defoult is 32 - which would produce blocks of size 32x32xzDim
        - we will have  the plane of threads of size 32x32 and in order to preserve memory coalescence we should have a warp have the  set of next x positions

    mainQuesCounter - counter that we will update atomically and will be usefull to populate the work queue
    mainWorkQueue - the list of the indicies of  data blocks in metadata with additional information is it referencing the goldpass or second one
"""
function firstHouseDorffPassKernel( reducedArrays
                                    ,metaData
                                    ,metadataDims::Tuple{UInt8,UInt8,UInt8}
                                    ,resArrays
                                    ,datablockDim
                                    ,mainQuesCounter
                                    ,mainWorkQueue )
    ############initializations of data
    resShmem,  isMaskFull, isMaskEmpty,locArr = memoryAllocations(datablockDim,zDim)
    #we iterate over metadata dimensions ...
    @unroll for xdim = UInt8(1):metaDatDims[1], ydim= UInt8(1):metaDatDims[2], ispassGoldd in [true, false]
        singleDataBlockPass(reducedArrays[ispassGoldd*2+1]
        ,reducedArrays[ispassGoldd*2+2]
        ,UInt16(1)
        ,((xdim-1)*32)+1
        ,((ydim-1)*32)+1
        ,((blockIdx().x -1)*32)+1
        ,isMaskFull
        ,isMaskEmpty
        ,resShmem
        ,locArr
        ,metaData
        ,metadataDims
        ,ispassGoldd
        ,xdim
        ,ydim
        ,blockIdx().x
        ,mainQuesCounter
        ,mainWorkQueue
        ,resArrays[ispassGoldd+1] )
  end#for
# in this spot we should have already filled work queue, set information which blocks are full or empty, and got throught first dilatation step

end #FirstHouseDorffPassKernel

"""
collects multiple functions that will be invoked over a single data blocks
analyzedArr - array that we dilatate
refAray - array we are comparing with
iterationNumber - in first pass it is 1
blockBeginingX,blockBeginingY,blockBeginingZ - coordinates where our block is begining - will be used as offset by our threads
isMaskFull,isMaskEmpty - needed for establishing state  of a current block after processing
resShmem- shared memory
locArr - thread local array with values loaded from global memory
metaData - 3 dim array with metadata of data blocks
metadataDims - dimensions of metadataDims
currMatadataBlockX,currMatadataBlockY, currMatadataBlockZ - cartesian coordinates of current block in metadaa!!!
mainQuesCounter - counter that we will update atomically and will be usefull to populate the work queue
mainWorkQueue - the list of the indicies of  data blocks in metadata with additional information is it referencing the goldpass or second one
"""
function singleDataBlockPass(analyzedArr
                ,refAray
                ,iterationNumber
                ,blockBeginingX
                ,blockBeginingY
                ,blockBeginingZ
                ,isMaskFull
                ,isMaskEmpty
                ,resShmem
                ,locArr
                ,metaData
                ,metadataDims::Tuple{UInt8,UInt8,UInt8}
                ,isPassGold::Bool
                ,currMatadataBlockX::UInt8
                ,currMatadataBlockY::UInt8
                ,currMatadataBlockZ::UInt8
                ,mainQuesCounter
                ,mainWorkQueue
                ,resArray )
            ############### execution
            executeDataIterFirstPass(analyzedArr, refAray,iterationNumber,blockBeginingX,blockBeginingY,blockBeginingZ,isMaskFull,isMaskEmpty,resShmem,locArr,resArray,mainQuesCounter)
            #for futher processing we need to have space in main shmem
            clearMainShmem(shmem)
            #now we need to deal with padding in shmem res
            processAllPaddingPlanes(x,y,z,shmem,currBlockX,currBlockY,currBlockZ,sourceArray,referenceArray,resArray,metaData,metadataDims,isPassGold,locArr)
            # now let's check weather block is eligible for futher processing - for this we need sums ...
            isActiveForFirstPass(isMaskFull, isMaskEmpty,resShmem,currMatadataBlockX,currMatadataBlockY,currMatadataBlockZ,isPassGold,metaData,mainQuesCounter,mainWorkQueue)
end#singleDataBlockPass

end #FirstHouseDorffPass


text:
# Sun 30 Dec 2012 01:22:44 PM EST
#
# NeHe Tut 17 - 2D texture font
#
# Q - quit
# L - turn lights on/off
# F - change texture filter (linear, nearest, mipmap)
# PageUp/Down - move camera closer/further away
# Up/Down - increase/decrease x-rotation speed
# Left/Right - increase/decrease y-rotation speed

# TODO: This example runs, but it produces a very glitchy output.

# load necessary GL/SDL routines

using OpenGL
@OpenGL.version "1.0"
@OpenGL.load
using SDL

# initialize variables

bpp                = 16
wintitle           = "NeHe Tut 17"
icontitle          = "NeHe Tut 17"
width              = 640
height             = 480

T0                 = 0
Frames             = 0

cnt1               = 0
cnt2               = 0

keystate_checked   = false
lastkeycheckTime   = 0
key_repeatinterval = 75 #ms

# open SDL window with an OpenGL context

SDL_Init(SDL_INIT_VIDEO)
#videoInfo = SDL_GetVideoInfo()
videoFlags = (SDL_OPENGL | SDL_GL_DOUBLEBUFFER | SDL_HWPALETTE | SDL_RESIZABLE)
#if videoInfo.hw_available
    videoFlags = (videoFlags | SDL_HWSURFACE)
#else
    #videoFlags = (videoFlags | SDL_SWSURFACE)
#end
#if videoInfo.blit_hw
    videoFlags = (videoFlags | SDL_HWACCEL)
#end
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1)
SDL_SetVideoMode(width, height, bpp, videoFlags)
SDL_WM_SetCaption(wintitle, icontitle)

glViewport(0, 0, width, height)
glClearColor(0.0, 0.0, 0.0, 0.0)
glClearDepth(1.0)
glDepthFunc(GL_LEQUAL)
glShadeModel(GL_SMOOTH)
glEnable(GL_DEPTH_TEST)

glMatrixMode(GL_PROJECTION)
glLoadIdentity()

gluPerspective(45.0,width/height,0.1,100.0)

glMatrixMode(GL_MODELVIEW)

### auxiliary functions

function glPrint(x::Integer, y::Integer, string::String, set::Integer)
    if set > 1
        set = 1
    end

    glBindTexture(GL_TEXTURE_2D, tex[1])
    glDisable(GL_DEPTH_TEST)

    glMatrixMode(GL_PROJECTION)
    glpushmatrix()

    glLoadIdentity()
    glOrtho(0, 640, 0, 480, -1, 1)

    glMatrixMode(GL_MODELVIEW)
    glPushMatrix()
    glLoadIdentity()

    glTranslate(x, y, 0)
    glListBase(uint32(base-32+(128*set)))
    glCallLists(strlen(string), GL_BYTE, string)

    glMatrixMode(GL_PROJECTION)
    glPopMatrix()

    glMatrixMode(GL_MODELVIEW)
    glPopMatrix()
end

### end of auxiliary functions

# load textures from images

tex       = Array(Uint32,2) # generating 2 textures

imgFont, wFont, hFont = glimread(expanduser("~/.julia/SDL/Examples/NeHe/tut17/font.bmp"))

imgBumps, wBumps, hBumps = glimread(expanduser("~/.julia/SDL/Examples/NeHe/tut17/bumps.bmp"))

glGenTextures(2,tex)
glBindTexture(GL_TEXTURE_2D,tex[1])
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
glTexImage2D(GL_TEXTURE_2D, 0, 3, wFont, hFont, 0, GL_RGB, GL_UNSIGNED_BYTE, imgFont)

glBindTexture(GL_TEXTURE_2D,tex[2])
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
glTexImage2D(GL_TEXTURE_2D, 0, 3, wBumps, hBumps, 0, GL_RGB, GL_UNSIGNED_BYTE, imgBumps)

# enable texture mapping & blending

glEnable(GL_TEXTURE_2D)
glBlendFunc(GL_SRC_ALPHA, GL_ONE)

# build the fonts

base = glGenLists(256)
glBindTexture(GL_TEXTURE_2D, tex[1])

for loop = 1:256
    cx = (loop%16)/16
    cy = (loop/16)/16

    glNewList(uint32(base+(loop-1)), GL_COMPILE)
        glBegin(GL_QUADS)
            glTexCoord(cx, 1-cy-0.0625)
            glVertex(0, 0)
            glTexCoord(cx+0.0625, 1-cy-0.0625)
            glVertex(16, 0)
            glTexCoord(cx+0.0625, 1-cy)
            glVertex(16, 16)
            glTexCoord(cx, 1-cy)
            glVertex(0, 16)
        glEnd()
        glTranslate(10, 0, 0)
    glEndList()
end

# main drawing loop

while true
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
    glLoadIdentity()

    glBindTexture(GL_TEXTURE_2D,tex[2])

    glTranslate(0.0,0.0,-5.0)
    glRotate(45.0, 0.0, 0.0, 1.0)
    glRotate(cnt1*30.0, 1.0, 1.0, 0.0)

    glDisable(GL_BLEND)
    glColor(1.0, 1.0, 1.0)

    glBegin(GL_QUADS)
        glTexCoord(0.0, 0.0)
        glVertex(-1.0, 1.0)
        glTexCoord(1.0, 0.0)
        glVertex(1.0, 1.0)
        glTexCoord(1.0, 1.0)
        glVertex(1.0, -1.0)
        glTexCoord(0.0, 1.0)
        glVertex(-1.0, -1.0)
    glEnd()

    glRotate(90.0, 1.0, 1.0, 0.0)
    glBegin(GL_QUADS)
        glTexCoord(0.0, 0.0)
        glVertex(-1.0, 1.0)
        glTexCoord(1.0, 0.0)
        glVertex(1.0, 1.0)
        glTexCoord(1.0, 1.0)
        glVertex(1.0, -1.0)
        glTexCoord(0.0, 1.0)
        glVertex(-1.0, -1.0)
    glEnd()

    glEnable(GL_BLEND)
    glLoadIdentity()

    glColor(1.0cos(cnt1), 1.0sin(cnt2), 1.0-0.5cos(cnt1+cnt2))
    glPrint(int(280+250cos(cnt1)), int(235+200sin(cnt2)), "NeHe", 0)
    glColor(1.0sin(cnt2), 1.0-0.5cos(cnt1+cnt2), 1.0cos(cnt1))
    glPrint(int(280+230cos(cnt2)), int(235+200sin(cnt1)), "OpenGL", 1)

    glColor(0.0, 0.0, 1.0)
    glPrint(int(240+200cos((cnt2+cnt1)/5)), 2, "JuliaLang", 0)
    glColor(1.0, 1.0, 1.0)
    glPrint(int(242+200cos((cnt2+cnt1)/5)), 2, "JuliaLang", 0)

    cnt1 +=0.01
    cnt2 +=0.0081

    SDL_GL_SwapBuffers()

    SDL_PumpEvents()
    if SDL_GetTicks() - lastkeycheckTime >= key_repeatinterval
        keystate         = SDL_GetKeyState()
        keystate_checked = true
        lastkeycheckTime = SDL_GetTicks()
    end

    # Sampling rates for event processing are so fast that a single key press
    # lasts through several iterations of this loop.  This means that one press
    # can be seen as 50 or more presses by the SDL event system.  To correct
    # for this, we only check keypresses every 75ms.

    if keystate_checked == true
        if keystate[SDLK_q] == true
            glDeleteLists(base,256)
            glDeleteTextures(2,tex)
            break
        end
        keystate_checked = false
    end
end


text:
# jarque_bera.jl
# Jarque-Bera goodness-of-fit test
#
# Copyright (C) 2017   Benjamin Born
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

export JarqueBeraTest

struct JarqueBeraTest <: HypothesisTest
    n::Int         # number of observations
    JB::Float64    # test statistic
    skew::Float64  # skewness
    kurt::Float64  # excess kurtosis
end

"""
    JarqueBeraTest(y::AbstractVector)

Compute the Jarque-Bera statistic to test the null hypothesis that a real-valued vector `y`
is normally distributed.

Note that the approximation by the Chi-squared distribution does not work well and the
speed of convergence is slow. In small samples, the test tends to be over-sized for
nominal levels up to about 3% and under-sized for larger nominal levels (Mantalos, 2010).

# References

  * Panagiotis Mantalos, 2011, "The three different measures of the sample skewness and
    kurtosis and the effects to the Jarque-Bera test for normality", International Journal
    of Computational Economics and Econometrics, Vol. 2, No. 1,
    [link](http://dx.doi.org/10.1504/IJCEE.2011.040576).

# External links

  * [Jarque-Bera test on Wikipedia](https://en.wikipedia.org/wiki/Jarque–Bera_test)
"""
function JarqueBeraTest(y::AbstractVector{T}) where T<:Real
    n = length(y)
    M = Base.promote_op(/, T, typeof(n))
    m1r = m2r = m3r = m4r = zero(M)
    @inbounds for yi in y # compute raw moments
        m1r += yi / n
        m2r += yi^2 / n
        m3r += yi^3 / n
        m4r += yi^4 / n
    end
    # compute central moments (http://mathworld.wolfram.com/CentralMoment.html)
    m2 = -m1r^2 + m2r
    m3 = 2 * m1r^3 - 3 * m1r * m2r + m3r
    m4 = -3 * m1r^4 + 6 * m1r^2 * m2r - 4 * m1r * m3r + m4r

    skew = m3 / m2^(3/2)
    kurt = m4 / m2^2

    stat = n * skew^2 / 6 + n * (kurt - 3)^2 / 24
    JarqueBeraTest(n, stat, skew, kurt)
end

testname(::JarqueBeraTest) = "Jarque-Bera normality test"
population_param_of_interest(x::JarqueBeraTest) =
    ("skewness and kurtosis", "0 and 3", "$(x.skew) and $(x.kurt)")
default_tail(test::JarqueBeraTest) = :right

function show_params(io::IO, x::JarqueBeraTest, ident)
    println(io, ident, "number of observations:         ", x.n)
    println(io, ident, "JB statistic:                   ", x.JB)
end

pvalue(x::JarqueBeraTest) = pvalue(Chisq(2), x.JB; tail=:right)


text:
module XiCor

using Random

export xicor

"""
    xicor(X, Y[, break_ties_randomly=false[, rng=nothing]])

Computes the correlation ξ between X and Y.

Unlike most coefficients of correlation, ξ ranges from -0.5 to 1.

If there are duplicate values in X, then ties are
broken based on the order in which they are observed.
If the order of X is not random, then you should
set `break_ties_randomly` to `true` to avoid a biased
estimate. You can use the `rng` parameter to
deterministically break ties.

See _A new coefficient of correlation_ by Chatterjee.

[arXiv:1909.10140 [math.ST]](https://arxiv.org/abs/1909.10140)

# Examples
```julia-repl
julia> ξ = xicor(1:100, 1:100)
0.9702970297029703
julia> x = trunc.((1:100) ./ 10);  # create x with lots of duplicates
julia> y = rand(MersenneTwister(0), 100);
julia> ξ = xicor(x, y, true, MersenneTwister(0))
-0.01830183018301823
julia> ξ = xicor(x, y, true, MersenneTwister(42))
0.004500450045004545
```
"""
function xicor(X, Y, break_ties_randomly=false, rng=nothing)
    if break_ties_randomly
        if !isnothing(rng)
            index = randperm(rng, length(X))
        else
            index = randperm(length(X))
        end
        X = X[index]
        Y = Y[index]
    end
    n = length(X)
    Y = Y[sortperm(X)]  # how should offset arrays be handled?
    sorter = sortperm(Y)
    R = zeros(Int, n)  # R[i] is the number of j such that Y[j] ≤ Y[i]
    L = zeros(Int, n)  # L[i] is the number of j such that Y[j] ≥ Y[i]

    i = 1
    while i <= n
        curr = Y[sorter[i]]
        counter = 1
        i += 1  # look ahead for repeated Y values
        while i <= n && Y[sorter[i]] == curr
            counter += 1
            i += 1
        end
        i -= 1
        for j = i-counter+1:i  # fill in R and L values wherever Y == curr
            R[sorter[j]] = i
            L[sorter[j]] = (n-i) + counter
        end
        i += 1
    end

    1 - n * sum(abs.(diff(R))) / (2 * sum(L .* (n .- L)))
end

end # module


text:
@inline choice_gradients(trace::SwitchTrace{T}, selection::Selection, retval_grad) where T = choice_gradients(getfield(trace, :branch), selection, retval_grad)
@inline accumulate_param_gradients!(trace::SwitchTrace{T}, retval_grad, scale_factor = 1.) where {T} = accumulate_param_gradients!(getfield(trace, :branch), retval_grad, scale_factor)

max_stars_repo_name: georgematheos/Gen

max_issues_repo_name: georgematheos/Gen

max_forks_repo_name: georgematheos/Gen


text:
#define functions to calculate the energy with Monte Carlo sampling

#calculate scalar product S_i \cdot S_j of a bond [i,j]
function sp_bond(RBMPar::RBM_par,Lt::Array{Complex{Float64},1},state::Array{Int64,1},bond::Array{Int64,1})

   if state[bond[1]] == state[bond[2]]
        return 1.0
   else return -1.0 - 2.0*ExpLog(RBMPar,Lt,state,bond)
   end

end

#Finds the non-zero matrix elements of the hamiltonian on the given state
#i.e. all the state' such that <state'|H|state> = conn(state') \neq 0
#state' is encoded as the sequence of spin flips to be performed on state
function Pushconn(RBMPar::RBM_par,Lt::Array{Complex{Float64},1},state::Array{Int64,1})

    #initialize array of S_i \cdot S_j between neighbouring spin along x
    en_x = Complex{Float64}[]

    #initialize array of S_i \cdot S_j between neighbouring spin along y
    en_y = Complex{Float64}[]

    #fill en_x and en_y with S_i \cdot S_j on all corresponding bonds
    for i=1:length(bonds_x)
    @views    push!(en_x,sp_bond(RBMPar,Lt,state,bonds_x[i]))
    end

    for i=1:length(bonds_y)
    @views    push!(en_y,sp_bond(RBMPar,Lt,state,bonds_y[i]))
    end

    return en_x, en_y
end

#Measuring the value of the local energy on the current state
#and fill it in the given vector energy
function Energy(RBMPar::RBM_par,Lt::Array{Complex{Float64},1},state::Array{Int64,1},energy::Array{Complex{Float64}},J::Array{Float64,1})

    #calculate S_i \cdot S_j for bonds along x and y
    sp_x, sp_y = Pushconn(RBMPar,Lt,state)

    #calculate the energy by multiplying S_i \cdot S_j with corresponding J
    @views en = J[1]*sum(sp_x) + J[2]*sum(sp_y)

    push!(energy,en)

end;

max_stars_repo_name: GiamFbn/MyULTRAFAST

max_issues_repo_name: GiamFbn/MyULTRAFAST

max_forks_repo_name: GiamFbn/MyULTRAFAST


text:
#needs testing!!!!

function nn_loop_if!(r,  nn_arr,  i::Int,  j::Int)
    rb = U_sa * r
    s = @. Integer(round(rb/g))
    sint = Integer(s[1] * 9 + s[2] * 3 + s[3])
    if sint == 4
        nn_arr[i,  1] = j
    elseif sint == 2
        nn_arr[i,  2] = j
    elseif sint == 10
        nn_arr[i,  3] = j
    elseif sint == -8
        nn_arr[i,  4] = j
    elseif sint == 12
        nn_arr[i,  5] = j
    elseif sint == 6
        nn_arr[i,  6] = j
    elseif sint == -4
        nn_arr[i,  7] = j
    elseif sint == -2
        nn_arr[i,  8] = j
    elseif sint == -10
        nn_arr[i,  9] = j
    elseif sint == 8
        nn_arr[i,  10] = j
    elseif sint == -12
        nn_arr[i,  11] = j
    elseif sint == -6
        nn_arr[i,  12] = j
    end
    return nn_arr
end

function nn_loop!(x::float_array,  nn_arr::Array{Int64, 2})
    for i in 1:N
        for j in 1:N
            temp = (x[j+2,  :] - x[i+2,  :])./cell
            temp = temp .- floor.(temp .+ 1.0/2)
            r = temp.*cell
            rmi = floor(sum(r.*r)*10000.0)/10000.0
            if rmi <= (g*1.01)^2
                nn_arr = nn_loop_if!(r,  nn_arr,  i,  j)
            end
        end
    end
end

function nn_lattice(x)
    nn_arr = zeros(Int64, N+2, 12)
    nn_loop!(x, nn_arr)
    return nn_arr
end

hmm= nn_lattice(s.x)


text:
# https://adventofcode.com/2020/day/9

input = read("2020/data/day_9.txt", String)

test_input = """
35
20
15
25
47
40
62
55
65
95
102
117
150
182
127
219
299
277
309
576
"""

function part_1(input, preamble)
    numbers = parse.(Int, split(strip(input), "\n"))
    for idx in (preamble + 1):length(numbers)

        sums = [i + j for (i, j) in combinations(numbers[idx - preamble:idx - 1], 2) if i != j]
        if numbers[idx] ∉ sums
            return numbers[idx]
        end
    end
end
@assert part_1(test_input, 5) == 127
@info part_1(input, 25)

function part_2(input, preamble)
    invalid_number = part_1(input, preamble)
    numbers = parse.(Int, split(strip(input), "\n"))
    for i in 1:length(numbers)
        for j in (i + 1):length(numbers)
            total = sum(numbers[i:j])
            if total == invalid_number
                return maximum(numbers[i:j]) + minimum(numbers[i:j])
            # avoid continuing inner loop if you know sum is too high anyway
            elseif total > invalid_number
                break
            end
        end
    end
end
@assert part_2(test_input, 5) == 62
@info part_2(input, 25)

max_stars_repo_name: RensDimmendaal/advent-of-code-julia

max_issues_repo_name: RensDimmendaal/advent-of-code-julia

max_forks_repo_name: RensDimmendaal/advent-of-code-julia


text:
module LibA
end

module LibB
	export varB
	varB = 42
end

module LibC
	export varC, funcC

	varC = "London"
	function funcC()
		# code
	end

end

module LibD
	export funcD
	function funcD()
		# code
	end
end

module LibE
end

max_stars_repo_path: Module 1/Chapter06/modules_ext.jl

max_issues_repo_path: Module 1/Chapter06/modules_ext.jl

max_forks_repo_path: Module 1/Chapter06/modules_ext.jl


text:
# FWI on the 2D Overthrust model using spectral projected gradient descent
# Author: mlouboutin3@gatech.edu
# Date: February 2021
#
using Distributed
@everywhere using DrWatson
@everywhere @quickactivate :TimeProbeSeismic

# Load starting model
~isfile(datadir("models", "overthrust_model.h5")) && run(`curl -L ftp://slim.gatech.edu/data/SoftwareRelease/WaveformInversion.jl/2DFWI/overthrust_model_2D.h5 --create-dirs -o $(datadir("models", "overthrust_model.h5"))`)
n, d, o, m0, m = h5read(datadir("models", "overthrust_model.h5"), "n", "d", "o", "m0", "m")
model0 = Model((n[1], n[2]), (d[1], d[2]), (o[1], o[2]), m0)

# Bound constraints
v0 = sqrt.(1f0 ./ model0.m)
vmin = ones(Float32,model0.n) .* 1.3f0
vmax = ones(Float32,model0.n) .* 6.5f0
vmin[:, 1:21] .= v0[:, 1:21]   # keep water column fixed
vmax[:, 1:21] .= v0[:, 1:21]

# Slowness squared [s^2/km^2]
mmin = vec((1f0 ./ vmax).^2)
mmax = vec((1f0 ./ vmin).^2)

# Load data and create data vector
~isfile(datadir("data", "overthrust_2D.segy")) && run(`curl -L ftp://slim.gatech.edu/data/SoftwareRelease/WaveformInversion.jl/2DFWI/overthrust_2D.segy --create-dirs -o $(datadir("data", "overthrust_2D.segy"))`)

block = segy_read(datadir("data", "overthrust_2D.segy"))
d_obs = judiVector(block)

# Set up wavelet and source vector
src_geometry = Geometry(block; key = "source", segy_depth_key = "SourceDepth")
wavelet = ricker_wavelet(src_geometry.t[1], src_geometry.dt[1], 0.008f0) # 8 Hz wavelet
q = judiVector(src_geometry, wavelet)
q_dist = generate_distribution(q)

########################################### FWI ####################################################

# Optimization parameters
fevals = 20
batchsize = 20
fvals = []
g_const = 0
frequencies = Array{Any}(undef, batchsize)

# Objective function for library
function objective_function(x, ps; dft=false)
    Base.flush(stdout)
    model0.m .= x;

    # select batch
    idx = randperm(d_obs.nsrc)[1:batchsize]
    # dft mode
    if dft
        for k=1:batchsize
            frequencies[k] = select_frequencies(q_dist; fmin=0.003, fmax=0.02, nf=ps)
        end
        opt = Options(frequencies=frequencies)
        f, g = JUDI.fwi_objective(model0, q[idx], d_obs[idx]; options=opt)
    elseif isnothing(ps)
        f, g = JUDI.fwi_objective(model0, q[idx], d_obs[idx])
    else
        f, g = fwi_objective(model0, q[idx], d_obs[idx], ps)
    end
    g[:, 1:19] .= 0f0
    g_const == 0 && global g_const = 1 / norm(g, Inf)
    return f, vec(g.data.*g_const)   # normalize gradient for line search
end

# Bound projection
ProjBound(x) = median([mmin x mmax], dims=2)[1:end]

# FWI with SPG
options = spg_options(verbose = 3, maxIter = fevals, memory = 3, iniStep = 1f0)
g_const = 0
sol = spg(x->objective_function(x, nothing), vec(m0), ProjBound, options)

# Save results
# wsave
wsave(datadir("fwi_overthrust_basic", "fwi_std.bson"), typedict(sol))

# FWI with probing
ps = 32
global g_const = 0
sol = spg(x->objective_function(x, ps), vec(m0), ProjBound, options)

# Save results
# wsave
wsave(datadir("fwi_overthrust_basic", "fwi_ps$(ps).bson"), typedict(sol))

max_stars_repo_name: slimgroup/TimeProbeSeismic

max_issues_repo_name: slimgroup/TimeProbeSeismic

max_forks_repo_name: slimgroup/TimeProbeSeismic


text:
function loadCFLP(instance::Symbol)
    file_name = joinpath(data_path, string(instance) * ".zip")
    if !isfile(file_name)
        println("File $(string(instance)) not found!")
        return nothing
    end

    name = splitext(basename(file_name))[1]
    file = ZipFile.Reader(file_name)
    values = parse.(Float64, split(read(file.files[1], String)))

    return load(values, name)
end

function loadCFLP(file_name::String)
    if !isfile(file_name)
        println("File $file_name not found!")
        return nothing
    end

    name = splitext(basename(file_name))[1]
    values = parse.(Float64, split(read(file_name, String)))

    return load(values, name)
end

function load(values::Array{Float64}, name::String)
    n_facilities = convert(Int64, values[1])
    n_customers = convert(Int64, values[2])

    counter = 3

    capacities = convert.(Int64, values[counter:2:counter + 2 * n_facilities - 1])
    fixed_costs = values[counter + 1:2:counter + 2 * n_facilities - 1]

    counter += 2 * n_facilities

    customers = CFLPCustomer[]
    for j in 1:n_customers
        push!(customers, CFLPCustomer(j, convert(Int64, values[counter]), values[counter + 1:counter + n_facilities]))
        counter += n_facilities + 1
    end

    facilities = [ CFLPFacility(i, capacities[i], fixed_costs[i], [ c.costs[i] for c in customers ]) for i in 1:n_facilities ]

    return CFLPData(name, facilities, customers, -Inf, Inf)
end


text:
using Printf

"""
    cinta()

Genera el cronograma de ajustes de velocidad
de la cinta.

Toma los valores de velocidad e inclinación
registrados en Notas.txt para cada programa de la
cinta y genera el cronograma de ajustes a realizar
en base a los objetivos establecidos como
base (velocidad en Km/h para la inclinación 3) y
var (variación en Km/h a decrementar por cada
unidad de inclinación que se incrementa a partir
de 3).

Ejemplo del archivo Notas.txt:
09/08/2020 06:32 cinta ruta 8 303
09/08/2020 06:36 cinta 805
09/08/2020 06:40 cinta 604
"""
function cinta()
	open("datos_cinta.txt") do f
		base = 10.5
		var = .2
		step = 0
		ruta = 0
		cab = r"cinta ruta [0-9]+ [0-9]+$"
		det = r"cinta [0-9]+$"
		ref = 3
		button = 9
		up = Char(0xFE3D)
		down = Char(0xFE3E)
		eq = Char(0x1d117)
		dont_touch = Char(0xa555)
		println("Ruta\tInc\tMin\tVel ofrecida\t\tBotón\tSubir o bajar\tVel")
		for l in eachline(f)
			if occursin(cab, l)
				step = 1
				m = match(cab, l).match
				ruta, vel_inc = parse(Int, split(m)[3]), parse(Int, split(m)[4])
				vel = Int(trunc(vel_inc / 100))
				inc = vel_inc % 100
				new_vel = base + (ref - inc) * var
				button = abs(new_vel - 9) < abs(new_vel - 12) ? 9 : 12
				closest = abs(new_vel - vel) < abs(new_vel - button) ? vel : button
				@printf("%2d\t%2d\t%2d:\t%2d\t→\t%2s\t%s\t%4.1f\n", ruta, inc, 43 - 4step, vel, vel == closest ? dont_touch : button, new_vel == closest ? eq : new_vel > closest ? up : down, new_vel)
				step += 1
			elseif occursin(det, l)
				m = match(det, l).match
				vel_inc = parse(Int, split(m)[2])
				vel = Int(trunc(vel_inc / 100))
				inc = vel_inc % 100
				new_vel = base + (ref - inc) * var
				button = abs(new_vel - 9) < abs(new_vel - 12) ? 9 : 12
				closest = abs(new_vel - vel) < abs(new_vel - button) ? vel : button
				@printf("%2d\t%2d\t%2d:\t%2d\t→\t%2s\t%s\t%4.1f\n", ruta, inc, 43 - 4step, vel, vel == closest ? dont_touch : button, new_vel == closest ? eq : new_vel > closest ? up : down, new_vel)
				step += 1
			end
		end
	end
end

cinta()

max_stars_repo_name: AndresParraSilva/julia-start

max_issues_repo_name: AndresParraSilva/julia-start

max_forks_repo_name: AndresParraSilva/julia-start


text:
# This file is a part of TypeDBClient.  License is MIT: https://github.com/Humans-of-Julia/TypeDBClient.jl/blob/main/LICENSE

#
# package typedb.client.api.concept.type;
#
# import typedb.client.api.TypeDBTransaction;
# import typedb.client.api.concept.Concept;
# import typedb.client.common.Label;
#
# import javax.annotation.CheckReturnValue;
# import javax.annotation.Nullable;
# import java.util.stream.Stream;
#
# public interface Type extends Concept {
#
#     @CheckReturnValue
#     Label getLabel();
#
#     @CheckReturnValue
#     boolean isRoot();
#
#     @Override
#     default boolean isType() {
#         return true;
#     }
#
#     @Override
#     Remote asRemote(TypeDBTransaction transaction);
#
#     interface Remote extends Type, Concept.Remote {
#
#         void setLabel(String label);
#
#         @CheckReturnValue
#         boolean isAbstract();
#
#         @Nullable
#         @CheckReturnValue
#         Type getSupertype();
#
#         @CheckReturnValue
#         Stream<? extends Type> getSupertypes();
#
#         @CheckReturnValue
#         Stream<? extends Type> getSubtypes();
#     }
# }


text:
function checknode!(log::AbstractVector, node::AbstractODMNode, type::ODMNodeType)
end

function checknode!(log::AbstractVector, node::AbstractODMNode, type::ODMNodeType{:ODM})
    ks = Set([:Description, :FileType, :Granularity, :Archival, :FileOID, :CreationDateTime, :PriorFileOID, :AsOfDateTime, :ODMVersion, :Originator, :SourceSystem, :SourceSystemVersion, :ID])
    for k in keys(node.attr)
        k in ks || push!(log, "$(name(node)): Unknown attribute ($(k))")
    end
    if :FileType in keys(node.attr)
        attribute(node, :FileType) in FILETYPE || push!(log, "$(name(node)): Wrong FileType")
        #other check
    else
        push!(log, "$(name(node)): No FileType attribute")
    end
    if :Granularity in keys(node.attr)
        attribute(node, :Granularity) in GRANULARITY || push!(log, "$(name(node)): Wrong Granularity")
    end
    if :Archival in keys(node.attr)
        attribute(node, :Archival) in ARCHIVAL || push!(log, "$(name(node)): Wrong Archival")
        attribute(node, :FileType) == "Transactional" || push!(log, "$(name(node)): Archival is $(attribute(node, "Archival")), but FileType not Transactional")
    end
    if :ODMVersion in keys(node.attr)
        attribute(node, :ODMVersion) in ODMVERSION || push!(log, "$(name(node)): Wrong ODMVersion")
    end
    if :FileOID ∉ keys(node.attr)
        push!(log, "$(name(node)): No FileOID")
    end
    if :CreationDateTime ∉ keys(node.attr)
        push!(log, "$(name(node)): No CreationDateTime")
    else
        #datetime
    end
    if :AsOfDateTime in keys(node.attr)
        #datetime
    end
    for i in node.el
        if name(i) ∉ Set([:Study, :AdminData, :ReferenceData, :ClinicalData, :Association, Symbol("ds:Signature")])
            push!(log, "$(name(node)): Unexpected node ($(name(i))) in body")
        end
    end
end

function checknode!(log::AbstractVector, node::AbstractODMNode, type::ODMNodeType{:Study})
    ks = Set([:OID])
    for k in keys(node.attr)
        k in ks || push!(log, "$(name(node)) ($(attribute(node, :OID))): Unknown attribute ($(k))")
    end
    if :OID ∉ keys(node.attr)
        push!(log, "$(name(node)): No OID")
    end
    gvn = 0
    bdn = 0
    for i in node.el
        if name(i) ∉ Set([:GlobalVariables, :BasicDefinitions, :MetaDataVersion])
            push!(log, "$(name(node)) ($(attribute(node, :OID))): Unexpected node ($(name(i))) in body")
        end
        name(i) == :GlobalVariables &&  (gvn += 1)
        name(i) == :BasicDefinitions &&  (bdn += 1)
    end
    gvn == 1 || push!(log, "$(name(node)) ($(attribute(node, :OID))): GlobalVariables not 1 ($gvn)")
    bdn <= 1 || push!(log, "$(name(node)) ($(attribute(node, :OID))): BasicDefinitions more than 1 ($bdn)")
end

function checknode!(log::AbstractVector, node::AbstractODMNode, type::ODMNodeType{:GlobalVariables})
    length(node.attr) == 0 || push!(log, "$(name(node)): Unknown attribute(s) - $(keys(node.attr))")
    snn = 0
    sdn = 0
    pnn = 0
    for i in node.el
        if name(i) ∉ Set([:StudyName, :StudyDescription, :ProtocolName])
            push!(log, "$(name(node)): Unexpected node ($(name(i))) in body")
        end
        name(i) == :StudyName &&  (snn += 1)
        name(i) == :StudyDescription &&  (sdn += 1)
        name(i) == :ProtocolName &&  (pnn += 1)
    end
    snn == 1 || push!(log, "$(name(node)): StudyName not 1 ($snn)")
    sdn == 1 || push!(log, "$(name(node)): StudyDescription not 1 ($sdn)")
    pnn == 1 || push!(log, "$(name(node)): ProtocolName not 1 ($pnn)")
end

function checknode!(log::AbstractVector, node::AbstractODMNode, type::ODMNodeType{:StudyName})
    length(node.attr) == 0 || push!(log, "$(name(node)): Unknown attribute(s) - $(keys(node.attr))")
end

function checknode!(log::AbstractVector, node::AbstractODMNode, type::ODMNodeType{:StudyDescription})
    length(node.attr) == 0 || push!(log, "$(name(node)): Unknown attribute(s) - $(keys(node.attr))")
end

function checknode!(log::AbstractVector, node::AbstractODMNode, type::ODMNodeType{:ProtocolName})
    length(node.attr) == 0 || push!(log, "$(name(node)): Unknown attribute(s) - $(keys(node.attr))")
end

function checknode!(log::AbstractVector, node::AbstractODMNode, type::ODMNodeType{:BasicDefinitions})
    length(node.attr) == 0 || push!(log, "$(name(node)): Unknown attribute(s) - $(keys(node.attr))")
end
function checknode!(log::AbstractVector, node::AbstractODMNode, type::ODMNodeType{:MeasurementUnit})
    ks = Set([:OID, :Name])
    for k in keys(node.attr)
        k in ks || push!(log, "$(name(node)): Unknown attribute ($(k))")
    end
    if :OID in keys(node.attr)
        #other check
    else
        push!(log, "$(name(node)): No OID attribute")
    end
    if :Name in keys(node.attr)
        #other check
    else
        push!(log, "$(name(node)): No Name attribute")
    end
end
#parse(DateTime, "2022-01-21T13:23:36.45", dateformat"yyyy-mm-ddTHH:MM:SS.s")
#ZonedDateTime("2022-01-21T13:23:36+00:00", "yyyy-mm-ddTHH:MM:SSzzzz")
#ZonedDateTime("2022-01-21T13:23:36.664+00:00", "yyyy-mm-ddTHH:MM:SS.s+zzzz")

# A human-readable name for a measurement unit
function checknode!(log::AbstractVector, node::AbstractODMNode, type::ODMNodeType{:Symbol})
    length(node.attr) == 0 || push!(log, "$(name(node)): Unknown attribute(s) - $(keys(node.attr))")
    ch = children(node)
    for i in ch
        if name(i) ∉ CHNS[name(node)] push!(log, "$(name(node)): Unexpected node ($(name(i))) in body") end
    end
    if countnodenames(node, :TranslatedText) < 1 push!(log, "$(name(node)): No TranslatedText node in body") end
end

#Human-readable text that is appropriate for a particular language. TranslatedText elements typically occur in a series, presenting a set of alternative textual renditions for different languages.
function checknode!(log::AbstractVector, node::AbstractODMNode, type::ODMNodeType{:TranslatedText})
    ks = Set([Symbol("xml:lang")])
    for k in keys(node.attr)
        k in ks || push!(log, "$(name(node)): Unknown attribute ($(k))")
    end
    if !existchildtextnode(node) push!(log, "$(name(node)): No text node in body") end
    for i in children(node)
        if !isa(i, ODMTextNode) push!(log, "$(name(node)): Unexpected node ($(name(i))) in body") end
    end
end

function checknode!(log::AbstractVector, node::AbstractODMNode, type::ODMNodeType{:MetaDataVersion})

end

function countnodenames(node, nodename)
    cnt = 0
    ch = children(node)
    for i in ch
        if name(i) == nodename cnt += 1 end
    end
    cnt
end
function existchildtextnode(node)
    for i in children(node)
        if isa(i, ODMTextNode) return true end
    end
    false
end

function validateodm_(log::AbstractVector, node::AbstractODMNode)
    checknode!(log, node, ODMNodeType(name(node)))
    for i in node.el
        validateodm_(log, i)
    end
end
function validateodm_(log::AbstractVector, node::ODMTextNode)
end
function validateodm(odm::ODMRoot)
    log = String[]
    validateodm_(log, odm)
    log
end


text:
#=
getFactorWp
getTrotterParameter
getTrotterIteration
getTrotterlayers
getBeta
setTrotterparameter!
setTrotterIteration
checkInfo!

getFactorW
getMeasureOperator
isZeroTemperature
getTemperature
getExternalfield
getEnvParameters
=#

abstract QuantumSpinModel{T} <: SpinModel{T}

function getFactorWp{T}(qspin::QuantumSpinModel{T})
	return qspin.factorWp
end

# functions for check trotterinfo and spininfo
function checkInfo!{T}(spininfo::SpinInfo{T}, trotterinfo::TrotterInfo{T})
	if !isZeroTemperature(spininfo)
		temp = getTemperature(trotterinfo)
		if getTemperature(spininfo) != temp
			setTemperature!(spininfo, temp)
			@printf "adjust temperature in spininfo to %f" temp
		end
	end
end

# inherit from trotterinfo
single_args_non_preserving = [
							  :getTrotterparameter,
							  :getTrotteriteration,
							  :getTrotterlayers,
							  :getBeta
							 ]

for f in single_args_non_preserving
	eval(quote

		function $(f)(quantumspinmodel::QuantumSpinModel)
			return $(f)(quantumspinmodel.trotterinfo)
		end

	end)
end

set_single_parameter = [:setTrotterparameter!,
						:setTrotterIteration!]
for f in set_single_parameter
	eval(quote

	  function $(f){T}(quantumspinmodel::QuantumSpinModel{T}, parameter)
		 $(f)(quantumspinmodel.trotterinfo, parameter)
		 initialize!(quantumspinmodel)
	  end

	end)
end


text:
# some temporary defapf.initions
struct MySBP{Tsbp} <: AbstractSBP{Tsbp}
  degree::Int
  numnodes::Int
  numfacenodes::Int
end

struct MyFace{Tsbp} <: SummationByParts.AbstractFace{Tsbp}
  degree::Int
  numnodes::Int
  stencilsize::Int
end


text:
#ДАНО: Робот - в произвольной клетке ограниченного прямоугольного поля
#РЕЗУЛЬТАТ: Робот - в исходном положении, и клетки поля промакированы так: нижний ряд - полностью,
#следующий - весь, за исключением одной последней клетки на Востоке, следующий - за исключением двух
#последних клеток на Востоке, и т.д.
#дополнительно на поле могут находиться внутрение перегородки прямоугольной формы, среди которых могут быть
#и вырожденые прямоугольники (отрезки), эти внутренние перегородки изолированы друг от друга и от внешней рамки.

function ryad(r,side)
    num = 0
    while !isborder(r,side)
        move!(r,side)
        num += 1
    end
    moves!(r, reverse(side))
    return num
end

function reverse(side::HorizonSide)
    for i=0:3
        if side == HorizonSide(i)
            return HorizonSide(mod(i+2, 4))
        end
    end
end

function moves!(r, side)
    num = 0
    while !isborder(r,side)
        move!(r, side)
        num += 1
    end
    return num
end

function check(r,sh, x, y) #функция проверяет нужно ли ставить маркер
    if (x+y) <= sh
        putmarker!(r)
    end
end

function move_coord!(r,side) #двигает робота и отсчитывает координаты
    global x_coord, y_coord
    if side == Nord
        y_coord += 1
    end
    if side == Sud
        y_coord -= 1
    end
    if side == Ost
        x_coord += 1
    end
    if side == West
        x_coord -= 1
    end
    move!(r,side)
end

function next_side(side)
    for i=0:3
        if side == HorizonSide(i)
            return HorizonSide(mod(i+3,4))
        end
    end
end

function obhod(r,side)
    global x_coord
    k = 0
    while (isborder(r,side) && !isborder(r,next_side(side)))
        move!(r,next_side(side))
        k += 1
    end
    if isborder(r,next_side(side))&&isborder(r,side)
        for i in 1:k
            move!(r,reverse(next_side(side)))
        end
        return 0
    end
    if !isborder(r,side)
        move_coord!(r,side)
    end
    if k != 0
        while isborder(r,reverse(next_side(side)))
            move_coord!(r,side)
        end
        for i in 1:k
            move!(r,reverse(next_side(side)))
        end
    end
    return 1
end

function back(r, side)
    c = 1
    while c != 0
        if !isborder(r, side)
            move_coord!(r, side)
        else
            c = obhod(r,side)
            if c == 0
                break
            end
        end
    end
end

function moves!(r, side, num) #перемещает на число шагов
    for i in 1:num
        if !isborder(r,side)
            move!(r, side)
        end
    end
end

function reverse(i::Int)
    if isodd(i) == true
        side = Ost
    else
        side = Nord
    end
    return side
end

function back_a(r,a)
    global num   #размер массива
    for i = 1:num
        moves!(r,reverse(num-i+1),a[num-i+1])
    end
end

function lesenka_17(r)
    a = Int64[]
    global num = 0
    global x_coord = 0
    global y_coord = 0
    while !isborder(r,Sud) || !isborder(r,West)
        push!(a, moves!(r,West))
        push!(a, moves!(r,Sud))
        num += 2
    end
    sh = ryad(r, Ost) #ширина поля
    while !isborder(r,Nord)
        c = 1
        while c != 0
            check(r, sh, x_coord, y_coord)
            if !isborder(r, Ost)
                move_coord!(r, Ost)
                check(r, sh, x_coord, y_coord)
            else
                c = obhod(r, Ost)
                check(r, sh, x_coord, y_coord)
                if c == 0
                    break
                end
            end
        end
        back(r, West)
        if !isborder(r, Nord)
            move_coord!(r, Nord)
        end
    end
    while !isborder(r, Ost)
        check(r,sh, x_coord, y_coord)
        move_coord!(r, Ost)
    end
    back(r, West)
    back(r, Sud)
    back_a(r,a)
end

max_stars_repo_name: gardend/mirea-progs

max_issues_repo_name: gardend/mirea-progs

max_forks_repo_name: gardend/mirea-progs