text:
@require NDSparseData begin
using NDSparseData: NDSparse

immutable EnumerableNDSparseData{T, S<:NDSparse} <: Enumerable{T}
    source::S
end

immutable NDSparseDataRow{TIndex,TValue}
    index::TIndex
    value::TValue
end

function query{S<:NDSparse}(source::S)
    TValue = S.parameters[1]
    if S.parameters[3]<:NamedTuples.NamedTuple
        col_expressions = Array{Expr,1}()
        columns_tuple_type = Expr(:curly, :Tuple)

        for (i,fieldname) in enumerate(fieldnames(S.parameters[3]))
            col_type = S.parameters[2].parameters[i]
            push!(col_expressions, Expr(:(::), fieldname, col_type))
            push!(columns_tuple_type.args, col_type)
        end
        t_expr = NamedTuples.make_tuple(col_expressions)
        TIndex = eval(NamedTuples, t_expr)
    else
        TIndex = S.parameters[2]
    end

    e_df = EnumerableNDSparseData{NDSparseDataRow{TIndex,TValue},S}(source)

    return e_df
end

#function length{T, S<:DataStreams.Data.Source, TC}(iter::EnumerableDataStream{T,S,TC})
#    return iter.schema.rows
#end

#function eltype{T, S<:DataStreams.Data.Source, TC}(iter::EnumerableDataStream{T,S,TC})
#    return T
#end

function start{T,S<:NDSparse}(iter::EnumerableNDSparseData{T,S})
    return 1
end

@generated function next{T,S<:NDSparse}(iter::EnumerableNDSparseData{T,S}, state)
    if T.parameters[1]<:NamedTuples.NamedTuple
        constructor_call = Expr(:call, :NDSparseDataRow, Expr(:call,T.parameters[1]),:(iter.source.data[row]))
        for i in 1:length(S.parameters[2].parameters)
            push!(constructor_call.args[2].args, :( iter.source.index.columns[$i][row] ))
        end
    else
        constructor_call = Expr(:call, :NDSparseDataRow,:((1,)),:(iter.source.data[row]))
        constructor_call.args[2].args[1] = :( iter.source.index.columns[1][row] )
        for i in 2:length(S.parameters[2].parameters)
            push!(constructor_call.args[2].args, :( iter.source.index.columns[$i][row] ))
        end
    end

    quote
    	source = iter.source
        row = state
        a = $constructor_call
        return a, state+1
    end
end

function done{T,S<:NDSparse}(iter::EnumerableNDSparseData{T,S}, state)
    return state>length(iter.source)
end

end


text:
# Tests for the total correlation function

# Test total correlation formula
@test get_total_correlation(arr1, arr2, arr3) ≈ get_entropy(arr1) + get_entropy(arr2) + get_entropy(arr3) - get_entropy(arr1, arr2, arr3)
println("Total correlation formula passed.")

ext: jl


text:
include("../../MaximinOPF/src/MaximinOPF.jl")
using PowerModels
using JuMP
using SCS
using Ipopt
using ProxSDP
PowerModels.silence()

function SolveFP(pm_data,pm_form,pm_optimizer; x_vals=Dict{Int64,Float64}() )
  pm = MaximinOPF.PF_FeasModel(pm_data, pm_form, x_vals)
  JuMP.set_optimizer(pm.model,pm_optimizer)
  JuMP.optimize!(pm.model)
  status=JuMP.termination_status(pm.model)
  if status != OPTIMAL
    println("FLAGGING: Solve status=",status)
  end
  return pm
end

testcase = Dict(
	"file" => "data/case9.m",
	"PMOption" => SparseSDPWRMPowerModel,
 	"name" => "case9K3ACR",
 	"attack_budget" => 0,
 	"inactive_indices" => [1,4,7],
 	"protected_indices" => []
	)

pm_data = PowerModels.parse_file(testcase["file"])
pm_data["attacker_budget"] = testcase["attack_budget"] ###Adding another key and entry
pm_data["inactive_branches"] = testcase["inactive_indices"] ###Adding another key and entry
pm_data["protected_branches"] = testcase["protected_indices"] ###Adding another key and entry

sdp_solver=with_optimizer(ProxSDP.Optimizer, log_verbose=false, tol_primal=1e-6, tol_dual=1e-6 )
#sdp_solver=with_optimizer(Mosek.Optimizer,MSK_IPAR_LOG=0)
#conic_solver=with_optimizer(Mosek.Optimizer,MSK_IPAR_LOG=0)
conic_solver=with_optimizer(SCS.Optimizer,verbose=0)
ip_solver=with_optimizer(Ipopt.Optimizer,print_level=0)

# nonconvex AC forms
nonconvex_ac=[ACPPowerModel, ACRPowerModel, ACTPowerModel]
for pm_form in nonconvex_ac
    println("Formulating and solving the form ",pm_form)
    pm = MaximinOPF.PF_FeasModel(pm_data, pm_form)
    JuMP.set_optimizer(pm.model,ip_solver)
    JuMP.optimize!(pm.model)
    println("\tOptimal value using powerform ", pm_form, " is: ",JuMP.objective_value(pm.model), "with status ",JuMP.termination_status(pm.model))
end

# linear approximations
linear_approx=[DCPPowerModel, DCMPPowerModel, NFAPowerModel]
for pm_form in linear_approx
    println("Formulating and solving the form ",pm_form)
    pm = MaximinOPF.PF_FeasModel(pm_data, pm_form)
    JuMP.set_optimizer(pm.model,conic_solver)
    JuMP.optimize!(pm.model)
    println("\tOptimal value using powerform ", pm_form, " is: ",JuMP.objective_value(pm.model), "with status ",JuMP.termination_status(pm.model))
end

# quadratic approximations
quadratic_approx=[DCPLLPowerModel, LPACCPowerModel]
for pm_form in quadratic_approx
    println("Formulating and solving the form ",pm_form)
    pm = MaximinOPF.PF_FeasModel(pm_data, pm_form)
    JuMP.set_optimizer(pm.model,ip_solver)
    JuMP.optimize!(pm.model)
    println("\tOptimal value using powerform ", pm_form, " is: ",JuMP.objective_value(pm.model), "with status ",JuMP.termination_status(pm.model))
end
# quadratic relaxations
quadratic_relax=[SOCWRPowerModel, SOCBFPowerModel, QCRMPowerModel, QCLSPowerModel]
for pm_form in quadratic_relax
    println("Formulating and solving the form ",pm_form)
    pm = MaximinOPF.PF_FeasModel(pm_data, pm_form)
    JuMP.set_optimizer(pm.model,ip_solver)
    JuMP.optimize!(pm.model)
    println("\tOptimal value using powerform ", pm_form, " is: ",JuMP.objective_value(pm.model), "with status ",JuMP.termination_status(pm.model))
end
quad_conic_relax=[SOCWRConicPowerModel, SOCBFConicPowerModel]
for pm_form in quad_conic_relax
    println("Formulating and solving the form ",pm_form)
    pm = MaximinOPF.PF_FeasModel(pm_data, pm_form)
    JuMP.set_optimizer(pm.model,conic_solver)
    JuMP.optimize!(pm.model)
    println("\tOptimal value using powerform ", pm_form, " is: ",JuMP.objective_value(pm.model), "with status ",JuMP.termination_status(pm.model))
end
# sdp relaxations
sdp_relax=[SDPWRMPowerModel, SparseSDPWRMPowerModel]
for pm_form in sdp_relax
    println("Formulating and solving the form ",pm_form)
    pm = MaximinOPF.PF_FeasModel(pm_data, pm_form)
    JuMP.set_optimizer(pm.model,sdp_solver)
    JuMP.optimize!(pm.model)
    println("\tOptimal value using powerform ", pm_form, " is: ",JuMP.objective_value(pm.model), "with status ",JuMP.termination_status(pm.model))
end


text:
function solve()
    a, b, w = [parse(Int, x) for x in split(readline())]
    w = 1000w

    can = []
    for i=1:1000000
        if a*i ≤ w ≤ b*i
            push!(can, i)
        end
    end
    if length(can) == 0
        println("UNSATISFIABLE")
    else
        println(can[1], " " , can[end])
    end
end

solve()

max_stars_repo_name: aishikawa/atcoder-julia

max_issues_repo_name: aishikawa/atcoder-julia

max_forks_repo_name: aishikawa/atcoder-julia


text:
# This file was generated, do not modify it. # hide
forest = EnsembleModel(atom=DecisionTreeRegressor())
forest.atom.n_subfeatures = 3


text:
import FirstOrderLp, Plots, CSV
using LaTeXStrings, DataFrames, Test
include("../src/PrimalDualMethods.jl")

simple_lp = FirstOrderLp.linear_programming_problem(
  [-Inf],  # variable_lower_bound
  [Inf],  # variable_upper_bound
  [0.0],  # objective_vector
  0.0,                 # objective_constant
  ones(1, 1),           # constraint_matrix
  [0.0],      # right_hand_side
  1,                     # num_equalities
)
restart_length = 25

for method_name in ["PDHG", "extragradient"]
  @testset "$method_name" begin
    params = PrimalDualOptimizerParameters(
      RecoverPrimalDualMethodFromString(method_name), # method
      0.2,  # step_size
      1.0,  # primal_weight
      1, # record every
      20,   # printing frequency
      false, # verbose
      600,  # iteration limit
      NoRestarts(), # restart scheme
      TwoDimensionalSubspace([1.0, 0.0], [0.0, 1.0]),
      1e-10,
    )
    # No restarts
    solver_output = optimize(params, simple_lp, [1.0], [1.0])
    @test norm(solver_output.primal_solution) < 1e-3
    @test norm(solver_output.dual_solution) < 1e-3

    # Fixed frequency restarts
    params.restart_scheme = FixedFrequencyRestarts(restart_length, true)
    solver_output = optimize(params, simple_lp, [1.0], [1.0])
    @test norm(solver_output.primal_solution) < 1e-8
    @test norm(solver_output.dual_solution) < 1e-8

    # Adaptive restarts
    params.restart_scheme = AdaptiveRestarts(exp(-1), true)
    solver_output = optimize(params, simple_lp, [1.0], [1.0])
    @test norm(solver_output.primal_solution) < 1e-8
    @test norm(solver_output.dual_solution) < 1e-8
  end
end

max_stars_repo_name: pedersor/google-research

max_issues_repo_name: pedersor/google-research

max_forks_repo_name: pedersor/google-research


text:
using Ramnet.Encoders
using Ramnet.Models.AltDiscriminators:RegressionDiscriminator

using LinearAlgebra:Diagonal

using ..Approximators:RegularizedContinousPolicy, VDiscriminator
# using ..Buffers: MultiStepDynamicBuffer, add!
using ..Buffers: FixedSizeBuffer, add!, sample!, take_last, get

mutable struct ContinousRegularizedAC{OS,AS,T <: Real,O <: StaticArray{Tuple{OS},T,1},A <: StaticArray{Tuple{AS},T,1},E <: AbstractEncoder{T}} <: AbstractAgent{O,A}
    steps::Int
    γ::Float64
    batchsize::Int
    actor::RegularizedContinousPolicy{OS,AS,T,O,A,E}
    critic::VDiscriminator
    # buffer::MultiStepDynamicBuffer{O,A}
    buffer::FixedSizeBuffer{O,A}
    observation::Union{Nothing,O}
    done::Bool
    action::Union{Nothing,A}
    min_obs::Union{Nothing,O}
    max_obs::Union{Nothing,O}
    unevaluated_experiences::Int
    # rng::MersenneTwister
