text:
function read_xml(io::Union{IO, AbstractString})
	xml = EzXML.readxml(io)
	return _parse_document(xml)
end

function parse_xml(xmlstring::AbstractString)
	xml = EzXML.parsexml(xmlstring)
	return _parse_document(xml)
end

function _parse_document(xml::EzXML.Document)

    data, cnpj, tipo = _parse_documento_ddr(xml)
    nome, telefone, email = _parse_parametros(xml)

    responsavel = Responsavel(nome, telefone, email)

    contas = _parse_contas(xml)

	doc = Doc2011(data, cnpj, tipo, responsavel, contas)
	return doc

end

function _parse_documento_ddr(xml::EzXML.Document)

	node = findfirst("/documentoDDR", xml)

	@assert node != nothing "nao encontrou node documentoDDR"

	str_data = node["dataBase"]
	data = Dates.Date(str_data, Dates.DateFormat("yyyy-mm-dd"))

	cnpj = node["cnpj"]

	str_tipo_envio = node["tipoEnvio"]
	tipo = decode_tipo_envio(str_tipo_envio)

	return data, cnpj, tipo

end

function _parse_parametros(xml::EzXML.Document)

	node_nome = findfirst("/documentoDDR/parametros/parametro[@codigoParametro='31']", xml)
	@assert node_nome != nothing "nao encontrou parametro nome (codigo 31)"
	nome = node_nome["valorParametro"]

	node_telefone = findfirst("/documentoDDR/parametros/parametro[@codigoParametro='32']", xml)
	@assert node_telefone != nothing "nao encontrou parametro telefone (codigo 32)"
	telefone = node_telefone["valorParametro"]

	node_email = findfirst("/documentoDDR/parametros/parametro[@codigoParametro='33']", xml)
	@assert node_email != nothing "nao encontrou parametro email (codigo 33)"
	email = node_email["valorParametro"]

	return nome, telefone, email

end

function _parse_contas(xml::EzXML.Document)::Vector{Conta}

	out = Vector{Conta}()

	nodes = findall("/documentoDDR/contas/conta", xml)

	for node in nodes
		codigo = node["codigoConta"]
		try
			valor = parse(Float64, node["valorConta"])
			detalhes = _parse_detalhes(node)
			conta = Conta(codigo, valor, detalhes)
			push!(out, conta)
		catch e
			error("erro ao ler conta $codigo: $e")
		end

	end

	return out

end

function _parse_detalhes(node_conta::EzXML.Node)::Vector{DetalheConta}

	out = Vector{DetalheConta}()
	nodes = findall("detalhamentosDDR/detalhamentoDDR", node_conta)

	for node in nodes
		valor_detalhe = parse(Float64, node["valorDetalhe"])
		elementos = Vector{ElementoDetalhe}()
		detalhes = findall("detalhe", node)
		for detalhe in detalhes
			codigo = detalhe["codigoElemento"]
			valor = detalhe["valorElemento"]
			elemento_detalhe = _parse_elemento_detalhe(codigo, valor)
			push!(elementos, elemento_detalhe)
		end
		detalhe_conta = DetalheConta(elementos, valor_detalhe)
		push!(out, detalhe_conta)
	end

	return out
end

function _parse_elemento_detalhe(codigo::String, valor::String)::ElementoDetalhe

	T = _decode_tipo_elemento_detalhe(codigo)
	return T(valor) # usando construtor com string

end

function _decode_tipo_elemento_detalhe(codigo::String)::DataType

	if codigo == "81"
		return Pais
	elseif codigo == "83"
		return Moeda
	elseif codigo == "84"
		return Posicao
	else
		error("codigoElemento invalido: $codigo")
	end

end


text:
using OrdinaryDiffEq, Test
using DiffEqProblemLibrary.ODEProblemLibrary: importodeproblems; importodeproblems()
import DiffEqProblemLibrary.ODEProblemLibrary: prob_ode_linear, prob_ode_2Dlinear
prob = prob_ode_2Dlinear
choice_function(integrator) = (Int(integrator.t<0.5) + 1)
alg_double = CompositeAlgorithm((Tsit5(),Tsit5()),choice_function)
alg_double2 = CompositeAlgorithm((Vern6(),Vern6()),choice_function)
alg_switch = CompositeAlgorithm((Tsit5(),Vern7()),choice_function)

@time sol1 = solve(prob_ode_linear,alg_double)
@time sol2 = solve(prob_ode_linear,Tsit5())
@test sol1.t == sol2.t
@test sol1(0.8) == sol2(0.8)

integrator1 = init(prob,alg_double2)
integrator2 = init(prob,Vern6())
solve!(integrator1)
solve!(integrator2)

@test integrator1.sol.t == integrator2.sol.t

sol = solve(prob,alg_switch)
@inferred DiffEqBase.__init(prob, alg_switch)
v = @inferred OrdinaryDiffEq.ode_interpolant(1.0, integrator1, integrator1.opts.save_idxs, Val{0})
@inferred OrdinaryDiffEq.ode_interpolant!(v, 1.0, integrator1, integrator1.opts.save_idxs, Val{0})
v = @inferred OrdinaryDiffEq.ode_extrapolant(1.0, integrator1, integrator1.opts.save_idxs, Val{0})
@inferred OrdinaryDiffEq.ode_extrapolant!(v, 1.0, integrator1, integrator1.opts.save_idxs, Val{0})

ext: jl


text:
using MechanicalUnits