end

function ContinousRegularizedAC(::Type{O}, ::Type{A}, steps, n, α, η, batchsize, epochs, discount, forgetting_factor, encoder::E, start_cov::Float64, end_cov::Float64, cov_decay::Int, buffersize::Int; seed::Union{Nothing,Int}=nothing) where {OS,AS,T <: Real,O <: StaticArray{Tuple{OS},T,1},A <: StaticArray{Tuple{AS},T,1},E <: AbstractEncoder{T},C <: AbstractMatrix{T}}
    # !isnothing(seed) && seed < 0 && throw(DomainError(seed, "Seed must be non-negative"))
    rng = isnothing(seed) ? MersenneTwister() : MersenneTwister(seed)

    n < 1 && throw(DomainError(n, "Tuple size must be at least 1"))

    actor = RegularizedContinousPolicy(O, A, n, encoder;α, start_cov, end_cov, cov_decay, η, epochs, partitioner=:uniform_random, seed)
    # critic = RegressionDiscriminator{1}(OS, 32, encoder; seed, γ=forgetting_factor)
    critic = VDiscriminator(O, 32, forgetting_factor, encoder, seed)

    # buffer = MultiStepDynamicBuffer{O,A}()
    buffer = FixedSizeBuffer{O,A}(buffersize, rng)

    ContinousRegularizedAC{OS,AS,T,O,A,E}(steps, discount, batchsize, actor, critic, buffer, nothing, false, nothing, nothing, nothing, 0)
end

function ContinousRegularizedAC(env, encoder::E; steps, tuple_size, alpha, learning_rate, batchsize, epochs, discount, forgetting_factor=1.0, start_cov, end_cov, cov_decay, buffersize, seed=nothing) where {T <: Real,E <: AbstractEncoder{T}}
    ContinousRegularizedAC(observation_type(env), action_type(env), steps, tuple_size, alpha, learning_rate, batchsize, epochs, discount, forgetting_factor, encoder, start_cov, end_cov, cov_decay, buffersize; seed)
end

function observe!(agent::ContinousRegularizedAC{OS,AS,T,O,A,E}, observation::O) where {OS,AS,T,O,A,E}
    agent.observation = observation
    agent.done = false

    agent.action = _select_action(agent, observation)

    # Finding the edges of the domain
    if isnothing(agent.min_obs)
        agent.min_obs = observation
    else
        agent.min_obs = min.(agent.min_obs, observation)
    end

    if isnothing(agent.max_obs)
        agent.max_obs = observation
    else
        agent.max_obs = max.(agent.max_obs, observation)
    end

    nothing
end

# TODO: All observe! methods are the same for all agents. Generalize.
# TODO: This method does not need to take in the action
function observe!(agent::ContinousRegularizedAC{OS,AS,T,O,A,E}, action::A, reward::Float64, observation::O, done::Bool) where {OS,AS,T,O,A,E}
    # if reward < 0
    #     println(reward)
    # end

    add!(agent.buffer, agent.observation, agent.action, reward)
    agent.unevaluated_experiences += 1

    if !done
        agent.action = _select_action(agent, observation)
    end

    agent.observation = observation
    agent.done = done

  # Finding the edges of the domain
    agent.min_obs = min.(agent.min_obs)
    agent.max_obs = max.(agent.max_obs)

    nothing
end

function _select_action(agent::ContinousRegularizedAC{OS,AS,T,O,A,E}, observation::O) where {OS,AS,T,O,A,E}
    select_action(agent.actor, observation)
end

function select_action!(agent::ContinousRegularizedAC{OS,AS,T,O,A,E}, observation::O) where {OS,AS,T,O,A,E}
    if !isnothing(agent.action)
        return agent.action
    end

    return _select_action(agent, observation)
end

function update!(agent::ContinousRegularizedAC)
    if agent.done
        G = 0.0
        # for transition in Iterators.reverse(agent.buffer)
        #     G = transition.reward + agent.γ * G

        #     δ = G - (predict(agent.critic, transition.observation) |> first)
        #     update!(agent.actor, transition.observation, transition.action, δ)
        #     train!(agent.critic, transition.observation, G)
        # end

        # reset!(agent.buffer)

        for ex in take_last(agent.buffer, agent.unevaluated_experiences)
            G = ex.reward + agent.γ * G
            ex.value = G

            # Não estou fazendo uso de vantagem aqui! (diferença entre valor previso e observado)
            update!(agent.actor, sample!(agent.buffer, agent.batchsize), agent.critic)
            # train!(agent.critic, ex.observation, G)
            update!(agent.critic, ex.observation, G)
        end

        agent.unevaluated_experiences = 0

    # Preste atenção nesse teste! Como você não remove mais experiências do buffer (popfirst), essa
    # condição só será satisfeita uma única vez! Não é o comportamento desejado!
    # talvez length(agent.buffer) > agent.steps? Não exatamente. Preciso que já tenham ocorrido
    # agent.steps no episódio corrente. Posso usar agent.unevaluated_experiences!
    elseif agent.unevaluated_experiences == agent.steps
        # G = predict(agent.critic, agent.observation) |> first
        G = agent.critic(agent.observation)

        # for transition in Iterators.reverse(agent.buffer)
        #     G = transition.reward + agent.γ * G
        # end

        # t = popfirst!(agent.buffer)

        # δ = G - (predict(agent.critic, t.observation) |> first)
        # update!(agent.actor, t.observation, t.action, δ)
        # train!(agent.critic, t.observation, G)

        for ex in take_last(agent.buffer, agent.steps)
            G = ex.reward + agent.γ * G
        end

        ex = get(agent.buffer, agent.buffer.tail - agent.steps)
        ex.value = G

        # Não estou fazendo uso de vantagem aqui! (diferença entre valor previso e observado)
        update!(agent.actor, sample!(agent.buffer, agent.batchsize), agent.critic)
        # train!(agent.critic, ex.observation, G)
        update!(agent.critic, ex.observation, G)

        agent.unevaluated_experiences -= 1
    end

    nothing
end

function reset!(agent::ContinousRegularizedAC; seed::Union{Nothing,Int}=nothing)
    if !isnothing(seed)
        if seed ≥ 0
        seed!(agent.rng, seed)
        else
            throw(DomainError(seed, "Seed must be non-negative"))
        end
    end

    reset!(agent.actor)
    # Ramnet.reset!(agent.critic)
    reset!(agent.critic)
    reset!(agent.buffer)

    nothing
end


text:
using Documenter, MarketBasket

makedocs(modules=[MarketBasket],
        doctest=true)

deploydocs(deps   = Deps.pip("mkdocs", "python-markdown-math"),
    repo = "git@github.com:OmriRoames/MarketBasket.jl.git",
    julia  = "0.5.2",
    osname = "linux")


text:
"""
'triangle generalized_preferential_attachment_graph'
===========================================
Generate an instance of a triangle generalized preferential attachment graph which
follows the Eikmeier, Gleich description (https://arxiv.org/pdf/1904.12989.pdf).
This is an undirected graph that is generated as follows:
- Start with an empty graph
- Add n vertices where at each time step one of three events occurs:
A new node is added with probability p, along with two edges to existing nodes;
Three new nodes with two edges between them is added with probability 1 - p
Every m steps, coalesce the nodes added in time step 1

Functions
---------
The following functions are synonyms
- 'triangle_generalized_preferential_attachment_graph_v2'
- 'tgpa_graph_v2'
and
- 'triangle_generalized_preferential_attachment_edges_v2!'
- 'tgpa_edges_v2!'
The computational functions are
- 'tgpa_graph_v2(n,p,k0,m)' Generate a TGPA graph with n total nodes.
    This returns a MatrixNetwork type. Note that this process allows self loops.
The edge functions are
-   'tgpa_edges_v2!(n,p,m,edges,n0)' Add new edges to an existing set, by taking
    n0 time steps. Edges are added in one of two ways: From a new node to
    an existing node with probability p, between three new nodes with probability 1-p

Input
-----
- 'n': the number of nodes in the final graph.
- 'p': The probability of a node event, p must be a constant.
- 'k0': The number of nodes in the starting clique.
- 'm': The frequency of combining nodes
- 'edges': A list of edges to be manipulated in the process of generating
          new edges.
Output
------
- A matrix network type for the triangle generalized preferential attachment graph.
- 'edges': An updated list of edges.
Example:
triangle_generalized_preferential_attachment_graph_v2(100,1/3,1/2)
"""
:triangle_generalized_preferential_attachment_graph_v2, :tgpa_graph_v2,
:triangle_generalized_preferential_attachment_edges_v2!, :tgpa_edges_v2!

using Printf
using MatrixNetworks
using Distributions

function triangle_generalized_preferential_attachment_graph_v2(
    n::Int,p::Float64,k0::Int,m::Int)
    k0 >= 0 || throw(ArgumentError(@sprintf("k0=%i must be >= 0",n)))
    n >= k0 || throw(ArgumentError(@sprintf("n=%i must be >= k0=%i",n,k0)))
    0<=p<=1 || throw(ArgumentError(@sprintf("p=%0.3f must be between 0 and 1",p)))
    m >= 1 || throw(ArgumentError(@sprintf("m=%i must be >= 1",m)))
    m <= max(n,1) || throw(ArgumentError(@sprintf("m=%i must be <= n=%i",m,n)))
    edges = Vector{Tuple{Int,Int}}()
    # add the clique
    for i=1:k0
        for j=1:i-1
            push!(edges, (i,j))
            push!(edges, (j,i))
        end
    end
    return MatrixNetwork(triangle_generalized_preferential_attachment_edges_v2!(n,p,m,edges,k0),n)
end

function _edges_to_neighbors(edges, k0)
    neighbors = Vector{Vector{Int}}(undef, k0)
    for i=1:k0
        neighbors[i] = Vector{Int}()
    end
    for e in edges
        push!(neighbors[e[1]], e[2])
    end
    return neighbors
end

function triangle_generalized_preferential_attachment_edges_v2!(
    n::Int,p::Float64,m::Int,edges::Vector{Tuple{Int,Int}},k0::Int)
    i = k0 #number of nodes added

    # for this code, we need to have random neighbor access, so we'll keep
    neighbors = _edges_to_neighbors(edges, k0)

    while i < n
        #determine how many component events we should have
        #this says for every m steps (every m new nodes) we should have this many new components
        num_component_events = rand(Binomial(m,1-p),1)[1]

        #new component events
        for j = 1:num_component_events
            if i+3 <= n #only allow this step if there is room for three more nodes
                push!(edges, (i+1, i+2)) #add wedge to edge list
                push!(edges, (i+2, i+1))
                push!(edges, (i+1, i+3))
                push!(edges, (i+3, i+1))
                push!(neighbors,Vector{Int}()) ##update neighbor list
                push!(neighbors,Vector{Int}())
                push!(neighbors,Vector{Int}())
                push!(neighbors[i+1],i+2)
                push!(neighbors[i+1],i+3)
                push!(neighbors[i+2],i+1)
                push!(neighbors[i+3],i+1)
                i = i+3
            end
        end
        #new node events
        if i+1 <=n
            push!(neighbors,Vector{Int}())
            for j = 1:m
                if length(edges) > 0
                    v = rand(edges)[1]
                    v_neighbors = neighbors[v]
                else
                    v = i+1
                    v_neighbors = [];
                end
                #edge between new node and v
                push!(edges, (i+1, v))
                push!(edges, (v, i+1))
                #update neighbor vector
                push!(neighbors[i+1],v)
                push!(neighbors[v],i+1)

                #add another edge between new node and a neighbor of v
                if length(v_neighbors) > 0
                    v2 = rand(v_neighbors)
                    push!(edges, (i+1, v2))
                    push!(edges, (v2, i+1))
                    push!(neighbors[i+1],v2)
                    push!(neighbors[v2],i+1)
                end
            end
            i = i+1;
        end

    end
    return edges
end

tgpa_graph_v2 = triangle_generalized_preferential_attachment_graph_v2
tgpa_edges_v2! = triangle_generalized_preferential_attachment_edges_v2!


text:
# ---
# title: 94. Binary Tree Inorder Traversal
# id: problem94
# author: zhwang
# date: 2022-02-19
# difficulty: Medium
# categories: Hash Table, Stack, Tree
# link: <https://leetcode.com/problems/binary-tree-inorder-traversal/description/>
# hidden: true
# ---
#
# Given the `root` of a binary tree, return _the inorder traversal of its nodes
# ' values_.
#
#
#
# **Example 1:**
#
# ![](https://assets.leetcode.com/uploads/2020/09/15/inorder_1.jpg)
#
#
#
#     Input: root = [1,null,2,3]
#     Output: [1,3,2]
#
#
# **Example 2:**
#
#
#
#     Input: root = []
#     Output: []
#
#
# **Example 3:**
#
#
#
#     Input: root = [1]
#     Output: [1]
#
#
# **Example 4:**
#
# ![](https://assets.leetcode.com/uploads/2020/09/15/inorder_5.jpg)
#
#
#
#     Input: root = [1,2]
#     Output: [2,1]
#
#
# **Example 5:**
#
# ![](https://assets.leetcode.com/uploads/2020/09/15/inorder_4.jpg)
#
#
#
#     Input: root = [1,null,2]
#     Output: [1,2]
#
#
#
#
# **Constraints:**
#
#   * The number of nodes in the tree is in the range `[0, 100]`.
#   * `-100 <= Node.val <= 100`
#
#
#
# **Follow up:**
#
# Recursive solution is trivial, could you do it iteratively?
#
#
#
#
## @lc code=start
using LeetCode

inorder_traversal(::Nothing) = Int[]
function inorder_traversal(root::TreeNode)::Vector{Int}
    res, stack = Int[], []
    while !isempty(stack) || !isnothing(root)
        while !isnothing(root)
            push!(stack, root)
            root = root.left
        end
        root = pop!(stack)
        push!(res, root.val) ## inorder search
        root = root.right
    end
    return res
end

##### code template for inorder traversal and preorder traversal #####
## traversal(::Nothing) = Int[]
## function traversal(root::TreeNode)::Vector{Int}
##     res, stack = Int[], []
##     while !isempty(stack) || !isnothing(root)
##         while !isnothing(root)
##             push!(stack, root)
##             ## preorder traversal: put codes here
##             root = root.left
##         end
##         root = pop!(stack)
##         ## inorder traversal: put codes here
##         root = root.right
##     end
##     res
## end

## @lc code=end


text:
using StatsModels
using RegressionFormulae
using Test

include("dummymod.jl")

# y must not be the multiplicative or additive identity
# otherwise some of the tests will trivially pass
dat = (; y=2*ones(3), a=["u","i","o"], b=["q","w","e"], c=["s","d","f"], x=1:3)

@testset "error checking" begin
    sch = schema(dat)
    @test_throws ArgumentError apply_schema(@formula(y ~ x / a), sch, RegressionModel)
    @test_throws ArgumentError apply_schema(@formula(y ~ /(a, b, c)), sch, RegressionModel)
    @test !RegressionFormulae._isfulldummy(term(:a))
end

@testset "division" begin
    m = fit(DummyMod, @formula(y / 1000 ~ 1 + x), dat)
    @test all(response(m) .≈ dat.y ./ 1000)

    m = fit(DummyMod, @formula(1000 / y ~ 1 + x), dat)
    @test all(response(m) .≈ 1000 ./ dat.y)

    m = fit(DummyMod, @formula(y ~ 1 + 1000 / x), dat)
    @test all(m.mm.m[:, 2] .≈ 1000 ./ dat.x)

    m = fit(DummyMod, @formula(y ~ 1 + x / 1000), dat)
    @test all(m.mm.m[:, 2] .≈ dat.x ./ 1000)
end

@testset "single nesting level" begin
    m = fit(DummyMod, @formula(y ~ 0 + a / b), dat)
    @test coefnames(m) == ["a: i", "a: o", "a: u",
                           "a: i & b: q", "a: o & b: q", "a: u & b: q",
                           "a: i & b: w", "a: o & b: w", "a: u & b: w"]

    m = fit(DummyMod, @formula(y ~ 0 + a / x), dat)
    @test coefnames(m) == ["a: i", "a: o", "a: u",
                           "a: i & x", "a: o & x", "a: u & x"]

    m = fit(DummyMod, @formula(y ~ 1 + a / b), dat)
    @test coefnames(m) == ["(Intercept)", "a: o", "a: u",
                           "a: i & b: q", "a: o & b: q", "a: u & b: q",
                           "a: i & b: w", "a: o & b: w", "a: u & b: w"]

    m = fit(DummyMod, @formula(y ~ 1 + a / x), dat)
    @test coefnames(m) == ["(Intercept)", "a: o", "a: u",
                           "a: i & x", "a: o & x", "a: u & x"]

    m = fit(DummyMod, @formula(y ~ 0 + a / (b + x)), dat)
    @test coefnames(m) == ["a: i", "a: o", "a: u",
                           "a: i & b: q", "a: o & b: q", "a: u & b: q",
                           "a: i & b: w", "a: o & b: w", "a: u & b: w",
                           "a: i & x", "a: o & x", "a: u & x"]
    m = fit(DummyMod, @formula(y ~ 0 + a / (b * x)), dat)
    @test coefnames(m) == ["a: i", "a: o", "a: u",
                           "a: i & b: q", "a: o & b: q", "a: u & b: q",
                           "a: i & b: w", "a: o & b: w", "a: u & b: w",
                           "a: i & x", "a: o & x", "a: u & x",
                           "a: i & b: q & x", "a: o & b: q & x", "a: u & b: q & x",
                           "a: i & b: w & x", "a: o & b: w & x", "a: u & b: w & x"]
end

@testset "multiple nesting levels" begin
    m = fit(DummyMod, @formula(y ~ 0 + a / b / c), dat)
    @test coefnames(m) == ["a: i", "a: o", "a: u",
                           "a: i & b: q", "a: o & b: q", "a: u & b: q",
                           "a: i & b: w", "a: o & b: w", "a: u & b: w",
                           "a: i & b: q & c: f", "a: o & b: q & c: f",
                           "a: u & b: q & c: f", "a: i & b: w & c: f",
                           "a: o & b: w & c: f", "a: u & b: w & c: f",
                           "a: i & b: q & c: s", "a: o & b: q & c: s",
                           "a: u & b: q & c: s", "a: i & b: w & c: s",
                           "a: o & b: w & c: s", "a: u & b: w & c: s"]
    m = fit(DummyMod, @formula(y ~ 0 + a / b / x), dat)
    @test coefnames(m) == ["a: i", "a: o", "a: u",
                           "a: i & b: q", "a: o & b: q", "a: u & b: q",
                           "a: i & b: w", "a: o & b: w", "a: u & b: w",
                           "a: i & b: q & x", "a: o & b: q & x",
                           "a: u & b: q & x", "a: i & b: w & x",
                           "a: o & b: w & x", "a: u & b: w & x"]
    m = fit(DummyMod, @formula(y ~ 1 + a / b / c), dat)
    @test coefnames(m) == ["(Intercept)", "a: o", "a: u",
                           "a: i & b: q", "a: o & b: q", "a: u & b: q",
                           "a: i & b: w", "a: o & b: w", "a: u & b: w",
                           "a: i & b: q & c: f", "a: o & b: q & c: f",
                           "a: u & b: q & c: f", "a: i & b: w & c: f",
                           "a: o & b: w & c: f", "a: u & b: w & c: f",
                           "a: i & b: q & c: s", "a: o & b: q & c: s",
                           "a: u & b: q & c: s", "a: i & b: w & c: s",
                           "a: o & b: w & c: s", "a: u & b: w & c: s"]
    m = fit(DummyMod, @formula(y ~ 1 + a / b / x), dat)
    @test coefnames(m) == ["(Intercept)", "a: o", "a: u",
                           "a: i & b: q", "a: o & b: q", "a: u & b: q",
                           "a: i & b: w", "a: o & b: w", "a: u & b: w",
                           "a: i & b: q & x", "a: o & b: q & x",
                           "a: u & b: q & x", "a: i & b: w & x",
                           "a: o & b: w & x", "a: u & b: w & x"]

    m = fit(DummyMod, @formula(y ~ 0 + a / b / (c * x)), dat)
    @test coefnames(m) == ["a: i", "a: o", "a: u",
                           "a: i & b: q", "a: o & b: q", "a: u & b: q",
                           "a: i & b: w", "a: o & b: w", "a: u & b: w",
                           "a: i & b: q & c: f", "a: o & b: q & c: f", "a: u & b: q & c: f",
                           "a: i & b: w & c: f", "a: o & b: w & c: f", "a: u & b: w & c: f",
                           "a: i & b: q & c: s", "a: o & b: q & c: s", "a: u & b: q & c: s",
                           "a: i & b: w & c: s", "a: o & b: w & c: s", "a: u & b: w & c: s",
                           "a: i & b: q & x", "a: o & b: q & x", "a: u & b: q & x",
                           "a: i & b: w & x", "a: o & b: w & x", "a: u & b: w & x",
                           "a: i & b: q & c: f & x", "a: o & b: q & c: f & x", "a: u & b: q & c: f & x",
                           "a: i & b: w & c: f & x", "a: o & b: w & c: f & x", "a: u & b: w & c: f & x",
                           "a: i & b: q & c: s & x", "a: o & b: q & c: s & x", "a: u & b: q & c: s & x",
                           "a: i & b: w & c: s & x", "a: o & b: w & c: s & x", "a: u & b: w & c: s & x"]
end


text:
module FactorGraph

using TupleTools
using OMEinsum

include("utils.jl")
include("contract.jl")
include("incidence_matrix.jl")
include("fgraph.jl")
include("random_graphs.jl")
include("autodiff.jl")
include("contractionorder/contractionorder.jl")

end # module


text:
struct StaticIRSimulateState
    stmts::Vector{Any}
end

function process!(::StaticIRSimulateState, node, options) end

function process!(state::StaticIRSimulateState, node::TrainableParameterNode, options)
    push!(state.stmts, :($(node.name) = $(QuoteNode(get_param))(gen_fn, $(QuoteNode(node.name)))))
end

function process!(state::StaticIRSimulateState, node::ArgumentNode, options)
    push!(state.stmts, :($(get_value_fieldname(node)) = $(node.name)))
end

function process!(state::StaticIRSimulateState, node::JuliaNode, options)
    args = map((input_node) -> input_node.name, node.inputs)
    push!(state.stmts, :($(node.name) = $(QuoteNode(node.fn))($(args...))))
    if options.cache_julia_nodes
        push!(state.stmts, :($(get_value_fieldname(node)) = $(node.name)))
    end
end