using Test
@testset "Prefixes and conversions" begin
    @test 10dm == 1m
    @test 1daN == 10N
    @test m(1e6μm) == 1.0m
    @test 1e6μm == 1.0m
    @test !(1e6μm === 1m)
    @test m(1e6μm) === 1.0m
    @test 1e6μm |> m === 1.0m
    @test 1000μm * 1m |> m² === (1//1000)m^2
    @test 1.0m² == 1.0m^2
    @test 1.0m² === 1.0m^2
end

max_stars_repo_name: hustf/MechanicalUnits

max_issues_repo_name: hustf/MechanicalUnits


text:
defs(mod::LLVM.Module)  = filter(f -> !isdeclaration(f), collect(functions(mod)))
decls(mod::LLVM.Module) = filter(f ->  isdeclaration(f) && !LLVM.isintrinsic(f),
                                 collect(functions(mod)))

## lazy module loading

using UUIDs

struct LazyModule
    pkg::Base.PkgId
    LazyModule(name, uuid) = new(Base.PkgId(uuid, name))
end

function Base.getproperty(lazy_mod::LazyModule, sym::Symbol)
    pkg = getfield(lazy_mod, :pkg)
    mod = get(Base.loaded_modules, pkg, nothing)
    if mod === nothing
        error("This functionality requires the $(pkg.name) package, which should be installed and loaded first.")
    end
    getfield(mod, sym)
end

## safe logging

using Logging

const STDERR_HAS_COLOR = Ref{Bool}(false)

# define safe loggers for use in generated functions (where task switches are not allowed)
for level in [:debug, :info, :warn, :error]
    @eval begin
        macro $(Symbol("safe_$level"))(ex...)
            macrocall = :(@placeholder $(ex...))
            # NOTE: `@placeholder` in order to avoid hard-coding @__LINE__ etc
            macrocall.args[1] = Symbol($"@$level")
            quote
                old_logger = global_logger()
                io = IOContext(Core.stderr, :color=>STDERR_HAS_COLOR[])
                min_level = Logging.min_enabled_level(old_logger)
                global_logger(Logging.ConsoleLogger(io, min_level))
                ret = $(esc(macrocall))
                global_logger(old_logger)
                ret
            end
        end
    end
end

## codegen locking

# lock codegen to prevent races on the LLVM context.
#
# XXX: it's not allowed to switch tasks while under this lock, can we guarantee that?
#      its probably easier to start using our own LLVM context when that's possible.
macro locked(ex)
    def = splitdef(ex)
    def[:body] = quote
        ccall(:jl_typeinf_begin, Cvoid, ())
        try
            $(def[:body])
        finally
            ccall(:jl_typeinf_end, Cvoid, ())
        end
    end
    esc(combinedef(def))
end

# HACK: temporarily unlock again to perform a task switch
macro unlocked(ex)
    def = splitdef(ex)
    def[:body] = quote
        ccall(:jl_typeinf_end, Cvoid, ())
        try
            $(def[:body])
        finally
            ccall(:jl_typeinf_begin, Cvoid, ())
        end
    end
    esc(combinedef(def))
end


text:
@testset "669.trim-a-binary-search-tree.jl" begin
    @test trim_BST(TreeNode{Int}([1, 0, 2]), 1, 2) == TreeNode{Int}([1, nothing, 2])
    @test trim_BST(TreeNode{Int}([3, 0, 4, nothing, 2, nothing, nothing, 1]), 1, 3) ==
          TreeNode{Int}([3, 2, nothing, 1])
    @test trim_BST(TreeNode{Int}([1]), 1, 2) == TreeNode{Int}([1])
    @test trim_BST(TreeNode{Int}([1, nothing, 2]), 1, 3) == TreeNode{Int}([1, nothing, 2])
    @test trim_BST(TreeNode{Int}([1, nothing, 2]), 2, 4) == TreeNode{Int}([2])
end


text:
using CSV
using DataFrames
using Query
using PyPlot
using Statistics

# Different choices of n_set is needed for different seeds (1, 2, or 3)
n_set = 1
# ------------------------------------------------------------------------------
# Defining Hyper Parameters
update_form = "SurNoR"
Path_Main = "src/Optimization_Simulated_Data/OverAll/"
Path_Files = Path_Main

# ------------------------------------------------------------------------------
# Load Data
Chains = 500

Chain = 1
Path = string(Path_Files, "CoAscData_OverAll_SurNoR_nset_", string(n_set), "_C",
               string(Chain), ".csv")

global CoAsc_Data = CSV.read(Path)

for Chain = 2:Chains
    Path = string(Path_Files, "CoAscData_OverAll_SurNoR_nset_", string(n_set), "_C",
                   string(Chain), ".csv")
    if isfile(Path)
        temp = CSV.read(Path)
        global CoAsc_Data = cat(CoAsc_Data,temp; dims=1)
    end
    @show Chain
end

for Chain = 1:length(CoAsc_Data)
    CoAsc_Data[Chain] = CoAsc_Data[Chain][CoAsc_Data[Chain].LogL .< 0,:]
end

# ------------------------------------------------------------------------------
# Plot Log Series
fig = figure(); ax = gca()
ax.plot(CoAsc_Data[1].LogL, linewidth=0.1)
for i = 2:length(CoAsc_Data)
   ax.plot(CoAsc_Data[i].LogL, linewidth=0.1)
end
title(string(update_form, " - LogL Series" ))
ax.grid(true); ax.legend()
Path_save = "data/Fitted_parameters_simulated/OverAll/"
savefig(string(Path_save, update_form, " - LogL Series_nset_", string(n_set), ".pdf" ))
close(fig)
# ------------------------------------------------------------------------------
# V_Cat
global CoAsc_Data_Series = CoAsc_Data[1][end,:]
for i = 2:length(CoAsc_Data)
    global CoAsc_Data_Series = vcat(CoAsc_Data_Series, CoAsc_Data[i][end,:])
end
CoAsc_Data_Series = @from i in CoAsc_Data_Series begin
                   @where i.LogL < 0
                   @select i
                   @collect DataFrame
                   end
unique!(CoAsc_Data_Series)

global BestLogL = findmax(CoAsc_Data_Series.LogL)
global BestParam = CoAsc_Data_Series[BestLogL[2],:]

Ind = CoAsc_Data_Series.LogL .> (BestLogL[1]-5)
global BestParam_diff5 = CoAsc_Data_Series[Ind,:]

BestParam_Save = DataFrame(BestParam)

Path = string(Path_save, "nset_", string(n_set), "/", "OverAll_", update_form, "_BestParams.csv")
CSV.write(Path, BestParam_Save)

BestParam_diff5_Save = DataFrame(BestParam_diff5)
sort!(BestParam_diff5_Save, :LogL, rev=true)
Path = string(Path_save, "nset_", string(n_set), "/", "OverAll_", update_form, "_BestParams_diff5.csv")
CSV.write(Path, BestParam_diff5_Save)


text:
using Test
using JustSayIt
using JustSayIt.API
using PyCall
import JustSayIt: DEFAULT_MODEL_NAME, TYPE_MODEL_NAME, MODELDIR_PREFIX, COMMAND_RECOGNIZER_ID
import JustSayIt: init_jsi, finalize_jsi, command_names, command, noises_names, noises, model, recognizer

@testset "$(basename(@__FILE__))" begin
    @testset "1. initialization" begin
        commands = Dict("help"    => Help.help,
                        "type"    => Keyboard.type,
                        "redo"    => (Key.ctrl, Key.shift, 'z'),
                        "upwards" => Key.page_up)
        modeldirs = Dict(DEFAULT_MODEL_NAME => joinpath(MODELDIR_PREFIX, "vosk-model-small-en-us-0.15"),
                         TYPE_MODEL_NAME    => joinpath(MODELDIR_PREFIX, "vosk-model-small-en-us-0.15"))
        mynoises  = Dict(DEFAULT_MODEL_NAME => ["huh"],
                         TYPE_MODEL_NAME    => ["huhuh"])
        init_jsi(commands, modeldirs, mynoises)
        @testset "commands" begin
            @test command_names() == keys(commands)
            @test command("help") == Help.help
            @test command("type") == Keyboard.type
            @test command("redo") == (Key.ctrl, Key.shift, 'z')
            @test command("upwards") == Key.page_up
        end;
        @testset "noises" begin
            @test noises_names() == keys(mynoises)
            @test noises(DEFAULT_MODEL_NAME) == ["huh"]
            @test noises(TYPE_MODEL_NAME) == ["huhuh"]
        end;
        @testset "models" begin
            @test isa(model(DEFAULT_MODEL_NAME), PyObject)
        end;
        @testset "recognizers" begin
            @test isa(recognizer(DEFAULT_MODEL_NAME), PyObject)
            @test isa(recognizer(COMMAND_RECOGNIZER_ID), PyObject)
        end;
        finalize_jsi()
    end;
end;


text:
function _get_initial_conditions_value(
    ::Vector{T},
    component::W,
    ::U,
    ::V,
    container::OptimizationContainer,
) where {
    T <: InitialCondition{U, Float64},
    V <: Union{AbstractDeviceFormulation, AbstractServiceFormulation},
    W <: PSY.Component,
} where {U <: InitialConditionType}
    ic_data = get_initial_conditions_data(container)
    var_type = initial_condition_variable(U(), component, V())
    if !has_initial_condition_value(ic_data, var_type, W)
        val = initial_condition_default(U(), component, V())
    else
        val = get_initial_condition_value(ic_data, var_type, W)[1, PSY.get_name(component)]
    end
    @debug "Device $(PSY.get_name(component)) initialized DeviceStatus as $var_type" _group =
        LOG_GROUP_BUILD_INITIAL_CONDITIONS
    return T(component, val)
end

function _get_initial_conditions_value(
    ::Vector{T},
    component::W,
    ::U,
    ::V,
    container::OptimizationContainer,
) where {
    T <: InitialCondition{U, PJ.ParameterRef},
    V <: Union{AbstractDeviceFormulation, AbstractServiceFormulation},
    W <: PSY.Component,
} where {U <: InitialConditionType}
    ic_data = get_initial_conditions_data(container)
    var_type = initial_condition_variable(U(), component, V())
    if !has_initial_condition_value(ic_data, var_type, W)
        val = initial_condition_default(U(), component, V())
    else
        val = get_initial_condition_value(ic_data, var_type, W)[1, PSY.get_name(component)]
    end
    @debug "Device $(PSY.get_name(component)) initialized DeviceStatus as $var_type" _group =
        LOG_GROUP_BUILD_INITIAL_CONDITIONS
    return T(component, add_jump_parameter(get_jump_model(container), val))
end

function _get_initial_conditions_value(
    ::Vector{T},
    component::W,
    ::U,
    ::V,
    container::OptimizationContainer,
) where {
    T <: InitialCondition{U, Float64},
    V <: Union{AbstractDeviceFormulation, AbstractServiceFormulation},
    W <: PSY.Component,
} where {U <: InitialTimeDurationOff}
    ic_data = get_initial_conditions_data(container)
    var_type = initial_condition_variable(U(), component, V())
    if !has_initial_condition_value(ic_data, var_type, W)
        val = initial_condition_default(U(), component, V())
    else
        var = get_initial_condition_value(ic_data, var_type, W)[1, PSY.get_name(component)]
        val = 0.0
        if !PSY.get_status(component) && !(var > ABSOLUTE_TOLERANCE)
            val = PSY.get_time_at_status(component)
        end
    end
    @debug "Device $(PSY.get_name(component)) initialized DeviceStatus as $var_type" _group =
        LOG_GROUP_BUILD_INITIAL_CONDITIONS
    return T(component, val)
end

function _get_initial_conditions_value(
    ::Vector{T},
    component::W,
    ::U,
    ::V,
    container::OptimizationContainer,
) where {
    T <: InitialCondition{U, PJ.ParameterRef},
    V <: Union{AbstractDeviceFormulation, AbstractServiceFormulation},
    W <: PSY.Component,
} where {U <: InitialTimeDurationOff}
    ic_data = get_initial_conditions_data(container)
    var_type = initial_condition_variable(U(), component, V())
    if !has_initial_condition_value(ic_data, var_type, W)
        val = initial_condition_default(U(), component, V())
    else
        var = get_initial_condition_value(ic_data, var_type, W)[1, PSY.get_name(component)]
        val = 0.0
        if !PSY.get_status(component) && !(var > ABSOLUTE_TOLERANCE)
            val = PSY.get_time_at_status(component)
        end
    end
    @debug "Device $(PSY.get_name(component)) initialized DeviceStatus as $var_type" _group =
        LOG_GROUP_BUILD_INITIAL_CONDITIONS
    return T(component, add_jump_parameter(get_jump_model(container), val))
end

function _get_initial_conditions_value(
    ::Vector{T},
    component::W,
    ::U,
    ::V,
    container::OptimizationContainer,
) where {
    T <: InitialCondition{U, Float64},
    V <: Union{AbstractDeviceFormulation, AbstractServiceFormulation},
    W <: PSY.Component,
} where {U <: InitialTimeDurationOn}
    ic_data = get_initial_conditions_data(container)
    var_type = initial_condition_variable(U(), component, V())
    if !has_initial_condition_value(ic_data, var_type, W)
        val = initial_condition_default(U(), component, V())
    else
        var = get_initial_condition_value(ic_data, var_type, W)[1, PSY.get_name(component)]
        val = 0.0
        if PSY.get_status(component) && (var > ABSOLUTE_TOLERANCE)
            val = PSY.get_time_at_status(component)
        end
    end
    @debug "Device $(PSY.get_name(component)) initialized DeviceStatus as $var_type" _group =
        LOG_GROUP_BUILD_INITIAL_CONDITIONS
    return T(component, val)
end

function _get_initial_conditions_value(
    ::Vector{T},
    component::W,
    ::U,
    ::V,
    container::OptimizationContainer,
) where {
    T <: InitialCondition{U, PJ.ParameterRef},
    V <: Union{AbstractDeviceFormulation, AbstractServiceFormulation},
    W <: PSY.Component,
} where {U <: InitialTimeDurationOn}
    ic_data = get_initial_conditions_data(container)
    var_type = initial_condition_variable(U(), component, V())
    if !has_initial_condition_value(ic_data, var_type, W)
        val = initial_condition_default(U(), component, V())
    else
        var = get_initial_condition_value(ic_data, var_type, W)[1, PSY.get_name(component)]
        val = 0.0
        if PSY.get_status(component) && (var > ABSOLUTE_TOLERANCE)
            val = PSY.get_time_at_status(component)
        end
    end
    @debug "Device $(PSY.get_name(component)) initialized DeviceStatus as $var_type" _group =
        LOG_GROUP_BUILD_INITIAL_CONDITIONS
    return T(component, add_jump_parameter(get_jump_model(container), val))
end

function _get_initial_conditions_value(
    ::Vector{T},
    component::W,
    ::U,
    ::V,
    container::OptimizationContainer,
) where {
    T <: InitialCondition{U, PJ.ParameterRef},
    V <: Union{AbstractDeviceFormulation, AbstractServiceFormulation},
    W <: PSY.Component,
} where {U <: Union{InitialEnergyLevel, InitialEnergyLevelUp, InitialEnergyLevelDown}}
    ic_data = get_initial_conditions_data(container)
    val = initial_condition_default(U(), component, V())
    @debug "Device $(PSY.get_name(component)) initialized DeviceStatus as $var_type" _group =
        LOG_GROUP_BUILD_INITIAL_CONDITIONS
    return T(component, add_jump_parameter(get_jump_model(container), val))
end

function _get_initial_conditions_value(
    ::Vector{T},
    component::W,
    ::U,
    ::V,
    container::OptimizationContainer,
) where {
    T <: InitialCondition{U, Float64},
    V <: Union{AbstractDeviceFormulation, AbstractServiceFormulation},
    W <: PSY.Component,
} where {U <: Union{InitialEnergyLevel, InitialEnergyLevelUp, InitialEnergyLevelDown}}
    ic_data = get_initial_conditions_data(container)
    val = initial_condition_default(U(), component, V())
    @debug "Device $(PSY.get_name(component)) initialized DeviceStatus as $var_type" _group =
        LOG_GROUP_BUILD_INITIAL_CONDITIONS
    return T(component, val)
end

function add_initial_condition!(
    container::OptimizationContainer,
    components::Union{Vector{T}, IS.FlattenIteratorWrapper{T}},
    ::U,
    ::D,
) where {
    T <: PSY.Component,
    U <: Union{AbstractDeviceFormulation, AbstractServiceFormulation},
    D <: InitialConditionType,
}
    ini_cond_vector = add_initial_condition_container!(container, D(), T, components)
    for (ix, component) in enumerate(components)
        ini_cond_vector[ix] =
            _get_initial_conditions_value(ini_cond_vector, component, D(), U(), container)
    end
end


text:
#
# Unit tests for AstrodynamicalModels.jl
#

include("R2BP.jl")
include("CR3BP.jl")
include("NBP.jl")


text:
cluster = [1 1 1 1; 2 2 3 3; 4 4 5 5]
X = Array(reshape(1:24, 2, 3, 4))

@testset "pool" begin
    @testset "GlobalPool" begin
        glb_cltr = [1 1 1 1; 1 1 1 1; 1 1 1 1]
        p = GlobalPool(+, 3, 4)
        @test p(X) == NNlib.scatter(+, X, glb_cltr)
    end

    @testset "LocalPool" begin
        p = LocalPool(+, cluster)
        @test p(X) == NNlib.scatter(+, X, cluster)
    end

    @testset "TopKPool" begin
        N = 10
        k, in_channel = 4, 7
        X = rand(in_channel, N)
        for T = [Bool, Float64]
            adj = rand(T, N, N)
            p = TopKPool(adj, k, in_channel)
            @test eltype(p.p) === Float32
            @test size(p.p) == (in_channel,)
            @test eltype(p.Ã) === T
            @test size(p.Ã) == (k, k)
            y = p(X)
            @test size(y) == (in_channel, k)
        end
    end

    @testset "topk_index" begin
        X = [8,7,6,5,4,3,2,1]
        @test topk_index(X, 4) == [1,2,3,4]
        @test topk_index(X', 4) == [1,2,3,4]
    end
end


text:
using GenericSchur;

function fun2m_condest(f, A, B, C; wp = 128)

    with_digits(wp) do
        A = mp(A, wp);
        B = mp(B, wp);
        C = mp(C, wp);

        FA = schur(A);
        FB = schur(B);

        C = FA.Z' * C * FB.Z;

        # size of the perturbation, make sure it's sufficiently far given the
        # current precision level.
        ep = 10.0^(-wp/2.0);

        TA = FA.T + diagm(randn(size(FA.T, 1))) * ep * norm(FA.T, Inf);
        TB = FB.T + diagm(randn(size(FB.T, 1))) * ep * norm(FB.T, Inf);
        Y = diag_fun(f, TA, TB, C);

        h = sqrt(ep);

        EA = mp(randn(size(TA, 1), size(TA, 1)), wp); EA = EA / norm(EA) * h * norm(TA);
        EB = mp(randn(size(TB, 1), size(TB, 1)), wp); EB = EB / norm(EB) * h * norm(TB);

        # We force the same sparsity pattern on the perturbations
        # EA = (TA .!= 0) .* EA;
        # EB = (TB .!= 0) .* EB;

        TA = TA + EA;
        TB = TB + EB;

        Y2 = diag_fun(f, TA, TB, C);

        c = convert(Float64, norm(Y2 - Y) / norm(Y) / h)

        return c;
    end

end

max_stars_repo_name: numpi/BivMatFun

max_issues_repo_name: numpi/BivMatFun

max_forks_repo_name: numpi/BivMatFun


text:
__precompile__()
module Shampoo

using JUDI, JOLI, LinearAlgebra, FFTW, SpecialFunctions, DSP

export CumsumOp,DiffOp,HammingOp,FractionalIntegrationOp,FractionalLaplacianOp, MaskOp

# utilities
include("utils/adj_diff_cumsum.jl")
include("utils/auxilary.jl")
include("utils/fgl_deriv.jl")
include("utils/Filter_freq_band.jl")
include("utils/joConvolve.jl")
include("utils/wavelet.jl")

# operators
include("operators/fractional_integration.jl")
include("operators/fractional_laplacian.jl")
include("operators/hamming_operator.jl")
include("operators/mask_op.jl")

# left preconditioners: work in data domain

function CumsumOp(nt::Int,nsrc::Int,nrec::Int;DDT=Float32)
	P = joLinearFunctionFwd_T(nt*nsrc*nrec, nt*nsrc*nrec,
	                             v -> cumsum(v),
	                             w -> adjoint_cumsum(w),
								 DDT,DDT,name="cumsum operator")
end

function DiffOp(nt::Int,nsrc::Int,nrec::Int;order=1,DDT=Float32)
	P = joLinearFunctionFwd_T(nt*nsrc*nrec, nt*nsrc*nrec,
	                             v -> diff(v),
	                             w -> adjoint_diff(w),
								 DDT,DDT,name="diff operator")
	return P
end

function HammingOp(nt::Int,nsrc::Int,nrec::Int;DDT=Float32)
	H = joLinearFunctionFwd_T(nt*nsrc*nrec, nt*nsrc*nrec,
								v -> hamm_op(v),
								w -> hamm_op(w),
								DDT,DDT,name="Hamming operator")
	return H
end

function FractionalIntegrationOp(nt::Int,nsrc::Int,nrec::Int,order::Number;DDT=Float32)
	### Positive order -> integration, Negative order -> derivative
	C = frac_int(nt,order; DDT=DDT)
	P = joLinearFunctionFwd_T(nt*nsrc*nrec, nt*nsrc*nrec,
	                             v -> apply_frac_integral(C,v),
	                             w -> apply_frac_integral(C',w),
								 DDT,DDT,name="Fractional integration operator")
	return P
end

# right preconditioners: work in model domain

function MaskOp(n::Tuple,mask::Array{DDT}) where {DDT}
	P = joLinearFunctionFwd_T(prod(n), prod(n),
								v -> mask_op(v,mask),
								w -> mask_op(w,mask),
								DDT,DDT,name="Mask operator")
	return P
end

function FractionalLaplacianOp(n::Tuple,order::Number;DDT=Float32)
	model = F.model
	info = F.info
	P = laplacian_operator(model::Model,order::Number,info::Info)
	return P
end

end


text:
module TestQuery

using StructuredQueries
using Base.Test

io = IOBuffer()
disp = TextDisplay(IOBuffer())

immutable MyData end
src = MyData()
_src = MyData()

n = 10
A = rand(n)
B = collect(1:n)
D = rand(["a", "b"], n)

# select

c1 = @with src select(A)
c2 = @with src begin
    select(A)
end
@test isequal(c1, c2)
show(io, c1)
display(disp, c1)

c1 = @with src select(C = A * B)
c2 = @with src begin
    select(C = A * B)
end
@test isequal(c1, c2)
show(io, c1)
display(disp, c1)

c1 = @with src select(A, C = A * B)
c2 = @with src begin
    select(A, C = A * B)
end
@test isequal(c1, c2)
show(io, c1)
display(disp, c1)

# filter

c1 = @with src filter(A > .5)
c2 = @with src begin
    filter(A > .5)
end
@test isequal(c1, c2)
show(io, c1)
display(disp, c2)

# orderby

c1 = @with src orderby(A)
c2 = @with src begin
    orderby(A)
end
@test isequal(c1, c2)
show(io, c1)
display(disp, c1)

c1 = @with src orderby(5 * B)
c2 = @with src begin
    orderby(5 * B)
end
@test isequal(c1, c2)
show(io, c1)
display(disp, c1)

c1 = @with src orderby(A, 5 * B)
c2 = @with src begin
    orderby(A, 5 * B)
end
@test isequal(c1, c2)
show(io, c1)
display(disp, c1)

# groupby

c1 = @with src groupby(D)
c2 = @with src begin
    groupby(D)
end
@test isequal(c1, c2)
show(io, c1)
display(disp, c1)

c1 = @with src groupby(A > .5)
c2 = @with src begin
    groupby(A > .5)
end
@test isequal(c1, c2)
show(io, c1)
display(disp, c1)

c1 = @with src groupby(D, A > .5)
c2 = @with src begin
    groupby(D, A > .5)
end
@test isequal(c1, c2)
show(io, c1)
display(disp, c1)

# summarize

c1 = @with src summarize(avg_A = mean(A))
c2 = @with src begin
    summarize(avg_A = mean(A))
end
@test isequal(c1, c2)
show(io, c1)
display(disp, c1)

end


text:
using DifferentiableNAS
using Flux
using Flux: throttle, logitcrossentropy, onecold, onehotbatch, Optimiser
using Zygote: @nograd
using StatsBase: mean
using Parameters
using CUDA
using Distributions
using BSON
using Dates
using Plots
include("../CIFAR10.jl")
include("../training_utils.jl")

argparams = trial_params()

m = DARTSModel(num_cells = argparams.num_cells, channels = argparams.channels) |> gpu

optimiser_α = Optimiser(WeightDecay(1e-3),ADAM(3e-4,(0.5,0.999)))
optimiser_w = Optimiser(WeightDecay(3e-4),Momentum(0.025, 0.9))

train, val = get_processed_data(argparams.val_split, argparams.batchsize, argparams.trainval_fraction)
test = get_test_data(argparams.test_fraction)

histepoch = historiessml()
histbatch = historiessml()
losses = [0.0, 0.0]

base_folder = prepare_folder("scaling")

cbepoch = CbAll(CUDA.reclaim, histepoch, save_progress, CUDA.reclaim)
cbbatch = CbAll(CUDA.reclaim, histbatch, CUDA.reclaim)

for epoch in 1:argparams.epochs
    @show epoch
    Scalingtrain1st!(loss, m, train, val, optimiser_α, optimiser_w, 0.1, losses)
end

max_stars_repo_name: huangyxi/DifferentiableNAS

max_issues_repo_name: huangyxi/DifferentiableNAS

max_forks_repo_name: huangyxi/DifferentiableNAS


text:
module Format2DB

export main

using UUIDs, Dates, CSV, StructArrays, VideoIO, Tables, TableOperations, Dates, DataFrames

include("resfile.jl")

function gettimes(path)
    x = CSV.read(joinpath(path, "calibration_times.csv"), ignoreemptylines = true)
    times = Dict(r.file => (; r[Not(:file)]...) for r in eachrow(x))
    @assert all(file -> isfile(joinpath(path, file)), keys(times)) "video file/s missing"
    @assert all(file -> isfile(joinpath(path, string(first(splitext(file)), ".res"))), keys(times)) "res file/s missing"
    return times
end

function gettables(path, times, pixel)
    expname = basename(path)
    experiment = StructArray(((experiment = expname, experiment_description = "none", experiment_folder = path) for _ in 1:1))
    designation = Symbol(string("a", hash(path)))
    board = StructArray(((designation = designation, checker_width_cm = 4.0, checker_per_width = 2, checker_per_height = 2, board_description = "this is pretty bogus") for _ in 1:1))
    d = CSV.File(joinpath(path, "factors.csv"), ignoreemptylines = true) |> Dict
    isazimuth = isfile(joinpath(path, "azimuths.csv"))
    if isazimuth
        d["azimuth"] = ""
    end
    istp = isfile(joinpath(path, "turningpoints.csv"))
    if istp
        d["turningpoint"] = ""
    end
    factors = Dict(Symbol(k) => v for (k, v) in d)
    factors[:person] = "unknown"
    x = (; Dict(k => String[] for k in keys(factors))...)
    run = StructArray((run = UUID[], experiment = String[], date = Date[], id = String[], comment = String[], x...))
    azimuths = if isazimuth
        CSV.File(joinpath(path, "azimuths.csv"), ignoreemptylines = true) |> Dict
    else
        Dict()
    end
    turningpoints = if istp
        CSV.File(joinpath(path, "turningpoints.csv"), ignoreemptylines = true) |> Dict
    else
        Dict()
    end
    video = StructArray((video = UUID[], comment = String[]))
    videofile = StructArray((file_name = String[], video = UUID[], date_time = DateTime[], duration = Nanosecond[], index = Int[]))
    calibration = StructArray((calibration = UUID[], intrinsic = Union{Missing, UUID}[], extrinsic = UUID[], board = Symbol[], comment = String[]))
    interval = StructArray((interval = UUID[], video = UUID[], start = Nanosecond[], stop = Union{Nanosecond, Missing}[], comment = String[]))
    poi = StructArray((poi = UUID[], type = Symbol[], run = UUID[], calibration = UUID[], interval = UUID[]))
    columns = CSV.File(joinpath(path, "columns.csv"), ignoreemptylines = true) |> propertynames
    for (k, v) in times
        runid = uuid1()
        if haskey(azimuths, k)
            factors[:azimuth] = string(azimuths[k], "∘")
        end
        if haskey(turningpoints, k)
            factors[:turningpoint] = string(turningpoints[k])
        end
        push!(run, (run = runid, experiment = expname, date = Date(now()), id = string("id", hash(string(path, k))), comment = k, factors...))
        videoid = uuid1()
        push!(video, (video = videoid, comment = k))
        date_time, _duration = VideoIO.get_time_duration(joinpath(path, k))
        duration = Nanosecond(round(Int, 1000000000_duration))
        push!(videofile, (file_name = k, video = videoid, date_time = date_time, duration = duration, index = 1))
        calibrationid = uuid1()
        if haskey(v, :timestart)
            extrinsicid = uuid1()
            intrinsicid = uuid1()
            push!(calibration, (calibration = calibrationid, intrinsic = intrinsicid, extrinsic = extrinsicid, board = designation, comment = ""))
            push!(interval, (interval = extrinsicid, video = videoid, start = v.ground - Time(0), stop = missing, comment = ""))
            push!(interval, (interval = intrinsicid, video = videoid, start = v.timestart - Time(0), stop = v.timeend - Time(0), comment = ""))
            push!(poi, (poi = uuid1(), type = :calibration, run = runid, calibration = calibrationid, interval = extrinsicid))
            push!(poi, (poi = uuid1(), type = :calibration, run = runid, calibration = calibrationid, interval = intrinsicid))
        else
            extrinsicid = uuid1()
            push!(calibration, (calibration = calibrationid, intrinsic = missing, extrinsic = extrinsicid, board = designation, comment = ""))
            push!(interval, (interval = extrinsicid, video = videoid, start = v.time - Time(0), stop = missing, comment = ""))
            push!(poi, (poi = uuid1(), type = :calibration, run = runid, calibration = calibrationid, interval = extrinsicid))
        end
        resfile = joinpath(path, string(first(splitext(k)), ".res"))
        ids = savepixels(pixel, resfile)
        for (column, id) in zip(columns, ids)
            push!(interval, (interval = id, video = videoid, start = Nanosecond(0), stop = column == :track ? Nanosecond(1000000000) : missing, comment = "bogus"))
            push!(poi, (poi = uuid1(), type = column, run = runid, calibration = calibrationid, interval = id))
            nr = size(readdlm(joinpath(pixel, "$id.csv")), 1)
            @assert column == :track ? nr > 5 : nr == 1 "in $k the column for $column (column #$(findfirst(isequal(column), columns))) has $nr row/s"
        end
    end
    return filter(kv -> last(kv) isa StructArray, Base.@locals())
end

tonano(_::Missing) = missing
tonano(x) = Dates.value(Dates.Nanosecond(x))
saving(source, name, obj) = obj |> TableOperations.transform(start = tonano, stop = tonano, duration = tonano) |> CSV.write(joinpath(source, "$name.csv"))

function main(path; prefix = "source_")
    source = mktempdir(; prefix = prefix, cleanup = false)
    pixel = joinpath(source, "pixel")
    mkdir(pixel)
    # get the data
    times = gettimes(path)
    a = gettables(path, times, pixel)
    # save the data
    for (k, v) in a
        saving(source, k, v)
    end
    for file in keys(times)
        # @spawn symlink(joinpath(path, file), joinpath(source, file))
        # @show joinpath(path, file), joinpath(source, file)
        cp(joinpath(path, file), joinpath(source, file))
    end
    return source
end

end # module


text:
#TODO exports
#    get_property_names,
#    get_property_value,
#    can_open,
#    openslide_open,
#    get_level_count,
#    close_slide,
#    get_level0_dimensions,
#    get_level_dimensions,
#    get_level_downsample,
#    get_best_level_for_downsample,
#    read_region,
#    get_associated_image_names,
#    read_associated_image,
#    get_error,
#    openslide_version

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

const OPENSLIDE_PROPERTY_NAME_COMMENT = "openslide.comment"
const OPENSLIDE_PROPERTY_NAME_VENDOR = "openslide.vendor"
const OPENSLIDE_PROPERTY_NAME_QUICKHASH1 = "openslide.quickhash-1"
const OPENSLIDE_PROPERTY_NAME_BACKGROUND_COLOR = "openslide.background-color"
const OPENSLIDE_PROPERTY_NAME_OBJECTIVE_POWER = "openslide.objective-power"
const OPENSLIDE_PROPERTY_NAME_MPP_X = "openslide.mpp-x"
const OPENSLIDE_PROPERTY_NAME_MPP_Y = "openslide.mpp-y"

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

function _rgbfromrowflat(data::Array{Uint8,1}, dims)
    output = zeros(Uint8, *(dims...),3)
    @inbounds for i = 1:3
        output[:,i] = data[-(i-4):4:end]
    end
    return reshape(output, dims...,3)
end
function _readstrings(buf::Ptr{Ptr{Uint8}})
    rv = Any[]
    i = 1
    while (n = unsafe_load(buf,i)) != C_NULL
        push!(rv, bytestring(n))
        i += 1
    end
    return rv
end

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

function get_property_names(s::OSt)
    nms = ccall( (:openslide_get_property_names, los),
                 Ptr{Ptr{Uint8}}, (OSt,), s)
    _readstrings(nms)
end

function get_property_value(s::OSt, prop::ASCIIString)
    bytestring( ccall( (:openslide_get_property_value, los), Ptr{Uint8}, (OSt, Ptr{Uint8}), s, prop))
end

function can_open(fname::ASCIIString)
    ccall( (:openslide_can_open, los), Cint, (Ptr{Uint8},), fname) == 1 ? true : false
end

function openslide_open(fname::ASCIIString)
    ccall( (:openslide_open, los), Ptr{openslide_t}, (Ptr{Uint8},), fname)
end

function get_level_count(s::OSt)
    ccall( (:openslide_get_level_count, los), Cint, (OSt,), s)
end

function close_slide(s::OSt)
    ccall( (:openslide_close, los), Cint, (OSt,), s)
end

function get_level0_dimensions(s::OSt)
    w = Int64[0]
    h = Int64[0]
    ccall( (:openslide_get_level0_dimensions, los), Void, (Ptr{openslide_t}, Ptr{Int64}, Ptr{Int64}), s, w, h)
    return [w, h]
end

function get_level_dimensions(s::OSt, level::Int)
    w = Int[0]
    h = Int[0]
    ccall( (:openslide_get_level_dimensions, los),
            Void,
            (Ptr{openslide_t}, Int, Ptr{Cint}, Ptr{Cint}),
            convert(Ptr{openslide_t}, s), level, pointer(w), pointer(h))
    return [w,h]
end

function get_level_downsample(s::OSt, level)
    ccall( (:openslide_get_level_downsample, los),
            Cdouble,
            (Ptr{openslide_t}, Cint),
            s, level)
end

function get_best_level_for_downsample(s::OSt, factor::Cdouble)
    ccall( (:openslide_get_best_level_for_downsample, los),
            Cint, (OSt, Cdouble),
            s, factor)
end

function _read_region(img::OSt, data, x, y, level, w, h)
    ccall( (:openslide_read_region, los),
            Void,
            (OSt, Ptr{Cint}, Int64, Int64, Int32, Int64, Int64),
            img, data, x, y, int32(level-1), w, h)
end

function read_region(img::OSt, x, y, level, w, h)
    # allocate memory to hold output
    data = zeros(Uint32, w*h)
    _read_region(img, data, x, y, level, w, h)
    return _rgbfromrowflat(reinterpret(Uint8,data), [w, h])
end

function get_associated_image_names(s::OSt)
    buf = ccall( (:openslide_get_associated_image_names, los), Ptr{Ptr{Uint8}}, (OSt,))
    _readstrings(buf)
end

function get_associated_image_dimensions(s::OSt, name::ASCIIString)
    w = h = Int64[0]
    ccall( (:openslide_get_associated_image_dimensions, los),
            Void, (OSt, Ptr{Cchar}, Ptr{Clong}, Ptr{Clong}),
            s, name, w, h)
    return [w,h]
end

function read_associated_image(img::OSt, name::ASCIIString, dims)
    data = zeros(Uint32, *(dims...), 4)
    ccall( (:openslide_read_associated_image, los), Void,
            (OSt, Ptr{Cchar}, Ptr{Cuint}),
            osptr, name, data)
    return _rgbfromrowflat(data, dims)
end

function get_error(img::OSt)
    bytestring(ccall( (:openslide_get_error, los), Ptr{Uint8}, (OSt,), img))
end

function openslide_version()
    bytestring(ccall( (:openslide_get_version,los),Ptr{Uint8}, ()))
end


text:
macro endpoint(fun::Expr, epargs=:auto)
    fname = fun.args[1]
    fargs = fun.args[2:end]
    epargs === :auto && (epargs = Expr(:tuple, map(ex -> ex.args[1], fargs)...))

    ex = quote
        export $fname
        Base.@__doc__ $fname(f::Forge, $(fargs...); kwargs...) =
            request(f, $fname, endpoint(f, $fname, $epargs...); kwargs...)
    end

    esc(ex)
end

"""
    @json struct T ... end

Create a type that can be parsed from JSON.
"""
macro json(def::Expr)
    T = def.args[2]
    renames = Expr[]
    names = Symbol[]

    for field in def.args[3].args
        field isa Expr || continue
        if field.head === :(::)
            push!(names, field.args[1])
            # Make the field nullable.
            field.args[2] = :(Union{$(field.args[2]), Nothing})
        elseif field.head === :call && field.args[1] === :(=>)
            push!(names, field.args[2])
            # Convert from => to::F to to::F, and record the old name.
            from = QuoteNode(field.args[2])
            to, F = field.args[3].args
            field.head = :(::)
            field.args = [to, :(Union{$F, Nothing})]
            push!(renames, :($to => (; name=$from)))
        else
            @warn "Invalid field expression $field"
        end
    end

    # Add a field for unhandled keys.
    push!(def.args[3].args, :(_extras::NamedTuple))

    # Document the struct.
    def = :(Base.@__doc__ $def)

    # Create a keyword constructor.
    kws = map(name -> Expr(:kw, name, :nothing), names)
    cons = :($T(; $(kws...), kwargs...) = $T($(names...), (; kwargs...)))

    # Apply the kwargs format with any renames.
    fmt = :(JSON2.@format $T keywordargs)
    isempty(renames) || push!(fmt.args, Expr(:block, renames...))

    # Set the default parse options,
    dfkws = quote
        if isdefined(@__MODULE__, :JSON_OPTS)
            # This isn't how you're "supposed" to do this, but I'm not quite sure
            # how to pass these options as literal keywords to @format.
            JSON2.defaultkwargs(::Type{$T}) = JSON_OPTS
        end
    end

    esc(Expr(:block, def, cons, fmt, dfkws))
end


text:
########################################################################################
# Sampling from a solution
########################################################################################
"""Helper function to sample from our covariances, which often have a "cross" of zeros
For the 0-cov entries the outcome of the sampling is deterministic!"""
function _rand(x::Gaussian, n::Int=1)
    m, C = x.μ, x.Σ
    @assert C isa SRMatrix

    sample = m .+ C.squareroot * randn(length(m), n)
    return sample
end

function sample_states(sol::ProbODESolution, n::Int=1)
    @assert sol.interp.smooth "sampling not implemented for non-smoothed posteriors"
    return sample_states(sol.t, sol.x_filt, sol.diffusions, sol.t, sol.interp, n)
end
function sample(sol::ProbODESolution, n::Int=1)
    d, q = sol.interp.d, sol.interp.q
    sample_path = sample_states(sol, n)
    return sample_path[:, 1:q+1:d*(q+1), :]
end
function sample_states(ts, xs, diffusions, difftimes, posterior, n::Int=1)
    @assert length(diffusions) + 1 == length(difftimes)

    @unpack A, Q, d, q = posterior
    D = d * (q + 1)

    x = xs[end]
    sample = _rand(x, n)
    @assert size(sample) == (D, n)

    sample_path = zeros(length(ts), D, n)
    sample_path[end, :, :] .= sample
    # @info "final value and samples" x.μ sample sample_path[end, :]

    for i in length(xs)-1:-1:1
        dt = ts[i+1] - ts[i]

        i_diffusion = sum(difftimes .<= ts[i])
        diffusion = diffusions[i_diffusion]

        Qh = apply_diffusion(Q, diffusion)
        make_preconditioners!(posterior, dt)
        P, PI = posterior.P, posterior.PI

        for j in 1:n
            sample_p = P * sample_path[i+1, :, j]
            x_prev_p = P * xs[i]

            prev_sample_p, _ =
                smooth(x_prev_p, Gaussian(sample_p, SRMatrix(zeros(D, D))), A, Qh)

            # sample_path[i, :, j] .= PI*prev_sample_p.μ
            sample_path[i, :, j] .= PI * _rand(prev_sample_p)[:]
        end
    end

    return sample_path
end
function dense_sample_states(sol::ProbODESolution, n::Int=1; density=1000)
    @assert sol.interp.smooth "sampling not implemented for non-smoothed posteriors"
    times = range(sol.t[1], sol.t[end], length=density)
    states = StructArray([
        sol.interp(t, sol.t, sol.x_filt, sol.x_smooth, sol.diffusions; smoothed=false)
        for t in times
    ])

    return sample_states(times, states, sol.diffusions, sol.t, sol.interp, n), times
end
function dense_sample(sol::ProbODESolution, n::Int=1; density=1000)
    samples, times = dense_sample_states(sol, n; density=density)
    d, q = sol.interp.d, sol.interp.q
    return samples[:, 1:q+1:d*(q+1), :], times
end


text:
function line(ctx,x1,x2,y1,y2)
    move_to(ctx,x1,y1)
    line_to(ctx,x2,y2)
    nothing
end

function add_button_label(button,mylabel)
    b_label=Label(mylabel)
    Gtk.GAccessor.markup(b_label, string("""""",mylabel,""))
    push!(button,b_label)
    show(b_label)
end

function change_button_label(button,mylabel)
    hi=Gtk.GAccessor.child(button)
    Gtk.GAccessor.markup(hi, string("""""",mylabel,""))
end

function draw_box(x1,y1,x2,y2,mycolor,linewidth,ctx)
    move_to(ctx,x1,y1)
    line_to(ctx,x2,y1)
    line_to(ctx,x2,y2)
    line_to(ctx,x1,y2)
    line_to(ctx,x1,y1)
    set_source_rgb(ctx,mycolor[1],mycolor[2],mycolor[3])
    set_line_width(ctx,linewidth)
    stroke(ctx)
    nothing
end


text:
@testset "Testing URLs" begin
    years = [2009, 2013, 2018] # WOA product years
    vvs = ["p", "i", "n"] # nutrients only
    tts = [0, 1, 13] # Annual, 1 month and 1 season — no need to test every month and season
    ggs = ["5°", "1°", "0.25°"]
    ffs = ["mn", "an", "sd", "se"]

    @testset "WOA$(WOA.my_year(year))" for year in years
        @testset "$gg x $gg grid" for gg in ggs
            @testset "$(WOA.my_averaging_period(tt)) period" for tt in tts
                @testset "$(WOA.WOA_path_varname(vv)) tracer" for vv in vvs
                    ds = Dataset(WOA.NetCDF_path(year, vv, tt, gg))
                    @testset "$ff field" for ff in ffs
                        @test haskey(ds, WOA.WOA_varname(vv, ff))
                    end
                    @testset "dimensions" begin
                        @test haskey(ds, "lat")
                        @test haskey(ds, "lon")
                        @test haskey(ds, "depth")
                    end
                end
            end
        end
    end
end


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

mutable struct IoK8sApiFlowcontrolV1alpha1PriorityLevelConfigurationSpec <: SwaggerModel
    limited::Any # spec type: Union{ Nothing, IoK8sApiFlowcontrolV1alpha1LimitedPriorityLevelConfiguration } # spec name: limited
    type::Any # spec type: Union{ Nothing, String } # spec name: type

    function IoK8sApiFlowcontrolV1alpha1PriorityLevelConfigurationSpec(;limited=nothing, type=nothing)
        o = new()
        validate_property(IoK8sApiFlowcontrolV1alpha1PriorityLevelConfigurationSpec, Symbol("limited"), limited)
        setfield!(o, Symbol("limited"), limited)
        validate_property(IoK8sApiFlowcontrolV1alpha1PriorityLevelConfigurationSpec, Symbol("type"), type)
        setfield!(o, Symbol("type"), type)
        o
    end
end # type IoK8sApiFlowcontrolV1alpha1PriorityLevelConfigurationSpec

const _property_map_IoK8sApiFlowcontrolV1alpha1PriorityLevelConfigurationSpec = Dict{Symbol,Symbol}(Symbol("limited")=>Symbol("limited"), Symbol("type")=>Symbol("type"))
const _property_types_IoK8sApiFlowcontrolV1alpha1PriorityLevelConfigurationSpec = Dict{Symbol,String}(Symbol("limited")=>"IoK8sApiFlowcontrolV1alpha1LimitedPriorityLevelConfiguration", Symbol("type")=>"String")
Base.propertynames(::Type{ IoK8sApiFlowcontrolV1alpha1PriorityLevelConfigurationSpec }) = collect(keys(_property_map_IoK8sApiFlowcontrolV1alpha1PriorityLevelConfigurationSpec))
Swagger.property_type(::Type{ IoK8sApiFlowcontrolV1alpha1PriorityLevelConfigurationSpec }, name::Symbol) = Union{Nothing,eval(Base.Meta.parse(_property_types_IoK8sApiFlowcontrolV1alpha1PriorityLevelConfigurationSpec[name]))}
Swagger.field_name(::Type{ IoK8sApiFlowcontrolV1alpha1PriorityLevelConfigurationSpec }, property_name::Symbol) =  _property_map_IoK8sApiFlowcontrolV1alpha1PriorityLevelConfigurationSpec[property_name]

function check_required(o::IoK8sApiFlowcontrolV1alpha1PriorityLevelConfigurationSpec)
    (getproperty(o, Symbol("type")) === nothing) && (return false)
    true
end

function validate_property(::Type{ IoK8sApiFlowcontrolV1alpha1PriorityLevelConfigurationSpec }, name::Symbol, val)
end


text:
using BinaryProvider # requires BinaryProvider 0.3.0 or later

# Parse some basic command-line arguments
const verbose = "--verbose" in ARGS
const prefix = Prefix(get([a for a in ARGS if a != "--verbose"], 1, joinpath(@__DIR__, "usr")))
products = [
    LibraryProduct(prefix, String["libtiff"], :libtiff),
    LibraryProduct(prefix, String["libtiffxx"], :libtiffxx),
]

# Download binaries from hosted location
bin_prefix = "https://github.com/SimonDanisch/LibTIFFBuilder/releases/download/v1.0.0"

# Listing of files generated by BinaryBuilder:
download_info = Dict(
    Linux(:aarch64, :glibc) => ("$bin_prefix/libtiff.v4.0.9.aarch64-linux-gnu.tar.gz", "d4b5fc2aa7e62d07414a19ad980ab734b2eb5fecf9226d14322a2aaca31dd4ab"),
    Linux(:aarch64, :musl) => ("$bin_prefix/libtiff.v4.0.9.aarch64-linux-musl.tar.gz", "33db60c463f4acab9d6fe519a8ed5fc3366b126a6661106c338e491e03e51933"),
    Linux(:armv7l, :glibc, :eabihf) => ("$bin_prefix/libtiff.v4.0.9.arm-linux-gnueabihf.tar.gz", "98f91418ffb2556d78eeaca965618d7218cb52e3ac07450f1e2b7e8969d9fee5"),
    Linux(:armv7l, :musl, :eabihf) => ("$bin_prefix/libtiff.v4.0.9.arm-linux-musleabihf.tar.gz", "6a8df8fd463a1360ab4f58b6c69d26504f68ae136dd3b807d9fa25f2206ec1a2"),
    Linux(:i686, :glibc) => ("$bin_prefix/libtiff.v4.0.9.i686-linux-gnu.tar.gz", "56f02ceaab858b74cddf14593e73b677e8cbf1cb78d5611fe7f28a8f772d27fb"),
    Linux(:i686, :musl) => ("$bin_prefix/libtiff.v4.0.9.i686-linux-musl.tar.gz", "6e09eaa9d2e97465f07f01e1bb9f22b935ac89245dd5360b7206a8d39092417b"),
    Windows(:i686) => ("$bin_prefix/libtiff.v4.0.9.i686-w64-mingw32.tar.gz", "6bdbd2f9ab41e59cadacbd01309f345aa59bd9afdfcf935c8746ad58c35694e3"),
    Linux(:powerpc64le, :glibc) => ("$bin_prefix/libtiff.v4.0.9.powerpc64le-linux-gnu.tar.gz", "32854bc4c7286eb2b76a255a9a24e9dffa46b2a1056ff77f2e4f1759a71a2f52"),
    MacOS(:x86_64) => ("$bin_prefix/libtiff.v4.0.9.x86_64-apple-darwin14.tar.gz", "669c2164823590be90d3211d52a5934cec5cdd7923e73e853d7e42e3aa749e98"),
    Linux(:x86_64, :glibc) => ("$bin_prefix/libtiff.v4.0.9.x86_64-linux-gnu.tar.gz", "bc75574e1fbecd401e74f5d13c75eb101210ec7a7d1fef7e5ecc0ced33a5c532"),
    Linux(:x86_64, :musl) => ("$bin_prefix/libtiff.v4.0.9.x86_64-linux-musl.tar.gz", "8a70ae547730d5c3d0f230c47a02ca80241c491735043419c8a89ba516763d92"),
    FreeBSD(:x86_64) => ("$bin_prefix/libtiff.v4.0.9.x86_64-unknown-freebsd11.1.tar.gz", "aae1fc9eeebe7b0b6fdbaf4fe4f8d7e717e1ec6bcd72b87e4a65177cee3dee04"),
    Windows(:x86_64) => ("$bin_prefix/libtiff.v4.0.9.x86_64-w64-mingw32.tar.gz", "bfe319539672e344933041b9134289b6036961ea665016d0e080db0087cd641b"),
)

# Install unsatisfied or updated dependencies:
unsatisfied = any(!satisfied(p; verbose=verbose) for p in products)
if haskey(download_info, platform_key())
    url, tarball_hash = download_info[platform_key()]
    if unsatisfied || !isinstalled(url, tarball_hash; prefix=prefix)
        # Download and install binaries
        install(url, tarball_hash; prefix=prefix, force=true, verbose=verbose)
    end
elseif unsatisfied
    # If we don't have a BinaryProvider-compatible .tar.gz to download, complain.
    # Alternatively, you could attempt to install from a separate provider,
    # build from source or something even more ambitious here.
    error("Your platform $(triplet(platform_key())) is not supported by this package!")
end

# Write out a deps.jl file that will contain mappings for our products
write_deps_file(joinpath(@__DIR__, "deps_tiff.jl"), products)


text:
if !@isdefined(TabLevel)
    TabLevel = ""
end
println(TabLevel*"Open MajBase.jl")
TabLevel=TabLevel*"    "

import Base.convert
import Base.show
import Base.zero
import Base.isapprox
import Base.length
import Base.iterate

include("OpSqrt.jl")
include("OpStructs.jl")
include("OpAdd.jl")
include("OpMul.jl")
include("OpEqual.jl")
include("OpReduce.jl")
include("OpIsLess.jl")
include("OpScaleType.jl")
include("OpToStr.jl")
include("MajoranaWolfReps.jl")

MajScalar(x::Number)=MajoranaOp(x,fill(MajElem("a",1),0))

###Overloading multiplication and additions of majoranas

zero(x::MajoranaSp) = 0
zero(x::MajoranaOp) = 0

length(x::MajoranaSp) = 1
length(x::MajoranaOp) = 1

iterate(x::MajoranaSp) = (x,nothing)
iterate(x::MajoranaOp) = (x,nothing)
iterate(x::MajoranaSp,nothing) = nothing
iterate(x::MajoranaOp,nothing) = nothing

###Convert Between Marorna Sp and Op

convert(::Type{MajoranaOp}, x::Number) = MajScalar(x)
convert(::Type{MajoranaSp}, Op::MajoranaOp) = MajoranaSp([OpReduce(Op)],true)
convert(::Type{MajoranaSp}, Op::MajoranaSp) = MajoranaSp(Op.SpList)
function convert(::Type{MajoranaOp}, Op::MajoranaSp)
    if length(Op.SpList)==1
        return OpReduce(Op.SpList[1])
    else
        throw(DomainError("MajoranaSp=$Op contains more than one term"))
    end
end

###Copy a majorana
function OpCopy(a::MajoranaOp)
    ###Create a new marorana with a copy of the OpList of the old one
    return MajoranaOp(a.scale,copy(a.OpList),a.KetState)
end

function OpCopy(a::MajoranaSp)
    return MajoranaSp([OpCopy(x) for x in a.SpList],a.Reduced)
end

function OpProp(a::MajoranaOp,b::MajoranaOp)
    SameKet = (a.KetState == b.KetState)
    SameOps = (a.OpList == b.OpList)
    return SameKet && SameOps
end

function OpCheck(Elem::MajElem)
    if Elem.Type == "bx" || Elem.Type == "by" || Elem.Type == "bz" || Elem.Type == "c"
        return Elem
    else
        error("Unknown majorana type $Elem")
    end
end

TabLevel=TabLevel[1:end-4]
println(TabLevel*"Close MajornaBase.jl")


text:
using GenderDemoInertia
using Test
include("conftest.jl")

@testset "Test column name imports from column_names.jl" begin
    @test :deptn ∈ GenderDemoInertia.INTEGER_COLUMNS
    @test :scen ∈ GenderDemoInertia.DECORATOR_COLUMNS
    @test :runn ∈ GenderDemoInertia.UNSUMMARIZED_COLUMNS
end

@testset "Test import of model_demographic_inertia_gender.jl" begin
    # @test GenderDemoInertia.probability(3,4) = 7
    @test TESTDATA["hiring_rate_women_1"] == 0.2059
    @test TESTDATA["attrition_rate_women_2"] == 0.00
    @test size(GenderDemoInertia.build_simulation_results_array(2, 10)) == (20,94)
    @test GenderDemoInertia.demographic_inertia_simulation(TESTDATA, 100, 100)[1, :r_fattr1] == 0.0615
    #@test GenderDemoInertia.run_gender_inertia_simulation(TESTDATA, 2, 2)
end


text:
int main() {
    boolean b=true;
    while(b) return 0;
}

max_stars_repo_name: carlostome/Javalette-Compiler

max_issues_repo_name: carlostome/Javalette-Compiler

max_forks_repo_name: carlostome/Javalette-Compiler


text:
# OpenCV.jl tests (demos)
#################################################################################################

export run_demo

demos = [ "CreateImage",
        #   "ImageConversion",
        #   "Thresholding",
        #   "LiveVideo",
        #   "setVideoProperties",
        #   "LiveVideoWithTrackbars",
        #   "displayHistogram",
        #   "Drawing",
        #   "im2dots",
        #   "ObjectTracking"
          ]

println("\nSelect a demo from the following options: \n")

for i in enumerate(demos)
    println("\t", i[1], ") ", i[2])
end

println("\nSelect and run the demo at the julia prompt: \n","e.g., run_demo(N)\n")

function run_demo(i::Int)
    Base.include(@__MODULE__, string("./test/cxx/demo",i,"_",demos[i],".jl"))
end


text:
function show_results(dt, net)
    println("** Test set")
    println("Accuracy: ", accuracy(zip(dt.input_test, dt.output_test), net))
    println("Error rate: ", error_rate(zip(dt.input_test, dt.output_test), net))
    println("** Training set")
    println("Accuracy: ", accuracy(zip(dt.input_train, dt.output_train), net))
    println("Error rate: ", error_rate(zip(dt.input_train, dt.output_train), net))
end

function MLP_error_rate(nfeatures::Int, labels::Vector{<:Union{Int, Float64}},
        hidden_layers::Vector{Int}, nets_number::Int, train_data, test_data, epochs::Int)

    net_sets = get_net_sets(nfeatures, labels, hidden_layers, nets_number, train_data)
    nets = getindex.(net_sets, 1)
    inputs = getindex.(net_sets, 2)
    outputs = getindex.(net_sets, 3)

    map((n, in, out) -> fit!(n, in, out; max_epochs=epochs), nets, inputs, outputs)

    train_error_rate =  map(n -> error_rate(train_data, n), nets) |> mean
    test_error_rate = map(n -> error_rate(test_data, n), nets) |> mean

    println("Taxa erro final média (treinamento): ", train_error_rate)
    println("Taxa erro final média (test): ", test_error_rate)
end

max_stars_repo_name: Lucas-Muniz/MNEAT

max_issues_repo_name: Lucas-Muniz/MNEAT

max_forks_repo_name: Lucas-Muniz/MNEAT


text:
using JuMP, EAGO

                     m = Model()

                     EAGO.register_eago_operators!(m)

                     @variable(m, -1 <= x[i=1:2] <= 1)

                     @variable(m, -47.02611826463841 <= q <= 46.175694332378946)

                     add_NL_constraint(m, :(gelu(0.14172886209520552 + -0.7326244672203441*gelu(-0.9862473619768446 + 0.12598046880516867*gelu(-0.32432918385015697 + -0.6977940842525037*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.476420397288412*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + -0.5549201217740469*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + 0.4315951265237059*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2]))) + 0.9857820194451663*gelu(0.2633379906083797 + 0.3509284626355762*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.5977055959243147*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + -0.642253969451728*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + 0.10048605306401859*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2]))) + 0.3507087497777257*gelu(-0.34549165187553976 + 0.5367448324029058*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.7077894233575681*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + -0.4911236080946888*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + -0.5306931393323575*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2]))) + 0.16930171271231975*gelu(0.538919292477293 + 0.8088100362525972*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.4318478690072691*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + 0.8077402924106214*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + 0.12603114956525063*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2])))) + 0.6188053648075824*gelu(-0.8901994655270467 + 0.3517572387180481*gelu(-0.32432918385015697 + -0.6977940842525037*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.476420397288412*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + -0.5549201217740469*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + 0.4315951265237059*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2]))) + 0.5057680398491988*gelu(0.2633379906083797 + 0.3509284626355762*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.5977055959243147*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + -0.642253969451728*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + 0.10048605306401859*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2]))) + 0.15346000401268212*gelu(-0.34549165187553976 + 0.5367448324029058*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.7077894233575681*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + -0.4911236080946888*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + -0.5306931393323575*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2]))) + 0.000907155550359029*gelu(0.538919292477293 + 0.8088100362525972*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.4318478690072691*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + 0.8077402924106214*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + 0.12603114956525063*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2])))) + 0.748255673773524*gelu(0.9418689270026719 + 0.23440750676702393*gelu(-0.32432918385015697 + -0.6977940842525037*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.476420397288412*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + -0.5549201217740469*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + 0.4315951265237059*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2]))) + -0.9578891219409944*gelu(0.2633379906083797 + 0.3509284626355762*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.5977055959243147*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + -0.642253969451728*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + 0.10048605306401859*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2]))) + -0.4332120963929875*gelu(-0.34549165187553976 + 0.5367448324029058*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.7077894233575681*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + -0.4911236080946888*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + -0.5306931393323575*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2]))) + 0.15216088947964046*gelu(0.538919292477293 + 0.8088100362525972*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.4318478690072691*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + 0.8077402924106214*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + 0.12603114956525063*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2])))) + -0.19681615050825796*gelu(-0.3160427191298667 + -0.1453900085539872*gelu(-0.32432918385015697 + -0.6977940842525037*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.476420397288412*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + -0.5549201217740469*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + 0.4315951265237059*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2]))) + 0.3370407689400481*gelu(0.2633379906083797 + 0.3509284626355762*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.5977055959243147*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + -0.642253969451728*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + 0.10048605306401859*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2]))) + 0.5646332930109117*gelu(-0.34549165187553976 + 0.5367448324029058*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.7077894233575681*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + -0.4911236080946888*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + -0.5306931393323575*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2]))) + -0.4312398718758548*gelu(0.538919292477293 + 0.8088100362525972*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.4318478690072691*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + 0.8077402924106214*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + 0.12603114956525063*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2]))))) + gelu(0.7126847484534728 + 0.5521736820641339*gelu(-0.9862473619768446 + 0.12598046880516867*gelu(-0.32432918385015697 + -0.6977940842525037*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.476420397288412*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + -0.5549201217740469*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + 0.4315951265237059*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2]))) + 0.9857820194451663*gelu(0.2633379906083797 + 0.3509284626355762*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.5977055959243147*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + -0.642253969451728*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + 0.10048605306401859*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2]))) + 0.3507087497777257*gelu(-0.34549165187553976 + 0.5367448324029058*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.7077894233575681*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + -0.4911236080946888*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + -0.5306931393323575*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2]))) + 0.16930171271231975*gelu(0.538919292477293 + 0.8088100362525972*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.4318478690072691*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + 0.8077402924106214*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + 0.12603114956525063*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2])))) + -0.5863621462894022*gelu(-0.8901994655270467 + 0.3517572387180481*gelu(-0.32432918385015697 + -0.6977940842525037*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.476420397288412*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + -0.5549201217740469*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + 0.4315951265237059*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2]))) + 0.5057680398491988*gelu(0.2633379906083797 + 0.3509284626355762*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.5977055959243147*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + -0.642253969451728*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + 0.10048605306401859*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2]))) + 0.15346000401268212*gelu(-0.34549165187553976 + 0.5367448324029058*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.7077894233575681*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + -0.4911236080946888*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + -0.5306931393323575*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2]))) + 0.000907155550359029*gelu(0.538919292477293 + 0.8088100362525972*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.4318478690072691*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + 0.8077402924106214*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + 0.12603114956525063*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2])))) + -0.2365722039484086*gelu(0.9418689270026719 + 0.23440750676702393*gelu(-0.32432918385015697 + -0.6977940842525037*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.476420397288412*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + -0.5549201217740469*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + 0.4315951265237059*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2]))) + -0.9578891219409944*gelu(0.2633379906083797 + 0.3509284626355762*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.5977055959243147*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + -0.642253969451728*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + 0.10048605306401859*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2]))) + -0.4332120963929875*gelu(-0.34549165187553976 + 0.5367448324029058*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.7077894233575681*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + -0.4911236080946888*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + -0.5306931393323575*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2]))) + 0.15216088947964046*gelu(0.538919292477293 + 0.8088100362525972*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.4318478690072691*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + 0.8077402924106214*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + 0.12603114956525063*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2])))) + -0.47134077688752996*gelu(-0.3160427191298667 + -0.1453900085539872*gelu(-0.32432918385015697 + -0.6977940842525037*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.476420397288412*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + -0.5549201217740469*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + 0.4315951265237059*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2]))) + 0.3370407689400481*gelu(0.2633379906083797 + 0.3509284626355762*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.5977055959243147*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + -0.642253969451728*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + 0.10048605306401859*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2]))) + 0.5646332930109117*gelu(-0.34549165187553976 + 0.5367448324029058*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.7077894233575681*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + -0.4911236080946888*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + -0.5306931393323575*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2]))) + -0.4312398718758548*gelu(0.538919292477293 + 0.8088100362525972*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.4318478690072691*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + 0.8077402924106214*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + 0.12603114956525063*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2]))))) + gelu(0.3678622626620536 + -0.645924933237755*gelu(-0.9862473619768446 + 0.12598046880516867*gelu(-0.32432918385015697 + -0.6977940842525037*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.476420397288412*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + -0.5549201217740469*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + 0.4315951265237059*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2]))) + 0.9857820194451663*gelu(0.2633379906083797 + 0.3509284626355762*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.5977055959243147*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + -0.642253969451728*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + 0.10048605306401859*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2]))) + 0.3507087497777257*gelu(-0.34549165187553976 + 0.5367448324029058*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.7077894233575681*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + -0.4911236080946888*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + -0.5306931393323575*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2]))) + 0.16930171271231975*gelu(0.538919292477293 + 0.8088100362525972*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.4318478690072691*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + 0.8077402924106214*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + 0.12603114956525063*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2])))) + 0.23980134898526861*gelu(-0.8901994655270467 + 0.3517572387180481*gelu(-0.32432918385015697 + -0.6977940842525037*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.476420397288412*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + -0.5549201217740469*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + 0.4315951265237059*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2]))) + 0.5057680398491988*gelu(0.2633379906083797 + 0.3509284626355762*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.5977055959243147*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + -0.642253969451728*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + 0.10048605306401859*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2]))) + 0.15346000401268212*gelu(-0.34549165187553976 + 0.5367448324029058*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.7077894233575681*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + -0.4911236080946888*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + -0.5306931393323575*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2]))) + 0.000907155550359029*gelu(0.538919292477293 + 0.8088100362525972*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.4318478690072691*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + 0.8077402924106214*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + 0.12603114956525063*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2])))) + 0.5641271464877478*gelu(0.9418689270026719 + 0.23440750676702393*gelu(-0.32432918385015697 + -0.6977940842525037*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.476420397288412*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + -0.5549201217740469*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + 0.4315951265237059*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2]))) + -0.9578891219409944*gelu(0.2633379906083797 + 0.3509284626355762*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.5977055959243147*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + -0.642253969451728*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + 0.10048605306401859*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2]))) + -0.4332120963929875*gelu(-0.34549165187553976 + 0.5367448324029058*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.7077894233575681*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + -0.4911236080946888*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + -0.5306931393323575*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2]))) + 0.15216088947964046*gelu(0.538919292477293 + 0.8088100362525972*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.4318478690072691*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + 0.8077402924106214*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + 0.12603114956525063*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2])))) + -0.22456183587218126*gelu(-0.3160427191298667 + -0.1453900085539872*gelu(-0.32432918385015697 + -0.6977940842525037*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.476420397288412*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + -0.5549201217740469*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + 0.4315951265237059*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2]))) + 0.3370407689400481*gelu(0.2633379906083797 + 0.3509284626355762*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.5977055959243147*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + -0.642253969451728*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + 0.10048605306401859*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2]))) + 0.5646332930109117*gelu(-0.34549165187553976 + 0.5367448324029058*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.7077894233575681*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + -0.4911236080946888*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + -0.5306931393323575*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2]))) + -0.4312398718758548*gelu(0.538919292477293 + 0.8088100362525972*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.4318478690072691*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + 0.8077402924106214*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + 0.12603114956525063*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2]))))) + gelu(-0.9861590919257504 + -0.9031060096581198*gelu(-0.9862473619768446 + 0.12598046880516867*gelu(-0.32432918385015697 + -0.6977940842525037*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.476420397288412*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + -0.5549201217740469*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + 0.4315951265237059*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2]))) + 0.9857820194451663*gelu(0.2633379906083797 + 0.3509284626355762*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.5977055959243147*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + -0.642253969451728*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + 0.10048605306401859*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2]))) + 0.3507087497777257*gelu(-0.34549165187553976 + 0.5367448324029058*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.7077894233575681*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + -0.4911236080946888*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + -0.5306931393323575*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2]))) + 0.16930171271231975*gelu(0.538919292477293 + 0.8088100362525972*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.4318478690072691*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + 0.8077402924106214*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + 0.12603114956525063*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2])))) + -0.6492392304855641*gelu(-0.8901994655270467 + 0.3517572387180481*gelu(-0.32432918385015697 + -0.6977940842525037*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.476420397288412*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + -0.5549201217740469*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + 0.4315951265237059*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2]))) + 0.5057680398491988*gelu(0.2633379906083797 + 0.3509284626355762*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.5977055959243147*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + -0.642253969451728*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + 0.10048605306401859*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2]))) + 0.15346000401268212*gelu(-0.34549165187553976 + 0.5367448324029058*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.7077894233575681*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + -0.4911236080946888*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + -0.5306931393323575*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2]))) + 0.000907155550359029*gelu(0.538919292477293 + 0.8088100362525972*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.4318478690072691*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + 0.8077402924106214*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + 0.12603114956525063*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2])))) + 0.1540584284169868*gelu(0.9418689270026719 + 0.23440750676702393*gelu(-0.32432918385015697 + -0.6977940842525037*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.476420397288412*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + -0.5549201217740469*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + 0.4315951265237059*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2]))) + -0.9578891219409944*gelu(0.2633379906083797 + 0.3509284626355762*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.5977055959243147*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + -0.642253969451728*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + 0.10048605306401859*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2]))) + -0.4332120963929875*gelu(-0.34549165187553976 + 0.5367448324029058*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.7077894233575681*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + -0.4911236080946888*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + -0.5306931393323575*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2]))) + 0.15216088947964046*gelu(0.538919292477293 + 0.8088100362525972*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.4318478690072691*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + 0.8077402924106214*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + 0.12603114956525063*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2])))) + -0.8682585596517867*gelu(-0.3160427191298667 + -0.1453900085539872*gelu(-0.32432918385015697 + -0.6977940842525037*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.476420397288412*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + -0.5549201217740469*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + 0.4315951265237059*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2]))) + 0.3370407689400481*gelu(0.2633379906083797 + 0.3509284626355762*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.5977055959243147*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + -0.642253969451728*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + 0.10048605306401859*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2]))) + 0.5646332930109117*gelu(-0.34549165187553976 + 0.5367448324029058*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.7077894233575681*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + -0.4911236080946888*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + -0.5306931393323575*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2]))) + -0.4312398718758548*gelu(0.538919292477293 + 0.8088100362525972*gelu(-0.9860262540836815 + 0.8911186935536937*$(x[1]) + 0.64267061852934*$(x[2])) + -0.4318478690072691*gelu(-0.12607269491856643 + -0.6901389567897818*$(x[1]) + -0.5431979251870089*$(x[2])) + 0.8077402924106214*gelu(0.4882924486844056 + 0.5602141072539029*$(x[1]) + 0.7222626702909976*$(x[2])) + 0.12603114956525063*gelu(-0.9654866490330036 + -0.27186143772128135*$(x[1]) + -0.864410033347212*$(x[2]))))) - $q <= 0.0))

                     @objective(m, Min, q)

                     return m