function process!(state::StaticIRSimulateState, node::RandomChoiceNode, options)
    args = map((input_node) -> input_node.name, node.inputs)
    incr = gensym("logpdf")
    addr = QuoteNode(node.addr)
    dist = QuoteNode(node.dist)
    push!(state.stmts, :($(node.name) = $qn_random($dist, $(args...))))
    push!(state.stmts, :($incr = $qn_logpdf($dist, $(node.name), $(args...))))
    push!(state.stmts, :($(get_value_fieldname(node)) = $(node.name)))
    push!(state.stmts, :($(get_score_fieldname(node)) = $incr))
    push!(state.stmts, :($num_nonempty_fieldname += 1))
    push!(state.stmts, :($total_score_fieldname += $incr))
end

function process!(state::StaticIRSimulateState, node::GenerativeFunctionCallNode, options)
    args = map((input_node) -> input_node.name, node.inputs)
    args_tuple = Expr(:tuple, args...)
    addr = QuoteNode(node.addr)
    gen_fn = QuoteNode(node.generative_function)
    subtrace = get_subtrace_fieldname(node)
    incr = gensym("weight")
    push!(state.stmts, :($subtrace = $(QuoteNode(simulate))($gen_fn, $args_tuple)))
    push!(state.stmts, :($num_nonempty_fieldname += !$qn_isempty($qn_get_choices($subtrace)) ? 1 : 0))
    push!(state.stmts, :($(node.name) = $qn_get_retval($subtrace)))
    push!(state.stmts, :($total_score_fieldname += $qn_get_score($subtrace)))
    push!(state.stmts, :($total_noise_fieldname += $qn_project($subtrace, $qn_empty_selection)))
end

function codegen_simulate(gen_fn_type::Type{T}, args) where {T <: StaticIRGenerativeFunction}

    ir = get_ir(gen_fn_type)
    options = get_options(gen_fn_type)
    stmts = []

    # initialize score, weight, and num_nonempty
    push!(stmts, :($total_score_fieldname = 0.))
    push!(stmts, :($total_noise_fieldname = 0.))
    push!(stmts, :($num_nonempty_fieldname = 0))

    # unpack arguments
    arg_names = Symbol[arg_node.name for arg_node in ir.arg_nodes]
    push!(stmts, :($(Expr(:tuple, arg_names...)) = args))

    # process expression nodes in topological order
    state = StaticIRSimulateState(stmts)
    for node in ir.nodes
        process!(state, node, options)
    end

    # return value
    push!(stmts, :($return_value_fieldname = $(ir.return_node.name)))

    # construct trace
    trace_type = get_trace_type(gen_fn_type)
    push!(stmts, :($static_ir_gen_fn_ref = gen_fn))
    push!(stmts, :($trace = $(QuoteNode(trace_type))($(fieldnames(trace_type)...))))

    # return trace
    push!(stmts, :(return $trace))

    Expr(:block, stmts...)
end

push!(generated_functions, quote
@generated function $(Expr(:(.), Gen, QuoteNode(:simulate)))(gen_fn::$(QuoteNode(StaticIRGenerativeFunction)), args::Tuple)
    $(QuoteNode(codegen_simulate))(gen_fn, args)
end
end)

max_stars_repo_name: dendisuhubdy/Gen

max_issues_repo_name: kumsh/Gen

max_forks_repo_name: kumsh/Gen


text:
using AcuteML: UN
using MLStyle: @match
using Pseudopotentials:
    CoreHole,
    ExchangeCorrelationFunctional,
    ValenceCoreState,
    Pseudization,
    PerdewZunger,
    VoskoWilkNusair,
    PerdewBurkeErnzerhof,
    PerdewBurkeErnzerhofRevisedForSolids,
    BeckeLeeYangParr,
    PerdewWang91,
    TaoPerdewStaroverovScuseria,
    Coulomb,
    KresseJoubert,
    Blöchl,
    TroullierMartins,
    BacheletHamannSchlüter,
    VonBarthCar,
    Vanderbilt,
    AllElectron,
    RappeRabeKaxirasJoannopoulos,
    RappeRabeKaxirasJoannopoulosUltrasoft,
    SemicoreState,
    CoreState,
    NonLinearCoreCorrection

export UPFFile

const PSEUDOPOTENTIAL_NAME =
    r"(?:(rel)-)?([^-]*-)?(?:(pz|vwn|pbe|pbesol|blyp|pw91|tpss|coulomb)-)(?:([spdfn]*)l?-)?(ae|mt|bhs|vbc|van|rrkjus|rrkj|kjpaw|bpaw)(?:_(.*))?"i  # spdfnl?

struct UPFFile
    name::String
end

function analyzename(file::UPFFile)
    prefix, extension = splitext(file.name)
    @assert uppercase(extension) == ".UPF"
    data = split(prefix, '.'; limit = 2)
    if length(data) == 2
        element, description = data
        m = match(PSEUDOPOTENTIAL_NAME, description)
        if m !== nothing
            fullrelativistic = m[1] !== nothing ? true : false
            corehole = m[2] !== nothing ? nothing : nothing
            xc = @match m[3] begin
                "pz" => PerdewZunger()
                "vwn" => VoskoWilkNusair()
                "pbe" => PerdewBurkeErnzerhof()
                "pbesol" => PerdewBurkeErnzerhofRevisedForSolids()
                "blyp" => BeckeLeeYangParr()
                "pw91" => PerdewWang91()
                "tpss" => TaoPerdewStaroverovScuseria()
                "coulomb" => Coulomb()
            end
            valencecore = if m[4] !== nothing
                map(collect(m[4])) do c
                    @match c begin
                        's' || 'p' || 'd' => SemicoreState(c)
                        'f' => CoreState('f')
                        'n' => NonLinearCoreCorrection()
                    end
                end
            end
            pseudization = @match m[5] begin
                "ae" => AllElectron()
                "mt" => TroullierMartins()
                "bhs" => BacheletHamannSchlüter()
                "vbc" => VonBarthCar()
                "van" => Vanderbilt()
                "rrkj" => RappeRabeKaxirasJoannopoulos()
                "rrkjus" => RappeRabeKaxirasJoannopoulosUltrasoft()
                "kjpaw" => KresseJoubert()
                "bpaw" => Blöchl()
            end
            free = m[6]
            return (
                element = element,
                fullrelativistic = fullrelativistic,
                corehole = corehole,
                xc = xc,
                valencecore = valencecore,
                pseudization = pseudization,
                free = free,
            )
        end
    end
    throw(
        ArgumentError(
            "parsing failed! The file name `$(file.name)` does not follow QE's naming convention!",
        ),
    )
end


text:
#!/bin/julia
source = ARGS[1]
target = ARGS[2]
excepts = Set(readlines(joinpath(target, "excepts")))
for member in readdir(source)
    if !(member in excepts)
        run(`rsync -ur $(joinpath(source, member)) $target`)
    end
end


text:
# indicator of the free cone

"""
  IndFree()

Returns the indicator function of the whole space, or "free cone", i.e.,
a function which is identically zero.
"""

immutable IndFree <: IndicatorConvexCone end

"""
  Zero()

Returns the identically zero function.
"""

typealias Zero IndFree

function (f::IndFree)(x::AbstractArray)
  return 0.0
end

function prox!(f::IndFree, x::AbstractArray, y::AbstractArray, gamma::Real=1.0)
  y[:] = x
  return 0.0
end

fun_name(f::IndFree) = "indicator of the free cone"
fun_dom(f::IndFree) = "AbstractArray{Real}, AbstractArray{Complex}"
fun_expr(f::IndFree) = "x ↦ 0"
fun_params(f::IndFree) = "none"

function prox_naive(f::IndFree, x::AbstractArray, gamma::Real=1.0)
  return x, 0.0
end


text:
module test_basics
using ApproXD
using Test
using SparseArrays
using LinearAlgebra

@testset "equally spaced interior knots constructor" begin

	deg    = 3
	nKnots = 7
	lb     = 0.0
	ub     = 10.0

	b = BSpline(nKnots,deg,lb,ub)

	@test getNumKnots(b) + 2*deg == length(b.knots)
	@test b.degree == deg
	@test b.numKnots == nKnots
	@test b.lower == lb
	@test b.upper == ub
	@test sum(abs.(ApproXD.getCoefs(b) .- b.knots[(deg+1):(length(b.knots)-deg)])) == 0.0

	@test_throws ArgumentError BSpline(nKnots,deg,ub,lb)
	@test_throws ArgumentError BSpline(nKnots,-1,lb,ub)
	nKnots=2
	@test_throws ArgumentError BSpline(nKnots,deg,lb,ub)

	# test that when x == upper/lower, first/last basis is 1
	@test findnz(getBasis(lb,b))[2][1] == 1.0
	@test findnz(getBasis(ub,b))[2][end] == 1.0

	# a special case
	deg    = 1
	npoints = 10
	nKnots = npoints - deg + 1
	lb     = 0.0
	ub     = 10.0
	points = collect(range(lb,stop=ub,length=npoints))
	b = BSpline(nKnots,deg,lb,ub)

	@test all(getBasis(points,b) .== sparse(I*1.0,npoints,npoints))
end

@testset "interior knots user supplied constructor" begin

	deg    = 3
	lb     = 0.0
	ub     = 10.0

	myknots = collect(range(lb,stop=ub,length=11))

	b = BSpline(myknots,deg)

	@test all(b.knots .== [ [lb for i=1:deg] ; myknots; [ub for i=1:deg] ])
	@test getNumKnots(b) == length(myknots)

	knots = collect(range(ub,stop=lb,length=11))
	@test_throws ArgumentError BSpline(knots,deg)

end

@testset "interpolate function with a kink" begin

	deg = 3
	lb = -1.0
	ub = 1.0
	kink = 0.0
	knots = vcat(lb,-0.5,0,0,0.5,ub)
	nKnots = length(knots)
	npoints = nKnots + deg -1
	points = collect(range(lb,stop=ub,length=npoints))
	b = BSpline(knots,deg)
	f(x) = x>=0 ? x^2 : 0.0
	B = Array(getBasis(points,b))

	# println(B)
	coef = pinv(B) * f.(points)

	newpts = collect(range(lb,stop=ub,length=100))
	newvls = getBasis(newpts,b) * coef

	@test maximum(abs,newvls .- f.(newpts)) < 1e-10

end

@testset "compare computed basis to R splineDesign()" begin

	nKnots = 15
	lb     = -1.1
	ub     = 17.4

	points = collect(range(lb,stop=ub,length=18))

	# R data
	# in R:
	# points = seq(lb,ub,length=5)
	# Rbase = as.numeric(splineDesign(knots=knots,x=points,ord=deg+1))
	Rbase = Dict{Int,Vector}()
	Rbase[1] = [1.00000000, 0.17647086, 0.00000000, 0.00000000, 0.00000000, 0.00000000,
	0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000,
	0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000,
	0.00000000, 0.82352914, 0.35294269, 0.00000000, 0.00000000, 0.00000000,
	0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000,
	0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000,
	0.00000000, 0.00000000, 0.64705731, 0.52941444, 0.00000000, 0.00000000,
	0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000,
	0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000,
	0.00000000, 0.00000000, 0.00000000, 0.47058556, 0.70588369, 0.00000000,
	0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000,
	0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000,
	0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.29411631, 0.88234983,
	0.05882130, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000,
	0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000,
	0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.11765017,
	0.94117870, 0.23529278, 0.00000000, 0.00000000, 0.00000000, 0.00000000,
	0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000,
	0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000,
	0.00000000, 0.76470722, 0.41176426, 0.00000000, 0.00000000, 0.00000000,
	0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000,
	0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000,
	0.00000000, 0.00000000, 0.58823574, 0.58823574, 0.00000000, 0.00000000,
	0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000,
	0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000,
	0.00000000, 0.00000000, 0.00000000, 0.41176426, 0.76471434, 0.00000000,
	0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000,
	0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000,
	0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.23528566, 0.94120763,
	0.11766041, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000,
	0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000,
	0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.05879237,
	0.88233959, 0.29411320, 0.00000000, 0.00000000, 0.00000000, 0.00000000,
	0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000,
	0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000,
	0.00000000, 0.70588680, 0.47056598, 0.00000000, 0.00000000, 0.00000000,
	0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000,
	0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000,
	0.00000000, 0.00000000, 0.52943402, 0.64704547, 0.00000000, 0.00000000,
	0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000,
	0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000,
	0.00000000, 0.00000000, 0.00000000, 0.35295453, 0.82354722, 0.00000000,
	0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000,
	0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000,
	0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.17645278, 1.00000000
	]

	Rbase[2] = [ 1.000000000, 0.031141963, 0.000000000, 0.000000000, 0.000000000, 0.000000000,
	0.000000000,0.000000000,0.000000000,0.000000000,0.000000000,0.000000000,
	0.000000000,0.000000000,0.000000000,0.000000000,0.000000000,0.000000000,
	0.000000000,0.629758168,0.062284318,0.000000000,0.000000000,0.000000000,
	0.000000000,0.000000000,0.000000000,0.000000000,0.000000000,0.000000000,
	0.000000000,0.000000000,0.000000000,0.000000000,0.000000000,0.000000000,
	0.000000000,0.339099869,0.728374021,0.140139769,0.000000000,0.000000000,
	0.000000000,0.000000000,0.000000000,0.000000000,0.000000000,0.000000000,
	0.000000000,0.000000000,0.000000000,0.000000000,0.000000000,0.000000000,
	0.000000000,0.000000000,0.209341660,0.749134425,0.249134948,0.000000000,
	0.000000000,0.000000000,0.000000000,0.000000000,0.000000000,0.000000000,
	0.000000000,0.000000000,0.000000000,0.000000000,0.000000000,0.000000000,
	0.000000000,0.000000000,0.000000000,0.110725806,0.707613013,0.389272080,
	0.001729979,0.000000000,0.000000000,0.000000000,0.000000000,0.000000000,
	0.000000000,0.000000000,0.000000000,0.000000000,0.000000000,0.000000000,
	0.000000000,0.000000000,0.000000000,0.000000000,0.043252039,0.603807138,
	0.555361351,0.027681347,0.000000000,0.000000000,0.000000000,0.000000000,
	0.000000000,0.000000000,0.000000000,0.000000000,0.000000000,0.000000000,
	0.000000000,0.000000000,0.000000000,0.000000000,0.000000000,0.006920782,
	0.442908669,0.679930089,0.084774903,0.000000000,0.000000000,0.000000000,
	0.000000000,0.000000000,0.000000000,0.000000000,0.000000000,0.000000000,
	0.000000000,0.000000000,0.000000000,0.000000000,0.000000000,0.000000000,
	0.000000000,0.292388564,0.742214454,0.173010642,0.000000000,0.000000000,
	0.000000000,0.000000000,0.000000000,0.000000000,0.000000000,0.000000000,
	0.000000000,0.000000000,0.000000000,0.000000000,0.000000000,0.000000000,
	0.000000000,0.000000000,0.173010642,0.742215737,0.292398436,0.000000000,
	0.000000000,0.000000000,0.000000000,0.000000000,0.000000000,0.000000000,
	0.000000000,0.000000000,0.000000000,0.000000000,0.000000000,0.000000000,
	0.000000000,0.000000000,0.000000000,0.084773620,0.679921160,0.442924171,
	0.006921803,0.000000000,0.000000000,0.000000000,0.000000000,0.000000000,
	0.000000000,0.000000000,0.000000000,0.000000000,0.000000000,0.000000000,
	0.000000000,0.000000000,0.000000000,0.000000000,0.027680404,0.555347557,
	0.603816624,0.043251286,0.000000000,0.000000000,0.000000000,0.000000000,
	0.000000000,0.000000000,0.000000000,0.000000000,0.000000000,0.000000000,
	0.000000000,0.000000000,0.000000000,0.000000000,0.000000000,0.001728271,
	0.389261573,0.707610624,0.110716169,0.000000000,0.000000000,0.000000000,
	0.000000000,0.000000000,0.000000000,0.000000000,0.000000000,0.000000000,
	0.000000000,0.000000000,0.000000000,0.000000000,0.000000000,0.000000000,
	0.000000000,0.249138090,0.749138941,0.209341841,0.000000000,0.000000000,
	0.000000000,0.000000000,0.000000000,0.000000000,0.000000000,0.000000000,
	0.000000000,0.000000000,0.000000000,0.000000000,0.000000000,0.000000000,
	0.000000000,0.000000000,0.140144889,0.728367352,0.339102179,0.000000000,
	0.000000000,0.000000000,0.000000000,0.000000000,0.000000000,0.000000000,
	0.000000000,0.000000000,0.000000000,0.000000000,0.000000000,0.000000000,
	0.000000000,0.000000000,0.000000000,0.062290807,0.629762237,0.000000000,
	0.000000000,0.000000000,0.000000000,0.000000000,0.000000000,0.000000000,
	0.000000000,0.000000000,0.000000000,0.000000000,0.000000000,0.000000000,
	0.000000000,0.000000000,0.000000000,0.000000000,0.031135584,1.000000000]

	Rbase[3] = [ 1.000000e+00, 5.495649e-03, 0.000000e+00, 0.000000e+00, 0.000000e+00,
	0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,
	0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,
	0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,3.960926e-01,
	1.099141e-02,0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,
	0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,
	0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,
	0.000000e+00,0.000000e+00,5.053256e-01,3.797757e-01,2.473067e-02,
	0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,
	0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,
	0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,
	9.308614e-02,5.640807e-01,4.973204e-01,5.861979e-02,0.000000e+00,
	0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,
	0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,
	0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,4.515215e-02,
	4.605802e-01,5.928834e-01,1.144917e-01,3.391997e-05,0.000000e+00,
	0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,
	0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,
	0.000000e+00,0.000000e+00,0.000000e+00,1.736870e-02,3.442564e-01,
	6.536401e-01,1.977060e-01,2.171079e-03,0.000000e+00,0.000000e+00,
	0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,
	0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,
	0.000000e+00,0.000000e+00,4.240355e-03,2.315968e-01,6.633080e-01,
	3.054812e-01,1.163576e-02,0.000000e+00,0.000000e+00,0.000000e+00,
	0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,
	0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,
	0.000000e+00,2.714104e-04,1.389521e-01,6.178172e-01,4.224164e-01,
	3.392368e-02,0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,
	0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,
	0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,
	0.000000e+00,7.453055e-02,5.320245e-01,5.320283e-01,7.453526e-02,
	0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,
	0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,
	0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,
	3.392334e-02,4.224124e-01,6.178178e-01,1.389577e-01,2.714672e-04,
	0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,
	0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,
	0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,1.163555e-02,
	3.054759e-01,6.633084e-01,2.316003e-01,4.240183e-03,0.000000e+00,
	0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,
	0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,
	0.000000e+00,0.000000e+00,0.000000e+00,2.171011e-03,1.977000e-01,
	6.536412e-01,3.442539e-01,1.736642e-02,0.000000e+00,0.000000e+00,
	0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,
	0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,
	0.000000e+00,0.000000e+00,3.386972e-05,1.144870e-01,5.928863e-01,
	4.605788e-01,4.515351e-02,0.000000e+00,0.000000e+00,0.000000e+00,
	0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,
	0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,
	0.000000e+00,0.000000e+00,5.861962e-02,4.973229e-01,5.640748e-01,
	9.308654e-02,0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,
	0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,
	0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,
	0.000000e+00,2.473187e-02,3.797783e-01,5.053253e-01,0.000000e+00,
	0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,
	0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,
	0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,
	1.099333e-02,3.960942e-01,0.000000e+00,0.000000e+00,0.000000e+00,
	0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,
	0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,
	0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,5.493960e-03,
	1.000000e+00]

	for deg in 1:3

		b = BSpline(nKnots,deg,lb,ub)
		bs = getBasis(points,b)

		@test size(bs) == (length(points),ApproXD.getNumCoefs(b))

		@test isapprox(maximum(abs,Array(bs)[:] .- Rbase[deg]), 0.0, atol=1e-4)

	end

end

end


text:
import StatsBase
import StatsBase: Weights
import Random
# using CuArrays

abstract type AbstractPolicy end
next!(ap::AbstractPolicy) = nothing

mutable struct RandomActingPolicy{T<:AbstractFloat} <: AbstractPolicy
    probabilities::Array{T,1}
    weight_vec::Weights{T, T, Array{T, 1}}
    RandomActingPolicy(probabilities::Array{T,1}) where {T<:AbstractFloat} =
        new{T}(probabilities, Weights(probabilities))
end

get_prob(π::RandomActingPolicy, action_t) =
    π.probabilities[action_t]

sample(π::RandomActingPolicy) =
    sample(Random.GLOBAL_RNG, π)

sample(rng::Random.AbstractRNG, π::RandomActingPolicy) =
    StatsBase.sample(rng, π.weight_vec)

function (π::RandomActingPolicy)(state_t, rng::Random.AbstractRNG=Random.GLOBAL_RNG)
    action = sample(rng, π)
    return action, get_prob(π, action)
end

abstract type AbstractValuePolicy <: AbstractPolicy end

action_set(ap::AbstractValuePolicy) = nothing
Base.eltype(ap::AbstractValuePolicy) = eltype(action_set(ap))

_get_max_action(ap::AbstractValuePolicy, values) =
    action_set(ap)[findmax(values)[2]]
# _get_max_action(ap::AbstractValuePolicy, values::CuArray) =
#     action_set(ap)[findmax(cpu(values))[2]]

"""
    ϵGreedy(ϵ, action_set)
    ϵGreedy(ϵ, num_actions)

Simple ϵGreedy value policy.
"""
Base.@kwdef struct ϵGreedy{AS} <: AbstractValuePolicy
    ϵ::Float64
    action_set::AS
end

ϵGreedy(ϵ::Float64, num_actions::Int) = ϵGreedy(ϵ, 1:num_actions)

action_set(ap::ϵGreedy) = ap.action_set

"""
    sample(ap::ϵGreedy, values, rng)

Select an action according to the values.
"""
sample(ap::ϵGreedy, values) = StatsBase.sample(Random.GLOBAL_RNG, ap, values)
function sample(rng::Random.AbstractRNG, ap::ϵGreedy, values)
    if rand(rng) > ap.ϵ
        return ap.action_set[findmax(values)[2]]
    else
        return rand(rng, ap.action_set)
    end
end

"""
    get_prob(ap::ϵGreedy, values, action)

Get probabiliyt of action according to values.
"""
function get_prob(ap::ϵGreedy, values, action)
    if action == findmax(values)[2]
        return 1 - ap.ϵ + (ap.ϵ / length(ap.action_set))
    else
        return ap.ϵ / length(ap.action_set)
    end
end