max_stars_repo_name: PSORLab/RSActivationFunctions

max_issues_repo_name: PSORLab/RSActivationFunctions

max_forks_repo_name: PSORLab/RSActivationFunctions


text:
export MIS2, MIS3C, MIS4, MIS4a, TVDMISA, TVDMISB

"""
    TimeScaledRHS(a, b, rhs!)

When evaluate at time `t`, evaluates `rhs!` at time `a + bt`.
"""
mutable struct TimeScaledRHS{RT}
    a::RT
    b::RT
    rhs!
end

function (o::TimeScaledRHS)(dQ, Q, params, tau; increment)
    o.rhs!(dQ, Q, params, o.a + o.b * tau; increment = increment)
end

"""
MultirateInfinitesimalStep(slowrhs!, fastrhs!, fastmethod,
                           α, β, γ,
                           Q::AT; dt=0, t0=0) where {AT<:AbstractArray}

This is a time stepping object for explicitly time stepping the partitioned differential
equation given by right-hand-side functions `f_fast` and `f_slow` with the state `Q`, i.e.,

```math
  \\dot{Q} = f_fast(Q, t) + f_slow(Q, t)
```

with the required time step size `dt` and optional initial time `t0`.  This
time stepping object is intended to be passed to the `solve!` command.

The constructor builds a multirate infinitesimal step Runge-Kutta scheme
based on the provided `α`, `β` and `γ` tableaux and `fastmethod` for solving
the fast modes.

### References
    @article{KnothWensch2014,
      title={Generalized split-explicit Runge--Kutta methods for the compressible Euler equations},
      author={Knoth, Oswald and Wensch, Joerg},
      journal={Monthly Weather Review},
      volume={142},
      number={5},
      pages={2067--2081},
      year={2014}
    }
"""
mutable struct MultirateInfinitesimalStep{
    T,
    RT,
    AT,
    FS,
    Nstages,
    Nstagesm1,
    Nstagesm2,
    Nstages_sq,
} <: AbstractODESolver
    "time step"
    dt::RT
    "time"
    t::RT
    "elapsed time steps"
    steps::Int
    "storage for y_n"
    yn::AT
    "Storage for ``Y_nj - y_n``"
    ΔYnj::NTuple{Nstagesm2, AT}
    "Storage for ``f(Y_nj)``"
    fYnj::NTuple{Nstagesm1, AT}
    "Storage for offset"
    offset::AT
    "slow rhs function"
    slowrhs!
    "RHS for fast solver"
    tsfastrhs!::TimeScaledRHS{RT}
    "fast rhs method"
    fastsolver::FS
    "number of substeps per stage"
    nsubsteps::Int
    α::SArray{NTuple{2, Nstages}, RT, 2, Nstages_sq}
    β::SArray{NTuple{2, Nstages}, RT, 2, Nstages_sq}
    γ::SArray{NTuple{2, Nstages}, RT, 2, Nstages_sq}
    d::SArray{NTuple{1, Nstages}, RT, 1, Nstages}
    c::SArray{NTuple{1, Nstages}, RT, 1, Nstages}
    c̃::SArray{NTuple{1, Nstages}, RT, 1, Nstages}
    function MultirateInfinitesimalStep(
        slowrhs!,
        fastrhs!,
        fastmethod,
        nsubsteps,
        α,
        β,
        γ,
        Q::AT;
        dt = 0,
        t0 = 0,
    ) where {AT <: AbstractArray}

        T = eltype(Q)
        RT = real(T)

        Nstages = size(α, 1)

        yn = similar(Q)
        ΔYnj = ntuple(_ -> similar(Q), Nstages - 2)
        fYnj = ntuple(_ -> similar(Q), Nstages - 1)
        offset = similar(Q)
        tsfastrhs! = TimeScaledRHS(RT(0), RT(0), fastrhs!)
        fastsolver = fastmethod(tsfastrhs!, Q)

        d = sum(β, dims = 2)

        c = similar(d)
        for i in eachindex(c)
            c[i] = d[i]
            if i > 1
                c[i] += sum(j -> (α[i, j] + γ[i, j]) * c[j], 1:(i - 1))
            end
        end
        c̃ = α * c

        new{
            T,
            RT,
            AT,
            typeof(fastsolver),
            Nstages,
            Nstages - 1,
            Nstages - 2,
            Nstages^2,
        }(
            RT(dt),
            RT(t0),
            0,
            yn,
            ΔYnj,
            fYnj,
            offset,
            slowrhs!,
            tsfastrhs!,
            fastsolver,
            nsubsteps,
            α,
            β,
            γ,
            d,
            c,
            c̃,
        )
    end