"""
    ϵGreedyDecay{AS}(ϵ_range, decay_period, warmup_steps, action_set::AS)
    ϵGreedyDecay(ϵ_range, end_step, num_actions)

This is an acting policy which decays exploration linearly over time. This api will possibly change overtime once I figure out a better way to specify decaying epsilon.

# Arguments
`ϵ_range::Tuple{Float64, Float64}`: (max epsilon, min epsilon)
`decay_period::Int`: period epsilon decays
`warmup_steps::Int`: number of steps before decay starts
"""
Base.@kwdef mutable struct ϵGreedyDecay{AS} <: AbstractValuePolicy
    ϵ_range::Tuple{Float64, Float64}
    decay_period::Int
    warmup_steps::Int
    cur_step::Int = 0
    action_set::AS
    ϵGreedyDecay(ϵ_range, decay_period, warmup_steps, action_set::AS) where {AS} =
        new{AS}(ϵ_range, decay_period, warmup_steps, 0, action_set)
end

ϵGreedyDecay(ϵ_range, end_step, num_actions) = ϵGreedyDecay(ϵ_range, end_step, 1:num_actions)

action_set(ap::ϵGreedyDecay) = ap.action_set

function _get_eps_for_step(ap::ϵGreedyDecay, step=ap.cur_step)
    ϵ_min = ap.ϵ_range[2]
    ϵ_max = ap.ϵ_range[1]

    steps_left = ap.decay_period + ap.warmup_steps - ap.cur_step
    bonus = (ϵ_max - ϵ_min) * steps_left / ap.decay_period
    bonus = clamp(bonus, 0.0, ϵ_max - ϵ_min)
    ϵ_min + bonus
end

sample(ap::ϵGreedyDecay, values) = StatsBase.sample(Random.GLOBAL_RNG, ap, values)
function sample(rng::Random.AbstractRNG, ap::ϵGreedyDecay, values, step=ap.cur_step)
    ϵ = _get_eps_for_step(ap::ϵGreedyDecay, step)
    if rand(rng) > ϵ
        return _get_max_action(ap, values)
    else
        return rand(rng, ap.action_set)
    end
end

function get_prob(ap::ϵGreedyDecay, values, action, step=ap.cur_step)
    ϵ = _get_eps_for_step(ap, step)
    if ap.action_set[action] == _get_max_action(ap, values)
        return 1 - ϵ + (ϵ / length(ap.action_set))
    else
        return ϵ / length(ap.action_set)
    end
end

next!(ap::ϵGreedyDecay) = ap.cur_step += 1


text:
# This file is auto-generated by AWSMetadata.jl
using AWS
using AWS.AWSServices: pricing
using AWS.Compat
using AWS.UUIDs

"""
    DescribeServices()

Returns the metadata for one service or a list of the metadata for all services. Use this without a service code to get the service codes for all services. Use it with a service code, such as AmazonEC2, to get information specific to that service, such as the attribute names available for that service. For example, some of the attribute names available for EC2 are volumeType, maxIopsVolume, operation, locationType, and instanceCapacity10xlarge.

# Optional Parameters
- `FormatVersion`: The format version that you want the response to be in. Valid values are: aws_v1
- `MaxResults`: The maximum number of results that you want returned in the response.
- `NextToken`: The pagination token that indicates the next set of results that you want to retrieve.
- `ServiceCode`: The code for the service whose information you want to retrieve, such as AmazonEC2. You can use the ServiceCode to filter the results in a GetProducts call. To retrieve a list of all services, leave this blank.
"""
describe_services(; aws_config::AWSConfig=global_aws_config()) = pricing("DescribeServices"; aws_config=aws_config)
describe_services(args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = pricing("DescribeServices", args; aws_config=aws_config)

"""
    GetAttributeValues()

Returns a list of attribute values. Attibutes are similar to the details in a Price List API offer file. For a list of available attributes, see Offer File Definitions in the AWS Billing and Cost Management User Guide.

# Required Parameters
- `AttributeName`: The name of the attribute that you want to retrieve the values for, such as volumeType.
- `ServiceCode`: The service code for the service whose attributes you want to retrieve. For example, if you want the retrieve an EC2 attribute, use AmazonEC2.

# Optional Parameters
- `MaxResults`: The maximum number of results to return in response.
- `NextToken`: The pagination token that indicates the next set of results that you want to retrieve.
"""
get_attribute_values(AttributeName, ServiceCode; aws_config::AWSConfig=global_aws_config()) = pricing("GetAttributeValues", Dict{String, Any}("AttributeName"=>AttributeName, "ServiceCode"=>ServiceCode); aws_config=aws_config)
get_attribute_values(AttributeName, ServiceCode, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = pricing("GetAttributeValues", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("AttributeName"=>AttributeName, "ServiceCode"=>ServiceCode), args)); aws_config=aws_config)

"""
    GetProducts()

Returns a list of all products that match the filter criteria.

# Optional Parameters
- `Filters`: The list of filters that limit the returned products. only products that match all filters are returned.
- `FormatVersion`: The format version that you want the response to be in. Valid values are: aws_v1
- `MaxResults`: The maximum number of results to return in the response.
- `NextToken`: The pagination token that indicates the next set of results that you want to retrieve.
- `ServiceCode`: The code for the service whose products you want to retrieve.
"""
get_products(; aws_config::AWSConfig=global_aws_config()) = pricing("GetProducts"; aws_config=aws_config)
get_products(args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = pricing("GetProducts", args; aws_config=aws_config)


text:
import .ForwardDiff
using SIMDDualNumbers

@generated function init_dual(v::Tuple{Vararg{AbstractSIMD,A}}) where {A}
  res = Expr(:tuple)
  q = Expr(:block, Expr(:meta,:inline))
  for a ∈ 1:A
    v_a = Symbol(:v_,a)
    push!(q.args, Expr(:(=), v_a, Expr(:ref, :v, a)))
    partials = Expr(:tuple)
    for i ∈ 1:A
      push!(partials.args, Expr(:call, i == a ? :one : :zero, v_a))
    end
    push!(res.args, :(ForwardDiff.Dual($v_a, ForwardDiff.Partials($partials))))
  end
  push!(q.args, res)
  q
end
@generated function dual_store!(∂p::Tuple{Vararg{AbstractStridedPointer,A}}, p::AbstractStridedPointer, ∂v, im::Vararg{Any,N}) where {A,N}
  quote
    $(Expr(:meta,:inline))
    v = ∂v.value
    ∂ = ∂v.partials
    Base.Cartesian.@nextract $N im im
    Base.Cartesian.@ncall $N VectorizationBase.vnoaliasstore! p v im  # store
    Base.Cartesian.@nexprs $A a -> begin # for each of `A` partials
      ∂p_a = ∂p[a]
      ∂_a = ∂[a]
      Base.Cartesian.@ncall $N VectorizationBase.vnoaliasstore! ∂p_a ∂_a im # store
    end
    nothing
  end
end


text:
module LeastSquaresEstimation

using LinearAlgebra
using StaticArrays
using Zygote

# Types used as constructor flags (Move to sep. file later)
abstract type SequentialEstimatorForm end
struct InformationForm <: SequentialEstimatorForm end
struct CovarianceForm <: SequentialEstimatorForm end

include("LinearLeastSquares.jl")
include("WeightedLinearLeastSquares.jl")
include("SequentialLinearLeastSquares.jl")
include("NonLinearLeastSquares.jl")

export LinearLeastSquares
export WeightedLinearLeastSquares
export SequentialLinearLeastSquares
export NonLinearLeastSquares
export InformationForm
export CovarianceForm
export FeedMeasurementBatch!
export ComputeEstimate!
export GetEstimate
export GetMeasurementEstimate

end


text:
import Sockets

function start(port)
    server = Sockets.listen(port)
    @async begin
        while true
            conn = Sockets.accept(server)
            @async begin
                read(conn)
            end
        end
    end
    "start tcp service success"
end

function read(conn)
    try
        while true
            line = readline(conn)
            write(conn, line)
        end
    catch err
        print("connection ended with error $err")
    end
end


text:
Base.isempty(d::Deck) = isempty(d.cards)
Base.empty!(d::Deck) = empty!(d.cards)
Base.length(d::Deck) = length(d.cards)
Base.endof(d::Deck) = endof(d.cards)
Base.shuffle!(d::Deck) = shuffle!(d.cards)
Base.sort!(d::Deck) = sort!(d.cards)
Base.getindex(d::Deck, r) = Deck(getindex(d.cards, r), d.design)
Base.size(d::Deck) = (d.design.rlen, d.design.slen)
function Base.print(d::Deck)
    sz = size(d)
    r = map(x->d.design.ranks[ind2sub(sz, x)[1]], d.cards)
    s = map(x->d.design.suits[ind2sub(sz, x)[2]], d.cards)
    join(r.*s, " ")
end

max_stars_repo_name: ethansaxenian/RosettaDecode

max_issues_repo_name: ethansaxenian/RosettaDecode

max_forks_repo_name: ethansaxenian/RosettaDecode


text:
# This file is a part of BinaryCommitteeMachineFBP.jl. License is MIT: http://github.com/carlobaldassi/BinaryCommitteeMachineFBP.jl/LICENCE.md

module Magnetizations

export Mag64, MagT64, MagP64, mfill, mflatp, mrand, damp, reinforce, ⊗, ⊘, ↑, sign0,
       merf, exactmix, erfmix, mtanh, log1pxy, mcrossentropy,
       logZ, forcedmag, showinner, parseinner, magformat,
       conv_diff

using SpecialFunctions

import Base: convert, promote_rule, *, /, +, -, sign, signbit, isnan,
             show, abs, isfinite, isless, copysign,
             atanh, zero

abstract type Mag64 <: Number end

@inline m2f(a::Mag64) = reinterpret(Float64, a)
@inline f2m(::Type{F}, a::Float64) where {F<:Mag64} = reinterpret(F, a)

convert(::Type{T}, y::Mag64) where {T<:Real} = convert(T, Float64(y))
convert(::Type{F}, y::Real) where {F<:Mag64} = convert(F, Float64(y))

convert(::Type{F}, x::F) where {F<:Mag64} = x
convert(::Type{F}, x::Mag64) where {F<:Mag64} = F(Float64(x))

Mag64(::Type{F}, pp::Real, pm::Real) where {F<:Mag64} = F(pp, pm)

Float64(x::F) where {F<:Mag64} = convert(Float64, x)

promote_rule(::Type{<:Mag64}, ::Type{Float64}) = Float64

zero(::Type{F}) where {F<:Mag64} = f2m(F, 0.0)

isnan(a::Mag64) = isnan(m2f(a))

abs(a::F) where {F<:Mag64} = f2m(F, abs(m2f(a)))
copysign(x::F, y::Float64) where {F<:Mag64} = f2m(F, copysign(m2f(x), y))
copysign(x::F, y::Mag64) where {F<:Mag64} = f2m(F, copysign(m2f(x), m2f(y)))

⊗(a::F, b::Float64) where {F<:Mag64} = a ⊗ F(b)
⊘(a::F, b::Float64) where {F<:Mag64} = a ⊘ F(b)

⊗(a::Float64, b::Mag64) = b ⊗ a

(*)(a::Mag64, b::Real) = Float64(a) * b
(*)(a::Real, b::Mag64) = b * a

(+)(a::Mag64, b::Real) = Float64(a) + b
(+)(a::Real, b::Mag64) = b + a

(-)(a::Mag64, b::Real) = Float64(a) - b
(-)(a::Real, b::Mag64) = -(b - a)
(-)(a::F) where {F<:Mag64} = f2m(F, -m2f(a))

(-)(a::Mag64, b::Mag64) = Float64(a) - Float64(b)

sign(a::Mag64) = sign(m2f(a))
signbit(a::Mag64) = signbit(m2f(a))
sign0(a::Union{Mag64,Real}) = (1 - 2signbit(a))

show(io::IO, a::Mag64) = show(io, Float64(a))
showinner(io::IO, a::Mag64) = show(io, m2f(a))

mfill(::Type{F}, x::Float64, n::Int) where {F<:Mag64} = F[F(x) for i = 1:n]
mflatp(::Type{F}, n::Int) where {F<:Mag64} = mfill(F, 0.0, n)

mrand(::Type{F}, x::Float64, n::Int) where {F<:Mag64} = F[F(x * (2*rand()-1)) for i = 1:n]

reinforce(m::Mag64, m0::Mag64, γ::Float64) = m ⊗ reinforce(m0, γ)

damp(newx::Float64, oldx::Float64, λ::Float64) = newx * (1 - λ) + oldx * λ

Base.:(==)(a::F, b::F) where {F<:Mag64} = (m2f(a) == m2f(b))
Base.:(==)(a::Mag64, b::Float64) = (Float64(a) == b)
Base.:(==)(a::Float64, b::Mag64) = (b == a)

Base.iszero(a::Mag64) = iszero(m2f(a))

isless(m::Mag64, x::Real) = isless(Float64(m), x)
isless(x::Real, m::Mag64) = isless(x, Float64(m))

function erfmix(H::Float64, m₊::Float64, m₋::Float64)
    erf₊ = erf(m₊)
    erf₋ = erf(m₋)
    return H * (erf₊ - erf₋) / (2 + H * (erf₊ + erf₋))
end

logZ(u::Vector{F}) where {F<:Mag64} = logZ(zero(F), u)

↑(m::F, x::Real) where {F<:Mag64} = mtanh(F, x * atanh(m))

conv_diff(x::F, y::F) where {F<:Mag64} = abs(m2f(x) - m2f(y))

include("MagnetizationsP.jl")
include("MagnetizationsT.jl")

end # module


text:
test_smoothstep = (x_step, dx, a, b) -> begin
    # at the center between edges
    c = (a+b)/2
    @test smoothstep(x_step,x_step,dx,a,b) == c
    # before and at edge0 return a
    @test smoothstep(x_step - dx -0.0001,x_step,dx,a,b) == a
    @test smoothstep(x_step - dx,x_step,dx,a,b) == a
    # after and at edge1 return b
    @test smoothstep(x_step + dx +0.0001,x_step,dx,a,b) == b
    @test smoothstep(x_step + dx, x_step,dx,a,b) == b
    if a <= b
        # before x_step return between a and center
        @test a <= smoothstep(x_step - dx/2,x_step,dx,a,b) <= c
        # after x_step return between center and b
        @test c <= smoothstep(x_step + dx/2,x_step,dx,a,b) <= b
    else
        # before x_step return between a and center
        @test a >= smoothstep(x_step - dx/2,x_step,dx,a,b) >= c
        # after x_step return between center and b
        @test c >= smoothstep(x_step + dx/2,x_step,dx,a,b) >= b
    end
    # monotonous
    xs = range(x_step-dx,x_step+dx,length=10)
    ys = smoothstep.(xs,x_step,dx,a,b)
    dys = [ys[i+1] - ys[i] for i in 1:(length(ys)-1)]
    @test all(sign.(dys) .== sign(b-a))
    true
end

@testset "smoothstep" begin
    x = 0; x_step = 0; dx = 1; a = 0; b = 1
    test_smoothstep(0,1,0,1)
    test_smoothstep(0,1,2,4)
    test_smoothstep(0,1,4,2)
    test_smoothstep(0,1,4,4)
    #
    test_smoothstep(3,1,0,1)
    test_smoothstep(3,1,2,4)
    test_smoothstep(3,1,4,2)
    test_smoothstep(3,1,4,4)
    #
    test_smoothstep(-3,1,0,1)
    test_smoothstep(-3,1,2,4)
    test_smoothstep(-3,1,4,2)
    test_smoothstep(-3,1,4,4)
    #
    @test_throws AssertionError smoothstep(3,0,0,0,1)
end;

i_tmp = () -> begin
    # using CairoMakie
    ts = -0.2:0.01:2
    scatter(ts, smoothstep.(ts,0.5,0.2) .* (1 .- smoothstep.(ts, 1, 0.2)))
end

max_stars_repo_name: bgctw/MTKHelpers

max_issues_repo_name: bgctw/MTKHelpers

max_forks_repo_name: bgctw/MTKHelpers


text:
# Tests for interaction information function

ii = cmi - mi

# Test interaction information
@test get_interaction_information(arr1, arr2, arr3) ≈ ii
println("Interaction information passed.")

# Test interaction information formula
@test apply_interaction_information_formula(cmi, mi) ≈ ii
println("Interaction information formula passed.")


text:
"""
    Tail

Tail used in some of the tests.
Can be `one_tail` or `two_tails`.
"""
@enum Tail one_tail two_tails

"""
    StatisticalTest

Supertype for all test types in this package.

The lowest level types are all structs because some of them need to hold values.
A parameter can become a struct field when it's never required to infer the parameter from the other parameters.
For example, it doesn't make sense to use a power analysis to check whether one should use a one tailed or two tailed t-test.
As another example, it does make sense to use a power analysis to check the required sample size `n` (an a priori power analysis).

See the G*Power 3 paper for many parameters and noncentrality parameters
(https://doi.org/10.3758/BF03193146).

The huge collection of types isn't making this code very pretty.
Unfortunately, it seems to be a requirement when working in the frequentist world.
"""
abstract type StatisticalTest end

"""
    TTest <: StatisticalTest

Tests based around the Student's t-distribution.
"""
abstract type TTest <: StatisticalTest end

"""
    OneSampleTTest(tail::Tail) <: TTest

Test whether the sample differs from a constant.
"""
struct OneSampleTTest <: TTest
    tail::Tail
end

"""
    IndependentSamplesTTest(tail::Tail) <: TTest

Test a difference between two independent groups.
When using this type, make sure that `n` states the total number of samples in both groups.
Also known as a _independent means t-test_ or _independent samples t-test_.
"""
struct IndependentSamplesTTest <: TTest
    tail::Tail
end

"""
    DependentSamplesTTest(tail::Tail) <: TTest

Test a difference between pairs of values.
Also known as a _correlated pairs t-test_, _dependent samples t-test_ or _dependent means t-test_.
"""
struct DependentSamplesTTest <: TTest
    tail::Tail
end

"""
    PointBiserialTTest(tail::Tail) <: TTest

Test a difference between a continous and binary variable for the null hypothesis that the effect size is 0.
"""
struct PointBiserialTTest <: TTest
    tail::Tail
end

"""
    FTest <: StatisticalTest

Tests for the ratio between two variances.
Mostly known for linear regressions such as ANOVAs, MANOVAs and ANCOVAs.
"""
abstract type FTest <: StatisticalTest end

"""
    DeviationFromZeroMultipleRegression(n_predictors::Int) <: FTest

Deviation of R² from zero for multiple regression with `n_predictors`.
Combined with this test, the sample size `n` means the **total** sample size.
"""
struct DeviationFromZeroMultipleRegression <: FTest
    n_predictors::Int
end

"""
    IncreaseMultipleRegression(n_predictors::Int, n_tested_predictors::Int) <: FTest

Increase of R² for multiple regression with total number of predictors `n_predictors` and number of tested predictors `n_tested_predictors`.
"""
struct IncreaseMultipleRegression <: FTest
    n_predictors::Int
    n_tested_predictors::Int
end

"""
    OneWayANOVA(n_groups::Int) <: FTest

Test whether multiple means are equal.
Also known as a one-way fixed effects ANOVA.
"""
struct OneWayANOVA <: FTest
    n_groups::Int
end

"""
    MultifactorFixedEffectsANOVA(n_groups::Int, df::Int) <: FTest

Fixed effects, multifactor and planned comparisons ANOVA with `n_groups` total groups in the design and `df` degrees of freedom in the tested effect.
"""
struct MultifactorFixedEffectsANOVA <: FTest
    n_groups::Int
    df::Int
end

"""
    ConstantVectorHotellingTsqTest(n_response_variables::Int) <: FTest

Hotelling's T-square ``T^2`` to test whether a vector of means differ from a constant mean vector.
"""
struct ConstantVectorHotellingTsqTest <: FTest
    n_response_variables::Int
end

"""
    TwoVectorsHotellingTsqTest(n_response_variables::Int) <: FTest

Hotelling's T-square ``T^2`` to test whether two mean vectors differ.
"""
struct TwoVectorsHotellingTsqTest <: FTest
    n_response_variables::Int
end

"""
    ChisqTest <: StatisticalTest

Supertype for Chi-Square tests.
"""
abstract type ChisqTest <: StatisticalTest end

"""
    GoodnessOfFitChisqTest(df::Int) <: ChisqTest

Chi-square goodness of fit test for categorical variables with more than two levels.
Here, the degrees of freedom `df` are `n_groups - 1`.
"""
struct GoodnessOfFitChisqTest <: ChisqTest
    df::Int
end

"""
    ConstantVarianceChisqTest(tail::Tail) <: ChisqTest

Chi-square test for determining whether the population variance σ² equals a specific (constant) value.
The effect size is the variance `ratio` and defined as `ratio = σ² / c`.

!!! warn
    The result of this test is slightly different from G*Power 3.1.9.7 even though the code here is based on the paper.
    It could be that G*Power 3 has a different calculation for distribution scaling.
"""
struct ConstantVarianceChisqTest <: ChisqTest
    tail::Tail
end


text:
####################################################################################################
#                                          Infrastructure                                          #
####################################################################################################

################################################################################
#                                    Types                                     #
################################################################################

@enum RenderType SVG PNG PDF EPS

"The Cairo backend object.  Used to dispatch to CairoMakie methods."
struct CairoBackend <: AbstractPlotting.AbstractBackend
    typ::RenderType
    path::String
end

"""
    struct CairoScreen{S} <: AbstractScreen
A "screen" type for CairoMakie, which encodes a surface
and a context which are used to draw a Scene.
"""
struct CairoScreen{S} <: AbstractPlotting.AbstractScreen
    scene::Scene
    surface::S
    context::Cairo.CairoContext
    pane::Nothing # TODO: GtkWindowLeaf
end

function CairoBackend(path::String)
    ext = splitext(path)[2]
    typ = if ext == ".png"
        PNG
    elseif ext == ".svg"
        SVG
    elseif ext == ".pdf"
        PDF
    elseif ext == ".eps"
        EPS
    else
        error("Unsupported extension: $ext")
    end
    CairoBackend(typ, path)
end

# we render the scene directly, since we have
# no screen dependent state like in e.g. opengl
Base.insert!(screen::CairoScreen, scene::Scene, plot) = nothing

function Base.show(io::IO, ::MIME"text/plain", screen::CairoScreen{S}) where S
    println(io, "CairoScreen{$S} with surface:")
    println(io, screen.surface)
end

# Default to ARGB Surface as backing device
# TODO: integrate Gtk into this, so we can have an interactive display
"""
    CairoScreen(scene::Scene; antialias = Cairo.ANTIALIAS_BEST)
Create a CairoScreen backed by an image surface.
"""
function CairoScreen(scene::Scene; device_scaling_factor = 1, antialias = Cairo.ANTIALIAS_BEST)
    w, h = round.(Int, scene.camera.resolution[] .* device_scaling_factor)
    surf = Cairo.CairoARGBSurface(w, h)

    # this sets a scaling factor on the lowest level that is "hidden" so its even
    # enabled when the drawing space is reset for strokes
    # that means it can be used to increase or decrease the image resolution
    ccall((:cairo_surface_set_device_scale, LIB_CAIRO), Cvoid, (Ptr{Nothing}, Cdouble, Cdouble),
        surf.ptr, device_scaling_factor, device_scaling_factor)

    ctx = Cairo.CairoContext(surf)
    Cairo.set_antialias(ctx, antialias)

    return CairoScreen(scene, surf, ctx, nothing)
end

"""
    CairoScreen(
        scene::Scene, path::Union{String, IO}, mode::Symbol;
        antialias = Cairo.ANTIALIAS_BEST
    )
Creates a CairoScreen pointing to a given output path, with some rendering type defined by `mode`.
"""
function CairoScreen(scene::Scene, path::Union{String, IO}, mode::Symbol; device_scaling_factor = 1, antialias = Cairo.ANTIALIAS_BEST)

    # the surface size is the scene size scaled by the device scaling factor
    w, h = round.(Int, scene.camera.resolution[] .* device_scaling_factor)

    if mode == :svg
        surf = Cairo.CairoSVGSurface(path, w, h)
    elseif mode == :pdf
        surf = Cairo.CairoPDFSurface(path, w, h)
    elseif mode == :eps
        surf = Cairo.CairoEPSSurface(path, w, h)
    elseif mode == :png
        surf = Cairo.CairoARGBSurface(w, h)
    else
        error("No available Cairo surface for mode $mode")
    end

    # this sets a scaling factor on the lowest level that is "hidden" so its even
    # enabled when the drawing space is reset for strokes
    # that means it can be used to increase or decrease the image resolution
    ccall((:cairo_surface_set_device_scale, Cairo.libcairo), Cvoid, (Ptr{Nothing}, Cdouble, Cdouble),
        surf.ptr, device_scaling_factor, device_scaling_factor)

    ctx = Cairo.CairoContext(surf)
    Cairo.set_antialias(ctx, antialias)

    return CairoScreen(scene, surf, ctx, nothing)
end

function Base.delete!(screen::CairoScreen, scene::Scene, plot::AbstractPlot)
    # Currently, we rerender every time, so nothing needs
    # to happen here.  However, in the event that changes,
    # e.g. if we integrate a Gtk window, we may need to
    # do something here.
end

"Convert a rendering type to a MIME type"
function to_mime(x::RenderType)
    x == SVG && return MIME("image/svg+xml")
    x == PDF && return MIME("application/pdf")
    x == EPS && return MIME("application/postscript")
    return MIME("image/png")
end
to_mime(x::CairoBackend) = to_mime(x.typ)

################################################################################
#                              Rendering pipeline                              #
################################################################################

########################################
#           Drawing pipeline           #
########################################

# The main entry point into the drawing pipeline
function cairo_draw(screen::CairoScreen, scene::Scene)
    AbstractPlotting.update!(scene)
    draw_background(screen, scene)
    draw_scene(screen, scene)
    return
end

function draw_scene(screen::CairoScreen, scene::Scene)

    # get the root area to correct for its pixel size when translating
    root_area = AbstractPlotting.root(scene).px_area[]

    root_area_height = widths(root_area)[2]
    scene_area = pixelarea(scene)[]
    scene_height = widths(scene_area)[2]
    scene_x_origin, scene_y_origin = scene_area.origin

    Cairo.save(screen.context)

    # we need to translate x by the origin, so distance from the left
    # but y by the distance from the top, which is not the origin, but can
    # be calculated using the parent's height, the scene's height and the y origin
    # this is because y goes downwards in Cairo and upwards in AbstractPlotting

    top_offset = root_area_height - scene_height - scene_y_origin
    Cairo.translate(screen.context, scene_x_origin, top_offset)

    # clip the scene to its pixelarea
    Cairo.rectangle(screen.context, 0, 0, widths(scene_area)...)
    Cairo.clip(screen.context)

    for elem in scene.plots
        if to_value(get(elem, :visible, true))
            Cairo.save(screen.context)
            draw_plot(scene, screen, elem)
            Cairo.restore(screen.context)
        end
    end
    Cairo.restore(screen.context)

    for child in scene.children
        draw_scene(screen, child)
    end

    return
end

function draw_background(screen::CairoScreen, scene::Scene)
    cr = screen.context
    Cairo.save(cr)
    if scene.clear[]
        bg = to_color(theme(scene, :backgroundcolor)[])
        Cairo.set_source_rgba(cr, red(bg), green(bg), blue(bg), alpha(bg));
        r = pixelarea(scene)[]
        Cairo.rectangle(cr, origin(r)..., widths(r)...) # background
        fill(cr)
    end
    Cairo.restore(cr)
    foreach(child_scene-> draw_background(screen, child_scene), scene.children)
end

function draw_plot(scene::Scene, screen::CairoScreen, primitive::Combined)

    if isempty(primitive.plots)
        draw_atomic(scene, screen, primitive)
    else
        for plot in primitive.plots
            if to_value(get(primitive, :visible, true)) == true
                draw_plot(scene, screen, plot)
            end
        end
    end

    return
end

function draw_atomic(::Scene, ::CairoScreen, x)
    @warn "$(typeof(x)) is not supported by cairo right now"
end

function clear(screen::CairoScreen)
    ctx = screen.ctx
    Cairo.save(ctx)
    Cairo.set_operator(ctx, Cairo.OPERATOR_SOURCE)
    Cairo.set_source_rgba(ctx, rgbatuple(screen.scene[:backgroundcolor])...);
    Cairo.paint(ctx)
    Cairo.restore(ctx)
end

#########################################
# Backend interface to AbstractPlotting #
#########################################

function AbstractPlotting.backend_display(x::CairoBackend, scene::Scene)
    return open(x.path, "w") do io
        AbstractPlotting.backend_show(x, io, to_mime(x), scene)
    end
end

AbstractPlotting.backend_showable(x::CairoBackend, ::MIME"image/svg+xml", scene::Scene) = x.typ == SVG
AbstractPlotting.backend_showable(x::CairoBackend, ::MIME"application/pdf", scene::Scene) = x.typ == PDF
AbstractPlotting.backend_showable(x::CairoBackend, ::MIME"application/postscript", scene::Scene) = x.typ == EPS
AbstractPlotting.backend_showable(x::CairoBackend, ::MIME"image/png", scene::Scene) = x.typ == PNG

function AbstractPlotting.backend_show(x::CairoBackend, io::IO, ::MIME"image/svg+xml", scene::Scene)

    pt_per_unit = get(io, :pt_per_unit, 1.0)

    screen = CairoScreen(scene, io, :svg; device_scaling_factor = pt_per_unit)
    cairo_draw(screen, scene)
    Cairo.finish(screen.surface)
    return screen
end

function AbstractPlotting.backend_show(x::CairoBackend, io::IO, ::MIME"application/pdf", scene::Scene)

    pt_per_unit = get(io, :pt_per_unit, 1.0)

    screen = CairoScreen(scene, io, :pdf; device_scaling_factor = pt_per_unit)
    cairo_draw(screen, scene)
    Cairo.finish(screen.surface)
    return screen
end

function AbstractPlotting.backend_show(x::CairoBackend, io::IO, ::MIME"application/postscript", scene::Scene)

    pt_per_unit = get(io, :pt_per_unit, 1.0)

    screen = CairoScreen(scene, io, :eps; device_scaling_factor = pt_per_unit)

    cairo_draw(screen, scene)
    Cairo.finish(screen.surface)
    return screen
end

function AbstractPlotting.backend_show(x::CairoBackend, io::IO, m::MIME"image/png", scene::Scene)

    # multiply the resolution of the png with this factor for more or less detail
    # while relative line and font sizes are unaffected
    px_per_unit = get(io, :px_per_unit, 1.0)
    # create an ARGB surface, to speed up drawing ops.
    screen = CairoScreen(scene; device_scaling_factor = px_per_unit)
    cairo_draw(screen, scene)
    Cairo.write_to_png(screen.surface, io)
    return screen
end

########################################
#    Fast colorbuffer for recording    #
########################################

function AbstractPlotting.colorbuffer(screen::CairoScreen)
    # extract scene
    scene = screen.scene
    # get resolution
    w, h = size(scene)
    # preallocate an image matrix
    img = Matrix{ARGB32}(undef, w, h)
    # create an image surface to draw onto the image
    surf = Cairo.CairoImageSurface(img)
    # draw the scene onto the image matrix
    ctx = Cairo.CairoContext(surf)
    scr = CairoScreen(scene, surf, ctx, nothing)

    cairo_draw(scr, scene)

    # x and y are flipped - return the transpose
    return permutedims(img)
end


text:
using TerminalUserInterfaces
const TUI = TerminalUserInterfaces
using Random

function main()
    TUI.initialize()
    y, x = 1, 1

    count = 1
    t = TUI.Terminal()

    # TUI.enableRawMode()
    TUI.clear_screen()
    TUI.hide_cursor()

    while true

        w, h = TUI.terminal_size()

        r = TUI.Rect(x, y, w ÷ 2, h ÷ 2)

        b = TUI.Block(title = "Bar Chart")
        p = TUI.BarChart(
            block = b,
            data = [
                ("B1", 1 * count)
                ("B2", 2)
                ("B3", 3 * count)
                ("B4", 4)
                ("B1", 5 * count)
                ("B2", 6)
                ("B3", 7 * count)
                ("B4", 8)
            ],
        )

        TUI.draw(t, p, r)

        TUI.flush(t)

        c = TUI.get_event(t)

        if c == 'j'
            count += 1
        elseif c == 'k'
            count -= 1
        elseif c == 'q'
            break
        end

        if count < 1
            count = 1
        end

    end

    TUI.cleanup()

end

main()


text:
#Ellipse methods

Ellipse(x::Int, y::Int, ρx::T, ρy::U) where {T<:Real, U<:Real} = Ellipse(Point(x,y), ρx, ρy)
Ellipse(p::CartesianIndex{2}, ρx::T, ρy::U) where {T<:Real, U<:Real} = Ellipse(Point(p), ρx, ρy)
Ellipse(circle::CirclePointRadius) = Ellipse(circle.center, circle.ρ, circle.ρ)

function draw!(img::AbstractArray{T, 2}, ellipse::Ellipse, color::T) where T<:Colorant
	ys = Int[]
	xs = Int[]
	for i in ellipse.center.y : ellipse.center.y + ellipse.ρy
		for j in ellipse.center.x : ellipse.center.x + ellipse.ρx
			val = ((i - ellipse.center.y) / ellipse.ρy) ^ 2 + ((j - ellipse.center.x) / ellipse.ρx) ^ 2
			if val < 1
				push!(ys, i)
				push!(xs, j)
			end
		end
	end
	for (yi, xi) in zip(ys, xs)
		drawifinbounds!(img, yi, xi, color)
		drawifinbounds!(img,2 * ellipse.center.y - yi, xi, color)
		drawifinbounds!(img,yi, 2 * ellipse.center.x - xi, color)
		drawifinbounds!(img, 2 * ellipse.center.y - yi, 2 * ellipse.center.x - xi, color)
	end
	img
end