end

function dostep!(Q, mis::MultirateInfinitesimalStep, p, time)
    dt = mis.dt
    FT = eltype(dt)
    α = mis.α
    β = mis.β
    γ = mis.γ
    yn = mis.yn
    ΔYnj = mis.ΔYnj
    fYnj = mis.fYnj
    offset = mis.offset
    d = mis.d
    c = mis.c
    c̃ = mis.c̃
    slowrhs! = mis.slowrhs!
    fastsolver = mis.fastsolver
    fastrhs! = mis.tsfastrhs!

    nstages = size(α, 1)

    copyto!(yn, Q) # first stage
    for i in 2:nstages
        slowrhs!(fYnj[i - 1], Q, p, time + c[i - 1] * dt, increment = false)

        groupsize = 256
        event = Event(array_device(Q))
        event = update!(array_device(Q), groupsize)(
            realview(Q),
            realview(offset),
            Val(i),
            realview(yn),
            map(realview, ΔYnj[1:(i - 2)]),
            map(realview, fYnj[1:(i - 1)]),
            α[i, :],
            β[i, :],
            γ[i, :],
            d[i],
            dt;
            ndrange = length(realview(Q)),
            dependencies = (event,),
        )
        wait(array_device(Q), event)

        fastrhs!.a = time + c̃[i] * dt
        fastrhs!.b = (c[i] - c̃[i]) / d[i]

        τ = zero(FT)
        dτ = d[i] * dt / mis.nsubsteps
        updatetime!(fastsolver, τ)
        updatedt!(fastsolver, dτ)
        # TODO: we want to be able to write
        #   solve!(Q, fastsolver, p; numberofsteps = mis.nsubsteps)  #(1c)
        # especially if we want to use StormerVerlet, but need some way to pass in `offset`
        updatedt!(fastsolver, dτ)
        for k in 1:(mis.nsubsteps)
            dostep!(Q, fastsolver, p, τ, FT(1), realview(offset))  #(1c)
            τ += dτ
        end
    end
end

@kernel function update!(
    Q,
    offset,
    ::Val{i},
    yn,
    ΔYnj,
    fYnj,
    αi,
    βi,
    γi,
    d_i,
    dt,
) where {i}
    e = @index(Global, Linear)
    @inbounds begin
        if i > 2
            ΔYnj[i - 2][e] = Q[e] - yn[e] # is 0 for i == 2
        end
        Q[e] = yn[e] # (1a)
        offset[e] = (βi[1] / d_i) .* fYnj[1][e] # (1b)
        @unroll for j in 2:(i - 1)
            Q[e] += αi[j] .* ΔYnj[j - 1][e] # (1a cont.)
            offset[e] +=
                (γi[j] / (d_i * dt)) * ΔYnj[j - 1][e] +
                (βi[j] / d_i) * fYnj[j][e] # (1b cont.)
        end
    end
end

function MIS2(
    slowrhs!,
    fastrhs!,
    fastmethod,
    nsubsteps,
    Q::AT;
    dt = 0,
    t0 = 0,
) where {AT <: AbstractArray}
    α = [
        0 0 0 0
        0 0 0 0
        0 0.536946566710 0 0
        0 0.480892968551 0.500561163566 0
    ]

    β = [
        0 0 0 0
        0.126848494553 0 0 0
        -0.784838278826 1.37442675268 0 0
        -0.0456727081749 -0.00875082271190 0.524775788629 0
    ]

    γ = [
        0 0 0 0
        0 0 0 0
        0 0.652465126004 0 0
        0 -0.0732769849457 0.144902430420 0
    ]

    MultirateInfinitesimalStep(
        slowrhs!,
        fastrhs!,
        fastmethod,
        nsubsteps,
        α,
        β,
        γ,
        Q;
        dt = dt,
        t0 = t0,
    )
end

function MIS3C(
    slowrhs!,
    fastrhs!,
    fastmethod,
    nsubsteps,
    Q::AT;
    dt = 0,
    t0 = 0,
) where {AT <: AbstractArray}
    α = [
        0 0 0 0
        0 0 0 0
        0 0.589557277145 0 0
        0 0.544036601551 0.565511042564 0
    ]

    β = [
        0 0 0 0
        0.397525189225 0 0 0
        -0.227036463644 0.624528794618 0 0
        -0.00295238076840 -0.270971764284 0.671323159437 0
    ]

    γ = [
        0 0 0 0
        0 0 0 0
        0 0.142798786398 0 0
        0 -0.0428918957402 0.0202720980282 0
    ]

    MultirateInfinitesimalStep(
        slowrhs!,
        fastrhs!,
        fastmethod,
        nsubsteps,
        α,
        β,
        γ,
        Q;
        dt = dt,
        t0 = t0,
    )
end

function MIS4(
    slowrhs!,
    fastrhs!,
    fastmethod,
    nsubsteps,
    Q::AT;
    dt = 0,
    t0 = 0,
) where {AT <: AbstractArray}
    α = [
        0 0 0 0 0
        0 0 0 0 0
        0 0.914092810304 0 0 0
        0 1.14274417397 -0.295211246188 0 0
        0 0.112965282231 0.337369411296 0.503747183119 0
    ]

    β = [
        0 0 0 0 0
        0.136296478423 0 0 0 0
        0.280462398979 -0.0160351333596 0 0 0
        0.904713355208 -1.04011183154 0.652337563489 0 0
        0.0671969845546 -0.365621862610 -0.154861470835 0.970362444469 0
    ]

    γ = [
        0 0 0 0 0
        0 0 0 0 0
        0 0.678951983291 0 0 0
        0 -1.38974164070 0.503864576302 0 0
        0 -0.375328608282 0.320925021109 -0.158259688945 0
    ]

    MultirateInfinitesimalStep(
        slowrhs!,
        fastrhs!,
        fastmethod,
        nsubsteps,
        α,
        β,
        γ,
        Q;
        dt = dt,
        t0 = t0,
    )
end

function MIS4a(
    slowrhs!,
    fastrhs!,
    fastmethod,
    nsubsteps,
    Q::AT;
    dt = 0,
    t0 = 0,
) where {AT <: AbstractArray}
    α = [
        0 0 0 0 0
        0 0 0 0 0
        0 0.52349249922385610 0 0 0
        0 1.1683374366893629 -0.75762080241712637 0 0
        0 -0.036477233846797109 0.56936148730740477 0.47746263002599681 0
    ]

    # β[5,1] in the paper is incorrect
    # the correct value is used below (from authors)
    β = [
        0 0 0 0 0
        0.38758444641450318 0 0 0 0
        -0.025318448354142823 0.38668943087310403 0 0 0
        0.20899983523553325 -0.45856648476371231 0.43423187573425748 0 0
        -0.10048822195663100 -0.46186171956333327 0.83045062122462809 0.27014914900250392 0
    ]

    γ = [
        0 0 0 0 0
        0 0 0 0 0
        0 0.13145089796226542 0 0 0
        0 -0.36855857648747881 0.33159232636600550 0 0
        0 -0.065767130537473045 0.040591093109036858 0.064902111640806712 0
    ]

    MultirateInfinitesimalStep(
        slowrhs!,
        fastrhs!,
        fastmethod,
        nsubsteps,
        α,
        β,
        γ,
        Q;
        dt = dt,
        t0 = t0,
    )
end

function TVDMISA(
    slowrhs!,
    fastrhs!,
    fastmethod,
    nsubsteps,
    Q::AT;
    dt = 0,
    t0 = 0,
) where {AT <: AbstractArray}
    FT = eltype(Q)
    RT = real(FT)

    α = [
        0 0 0 0
        0 0 0 0
        0 0.1946360605647457 0 0
        0 0.3971200136786614 0.2609434606211801 0
    ]

    β = [
        0 0 0 0
        RT(2 // 3) 0 0 0
        -0.28247174703488398 RT(4 // 9) 0 0
        -0.31198081960042401 0.18082737579913699 RT(9 // 16) 0
    ]

    γ = [
        0 0 0 0
        0 0 0 0
        0 0.5624048933209129 0 0
        0 0.4408467475713277 -0.2459300561692391 0
    ]

    MultirateInfinitesimalStep(
        slowrhs!,
        fastrhs!,
        fastmethod,
        nsubsteps,
        α,
        β,
        γ,
        Q;
        dt = dt,
        t0 = t0,
    )
end

function TVDMISB(
    slowrhs!,
    fastrhs!,
    fastmethod,
    nsubsteps,
    Q::AT;
    dt = 0,
    t0 = 0,
) where {AT <: AbstractArray}
    FT = eltype(Q)
    RT = real(FT)

    α = [
        0 0 0 0
        0 0 0 0
        0 0.42668232863311001 0 0
        0 0.26570779016173801 0.41489966891866698 0
    ]

    β = [
        0 0 0 0
        RT(2 // 3) 0 0 0
        -0.25492859100078202 RT(4 // 9) 0 0
        -0.26452517179288798 0.11424084424766399 RT(9 // 16) 0
    ]

    γ = [
        0 0 0 0
        0 0 0 0
        0 0.28904389120139701 0 0
        0 0.45113560071334202 -0.25006656847591002 0
    ]

    MultirateInfinitesimalStep(
        slowrhs!,
        fastrhs!,
        fastmethod,
        nsubsteps,
        α,
        β,
        γ,
        Q;
        dt = dt,
        t0 = t0,
    )
end

max_stars_repo_name: mwarusz/CLIMA

max_issues_repo_name: mwarusz/CLIMA

max_forks_repo_name: mwarusz/CLIMA


text:
#
# These work
#

@Base.ccallable Float64 myabs(x::Float64) = abs(x)
@Base.ccallable Float64 myfun1(x::Float64) = sum((x, x, 1.0))

#
# These are quirky
#

# @Base.ccallable Float64 myfun2(x::Float64) = sum(Float64[x, x, 1.0]) # Need to replace _jlplt_alloc_array_1d_XX with _alloc_array_1d in JS
# @Base.ccallable Float64 myfun3(x::Float64) = myfun2(x)
# @Base.ccallable Float64 myfun4(x::Float64) = sum((abs(x), asin(x), tan(x))) # Need to replace _jlplt_asin_XX and _jlplt_tan_XX with Math_asin and Math_tan in JS

#
# These are broken
#

# @Base.ccallable Void    hi() = (println("hello world");nothing)
# @Base.ccallable Cstring hi1() = Vector{UInt8}("hello world")  # If _jlplt_string_to_array_XX is replace by _jl_string_to_array, returns something, but it's not a string

# @Base.ccallable Void function testio(x::Float64)
#    open("test.dat", "w") do io
#        println(io, 2x)
#    end
#    # y = open("test.dat") do io
#    #     readlines(io)
#    # end
#    nothing
#end
# @Base.ccallable function jl_test_returns_float()::Float64
#         return 42
# end
# @Base.ccallable Float64 function nonsense()
#     # ccall("Xllvm.nvvm.read.ptx.sreg.tid.x", llvmcall, Int32, ())
#     # ccall("junk",Float64,())
#     Base.llvmcall(
#         (""" declare double @jl_test_returns_float()""",
#         """
#         %1 = call double @jl_test_returns_float()
#         ret double %1
#         """),Float64,Tuple{})
# end

#
# Attempt to print out the internal llvm function names.
# Ordering changes may mess these up.
#

function showname(fun, types)
    io = PipeBuffer()
    code_llvm(io, fun, types)
    println(readlines(io)[2])
    nothing
end
showname(fun) = showname(fun, (Float64,))

# showname.((myabs, myfun1, myfun2, myfun3, myfun4))
# showname(hi, ())
# showname(hi1, ())
# showname(testio)
# showname(nonsense, ())