text:
using Compose, Test, Random, Colors

# must be before importing cairo
@testset "missing cairo errors" begin
    ctx = compose(context(), circle(), fill("gold"))
    @test_throws ErrorException ctx |> PNG("test.png")
    @test_throws ErrorException ctx |> PDF("test.pdf")
    @test_throws ErrorException ctx |> PS("test.ps")

    io = IOBuffer()
    @test_throws ErrorException show(io, MIME("image/png"), ctx)
    @test_throws ErrorException show(io, MIME("application/pdf"), ctx)
    @test_throws ErrorException show(io, MIME("application/ps"), ctx)
end

import Cairo

# showcompact
@testset "printing" begin
    @testset "context" begin
        io = IOBuffer()
        tomato_bisque = compose(context(),
                    (context(), circle(), fill(colorant"bisque")),
                    (context(), rectangle(), fill(colorant"tomato")))

        # compact printing
        show(IOContext(io, :compact=>true), tomato_bisque)
        str = String(take!(io))
        @test str == "Context(Context(R,f),Context(C,f))"

        # full printing
        show(io, context())
        str = String(take!(io))
        @test str == "Context(Measures.BoundingBox{Tuple{Measures.Length{:w,Float64},Measures.Length{:h,Float64}},Tuple{Measures.Length{:w,Float64},Measures.Length{:h,Float64}}}((0.0w, 0.0h), (1.0w, 1.0h)), nothing, nothing, nothing, nothing, List([]), List([]), List([]), 0, false, false, false, false, nothing, nothing, 0.0, Symbol(\"\"))"
    end
    @testset "table" begin
        t = Compose.Table(1, 1, UnitRange(1,1), UnitRange(3:3), aspect_ratio=1.6)
        io = IOBuffer()

        # compact printing
        show(IOContext(io, :compact=>true), t)
        str = String(take!(io))
        @test str == "1x1 Table:\n  Context[]\n"

        # full printing
        show(io, t)
        str = String(take!(io))
        @test str == "Compose.Table(Array{Context,1}[[]], 3:3, 1:1, nothing, nothing, 1.6, Any[], nothing, 0, false, false)"
    end
end

# Tagging
points(xa, ya) = [(x, y) for (x, y) in zip(xa, ya)]

pnts = points(rand(5), rand(5))
p = polygon(pnts, :mypoints)
@test p.tag == :mypoints

r = rectangle(0, 1, 0.5, 0.8, :box)
@test r.tag == :box
r = rectangle(rand(5),rand(5),rand(5),rand(5),:manybox)
@test r.tag == :manybox

c = circle(0, 0.8, 1.2, :circle)
@test c.tag == :circle
c = circle(rand(5), rand(5), rand(5), :data)
@test c.tag == :data

elps = ellipse(0, 0.8, 1.2, 1.5, :ellipse)
@test elps.tag == :ellipse
elps = ellipse(rand(5),rand(5),rand(5),rand(5),:manyellipse)
@test elps.tag == :manyellipse

txt = text(1.5, 15, "hello", tag=:hello)
@test txt.tag == :hello
txt = text(rand(5),rand(5),map(x->randstring(5), 1:5), tag=:random)
@test txt.tag == :random

ln = line(pnts, :line)
@test ln.tag == :line

crv = curve((0,0), (1,0.5), (0.2,0.3), (0.7,-2.4), :curve)
@test crv.tag == :curve
crv = curve(pnts, pnts, pnts, pnts, :manycurve)
@test crv.tag == :manycurve

bm = bitmap("fake", rand(UInt8,10), 0, 1, 0.8, 0.7, :image)
@test bm.tag == :image

# type definitions & constructors (issue #149)
@test isa(Compose.polygon(), Compose.Polygon)
@test isa(Compose.polygon([(1,2),(3,5),(4,2)]), Compose.Polygon)

@test isa(Compose.rectangle(), Compose.Rectangle)
@test isa(Compose.rectangle(0,1,0.3,0.8), Compose.Rectangle)
@test isa(Compose.rectangle(rand(5),rand(5),rand(5),rand(5)), Compose.Rectangle)

@test isa(Compose.circle(), Compose.Circle)
@test isa(Compose.circle(3.2,1.4,0.8), Compose.Circle)
@test isa(Compose.circle(rand(5), rand(5), rand(5)), Compose.Circle)

@test isa(Compose.ellipse(), Compose.Ellipse)
@test isa(Compose.ellipse(0.5,0.5,0.3,0.2), Compose.Ellipse)
@test isa(Compose.ellipse(rand(5), rand(5), rand(5), rand(5)), Compose.Ellipse)

@test isa(Compose.text(0.5,0.4,"hello"), Compose.Text)
@test isa(Compose.text(rand(5),rand(5),["hello","there"]), Compose.Text)

@test isa(Compose.line(), Compose.Line)
@test isa(Compose.line([(1,2),(3,5),(4,2)]), Compose.Line)

# issue #172: default circle(xs, ys, rs) radius measure is context units
@test isequal(circle([0.5], [0.5], [0.1]).primitives[1].radius, 0.1cx)

# Gadfly issue 857 and 436
# make sure that newlines are respected by `text_extents`
font_family = "'PT Sans Caption','Helvetica Neue','Helvetica',sans-serif"
oneline = text_extents(font_family, 8pt, "PegPeg")[1]
twolines = text_extents(font_family, 8pt, "Peg\nPeg")[1]
@test round(Int, oneline[1] / twolines[1]) == 2
@test round(Int, twolines[2] / oneline[2]) == 2

# PR 252
@test Compose.parse_colorant("red") == RGB(1.0,0.0,0.0)
@test Compose.parse_colorant(colorant"red") == RGB(1.0,0.0,0.0)
@test Compose.parse_colorant(["red","blue"]) == [RGB(1.0,0.0,0.0), RGB(0.0,0.0,1.0)]
@test Compose.parse_colorant(("red","blue")) == [RGB(1.0,0.0,0.0), RGB(0.0,0.0,1.0)]
@test Compose.parse_colorant("red","blue") == [RGB(1.0,0.0,0.0), RGB(0.0,0.0,1.0)]
@test Compose.parse_colorant("red",colorant"blue") == [RGB(1.0,0.0,0.0), RGB(0.0,0.0,1.0)]

# PR 263
@test ~ @isdefined Fontconfig
@test Compose.pango_to_svg("hello world") == "hello world"
import Fontconfig
@test Compose.pango_to_svg("hello world") == "hello world"

@testset "pango" begin
    @test Compose.escape_tex_chars("\\") == "\\textbackslash{}"
    @test Compose.pango_to_pgf("hello\\") == "\\text{hello\\textbackslash{}}"
end

@testset "pango utf-8 text_extents" begin
    @test @isdefined Fontconfig
    w1 = Compose.text_extents("", 8pt, "α")[1]
    w2 = Compose.text_extents("", 8pt, "αα")[1]
    @test w1 < w2
end

@testset "table" begin
    @testset "force aspect ratio" begin
        tbl = Compose.Table(1, 1, UnitRange(1,1), UnitRange(3:3), aspect_ratio=1.6);
        x_solution = [0.0, 5.8, 11.8]
        w_solution = [5.8, 6.0, 119.6]
        y_solution = [0.0, 85.3]
        h_solution = [85.3, 4.7]
        x0, w0 = copy(x_solution), copy(w_solution)
        Compose.force_aspect_ratio!(tbl, x_solution, y_solution, w_solution, h_solution)
        @test x_solution == x0
        @test w_solution == w0
        @test y_solution ≈ [5.275, 80.025]
        @test h_solution == [74.75, 4.7]
    end
end

@testset "Image keyword args" begin
    @test isa(PNG(4inch, 3inch, dpi=172), Compose.Image)
end

@testset "No Global RNG contamination" begin
    Random.seed!(23)
    withoutcompose = rand()
    Random.seed!(23)
    draw(SVG(10cm, 8cm, false), compose(context()))
    withcompose = rand()
    @test withoutcompose == withcompose
end

@testset "Image fillopacity" begin
    properties = [fill(["red","blue"]), fillopacity(0.3), stroke("black")]
    img1 = PNG(); Compose.push_property_frame(img1, properties)
    img2 = SVG(); Compose.push_property_frame(img2, properties)
    img3 = PGF(); Compose.push_property_frame(img3, properties)
    @test getfield.(img1.vector_properties[Compose.Property{Compose.FillOpacityPrimitive}].primitives, :value) == [0.3, 0.3]
    @test occursin("fill-opacity=\"0.3\"", String(img2.out.data))
    @test img3.fill_opacity == 0.3
end

@testset "Missing" begin
    @test Compose.x_measure(missing)===NaN*cx
    @test Compose.y_measure(missing)===NaN*cy
end


text:
using Adapt
using Test

# custom array type

struct CustomArray{T,N} <: AbstractArray{T,N}
    arr::AbstractArray
end

CustomArray(x::AbstractArray{T,N}) where {T,N} = CustomArray{T,N}(x)
Adapt.adapt_storage(::Type{<:CustomArray}, xs::AbstractArray) = CustomArray(xs)

Base.size(x::CustomArray, y...) = size(x.arr, y...)
Base.getindex(x::CustomArray, y...) = getindex(x.arr, y...)

const val = CustomArray{Float64,2}(rand(2,2))

# basic adaption
@test adapt(CustomArray, val.arr) == val
@test adapt(CustomArray, val.arr) isa CustomArray

# idempotency
@test adapt(CustomArray, val) == val
@test adapt(CustomArray, val) isa CustomArray

# custom wrapper
struct Wrapper{T}
    arr::T
end
Wrapper(x::T) where T = Wrapper{T}(x)
Adapt.adapt_structure(to, xs::Wrapper) = Wrapper(adapt(to, xs.arr))
@test adapt(CustomArray, Wrapper(val.arr)) == Wrapper(val)
@test adapt(CustomArray, Wrapper(val.arr)) isa Wrapper{<:CustomArray}

## base wrappers

@test adapt(CustomArray, (val.arr,)) == (val,)
@test @allocated(adapt(nothing, ())) == 0
@test @allocated(adapt(nothing, (1,))) == 0
@test @allocated(adapt(nothing, (1,2,3,4,5,6,7,8,9,10))) == 0

@test adapt(CustomArray, (a=val.arr,)) == (a=val,)

@test adapt(CustomArray, view(val.arr,:,:)) == view(val,:,:)
const inds = CustomArray{Int,1}([1,2])
@test adapt(CustomArray, view(val.arr,inds.arr,:)) == view(val,inds,:)

# NOTE: manual creation of PermutedDimsArray because permutedims collects
@test adapt(CustomArray, PermutedDimsArray(val.arr,(2,1))) == PermutedDimsArray(val,(2,1))

# NOTE: manual creation of ReshapedArray because Base.Array has an optimized `reshape`
@test adapt(CustomArray, Base.ReshapedArray(val.arr,(2,2),())) == reshape(val,(2,2))

using LinearAlgebra

@test adapt(CustomArray, val.arr') == val'

@test adapt(CustomArray, transpose(val.arr)) == transpose(val)

@test adapt(CustomArray, LowerTriangular(val.arr)) == LowerTriangular(val)
@test adapt(CustomArray, UnitLowerTriangular(val.arr)) == UnitLowerTriangular(val)
@test adapt(CustomArray, UpperTriangular(val.arr)) == UpperTriangular(val)
@test adapt(CustomArray, UnitUpperTriangular(val.arr)) == UnitUpperTriangular(val)

@test adapt(CustomArray, Diagonal(val.arr)) == Diagonal(val)
@test adapt(CustomArray, Tridiagonal(val.arr)) == Tridiagonal(val)

ext: jl


text:
# require script: loss.jl, gradient.jl
# require package: ForwardDiff, LinearAlgebra, GenericLinearAlgebra, Statistics

# test test_grad_kurt function
@testset "Test test_grad_kurt" begin
    for idx = 1: 10
        s = 3
        Y = [randn(10,20) for i = 1: s]
        W = randn(s, s)
        @test rel_error(ForwardDiff.gradient(x -> neg_abs_sum_free_kurt(x'*Y), W)
            , grad_neg_abs_sum_free_kurt(W, Y)) < 1e-8
    end
end

# test grad_sum_free_ent function
@testset "Test grad_sum_free_ent $mat" for mat in ["her", "rec"]
    # test for Hermitian matrices
    if mat == "her"
        G = randn(10,10)
        Y = [G + G', G*G']
        W = randn(2,2)
        @test rel_error(ForwardDiff.gradient(x -> sum_free_ent(x'*Y; mat = "her"), W)
        , grad_sum_free_ent(W, Y; mat = "her")) < 1e-8
    end

    # test for rectangular matrices
    if mat == "rec"
        s = 3
        Y = [randn(10,20) for i = 1: s]
        W = randn(s,s)
        @test rel_error(ForwardDiff.gradient(x -> sum_free_ent(x'*Y; mat = "rec"), W)
            , grad_sum_free_ent(W, Y; mat = "rec")) < 1e-8
    end
end


text:
#=
This file is auto-generated. Do not edit.
=#
"""
    mutable struct SCRX <: AVR
        Ta_Tb::Float64
        Tb::Float64
        K::Float64
        Te::Float64
        Efd_lim::NamedTuple{(:min, :max), Tuple{Float64, Float64}}
        switch::Int
        rc_rfd::Float64
        V_ref::Float64
        ext::Dict{String, Any}
        states::Vector{Symbol}
        n_states::Int
        states_types::Vector{StateTypes}
        internal::InfrastructureSystemsInternal
    end

This exciter is based on an IEEE type SCRX solid state exciter.  The output field voltage is varied by a control system to maintain the system voltage at Vref.  Please note that this exciter model has no initialization capabilities - this means that it will respond to whatever inputs it receives regardless of the state of the machine model.

# Arguments
- `Ta_Tb::Float64`: Lead input constant ratio, validation range: `(0.05, 0.3)`, action if invalid: `error`
- `Tb::Float64`: Lag input constant in s, validation range: `(5, 20)`, action if invalid: `error`
- `K::Float64`: Regulator Gain, validation range: `(20, 100)`, action if invalid: `warn`
- `Te::Float64`: Regulator Time Constant, validation range: `(0, 1)`, action if invalid: `warn`
- `Efd_lim::NamedTuple{(:min, :max), Tuple{Float64, Float64}}`: Field Voltage regulator limits (regulator output) (Efd_min, Efd_max)
- `switch::Int`: Switch, validation range: `(0, 1)`, action if invalid: `error`
- `rc_rfd::Float64`: Field current capability. Set = 0 for negative current capability. Typical value 10, validation range: `(0, 10)`, action if invalid: `warn`
- `V_ref::Float64`: Reference Voltage Set-point, validation range: `(0, nothing)`
- `ext::Dict{String, Any}`
- `states::Vector{Symbol}`: The states are:
	Vr1: First integrator,
	Vr2: Second integrator
- `n_states::Int`: SCRX has 2 states
- `states_types::Vector{StateTypes}`: SCRX has 2 differential states
- `internal::InfrastructureSystemsInternal`: power system internal reference, do not modify
"""
mutable struct SCRX <: AVR
    "Lead input constant ratio"
    Ta_Tb::Float64
    "Lag input constant in s"
    Tb::Float64
    "Regulator Gain"
    K::Float64
    "Regulator Time Constant"
    Te::Float64
    "Field Voltage regulator limits (regulator output) (Efd_min, Efd_max)"
    Efd_lim::NamedTuple{(:min, :max), Tuple{Float64, Float64}}
    "Switch"
    switch::Int
    "Field current capability. Set = 0 for negative current capability. Typical value 10"
    rc_rfd::Float64
    "Reference Voltage Set-point"
    V_ref::Float64
    ext::Dict{String, Any}
    "The states are:
	Vr1: First integrator,
	Vr2: Second integrator"
    states::Vector{Symbol}
    "SCRX has 2 states"
    n_states::Int
    "SCRX has 2 differential states"
    states_types::Vector{StateTypes}
    "power system internal reference, do not modify"
    internal::InfrastructureSystemsInternal
end

function SCRX(Ta_Tb, Tb, K, Te, Efd_lim, switch, rc_rfd, V_ref=1.0, ext=Dict{String, Any}(), )
    SCRX(Ta_Tb, Tb, K, Te, Efd_lim, switch, rc_rfd, V_ref, ext, [:Vr1, :Vr2], 2, [StateTypes.Differential, StateTypes.Hybrid], InfrastructureSystemsInternal(), )
end

function SCRX(; Ta_Tb, Tb, K, Te, Efd_lim, switch, rc_rfd, V_ref=1.0, ext=Dict{String, Any}(), states=[:Vr1, :Vr2], n_states=2, states_types=[StateTypes.Differential, StateTypes.Hybrid], internal=InfrastructureSystemsInternal(), )
    SCRX(Ta_Tb, Tb, K, Te, Efd_lim, switch, rc_rfd, V_ref, ext, states, n_states, states_types, internal, )
end

# Constructor for demo purposes; non-functional.
function SCRX(::Nothing)
    SCRX(;
        Ta_Tb=0,
        Tb=0,
        K=0,
        Te=0,
        Efd_lim=(min=0.0, max=0.0),
        switch=0,
        rc_rfd=0,
        V_ref=0,
        ext=Dict{String, Any}(),
    )
end

"""Get [`SCRX`](@ref) `Ta_Tb`."""
get_Ta_Tb(value::SCRX) = value.Ta_Tb
"""Get [`SCRX`](@ref) `Tb`."""
get_Tb(value::SCRX) = value.Tb
"""Get [`SCRX`](@ref) `K`."""
get_K(value::SCRX) = value.K
"""Get [`SCRX`](@ref) `Te`."""
get_Te(value::SCRX) = value.Te
"""Get [`SCRX`](@ref) `Efd_lim`."""
get_Efd_lim(value::SCRX) = value.Efd_lim
"""Get [`SCRX`](@ref) `switch`."""
get_switch(value::SCRX) = value.switch
"""Get [`SCRX`](@ref) `rc_rfd`."""
get_rc_rfd(value::SCRX) = value.rc_rfd
"""Get [`SCRX`](@ref) `V_ref`."""
get_V_ref(value::SCRX) = value.V_ref
"""Get [`SCRX`](@ref) `ext`."""
get_ext(value::SCRX) = value.ext
"""Get [`SCRX`](@ref) `states`."""
get_states(value::SCRX) = value.states
"""Get [`SCRX`](@ref) `n_states`."""
get_n_states(value::SCRX) = value.n_states
"""Get [`SCRX`](@ref) `states_types`."""
get_states_types(value::SCRX) = value.states_types
"""Get [`SCRX`](@ref) `internal`."""
get_internal(value::SCRX) = value.internal

"""Set [`SCRX`](@ref) `Ta_Tb`."""
set_Ta_Tb!(value::SCRX, val) = value.Ta_Tb = val
"""Set [`SCRX`](@ref) `Tb`."""
set_Tb!(value::SCRX, val) = value.Tb = val
"""Set [`SCRX`](@ref) `K`."""
set_K!(value::SCRX, val) = value.K = val
"""Set [`SCRX`](@ref) `Te`."""
set_Te!(value::SCRX, val) = value.Te = val
"""Set [`SCRX`](@ref) `Efd_lim`."""
set_Efd_lim!(value::SCRX, val) = value.Efd_lim = val
"""Set [`SCRX`](@ref) `switch`."""
set_switch!(value::SCRX, val) = value.switch = val
"""Set [`SCRX`](@ref) `rc_rfd`."""
set_rc_rfd!(value::SCRX, val) = value.rc_rfd = val
"""Set [`SCRX`](@ref) `V_ref`."""
set_V_ref!(value::SCRX, val) = value.V_ref = val
"""Set [`SCRX`](@ref) `ext`."""
set_ext!(value::SCRX, val) = value.ext = val
"""Set [`SCRX`](@ref) `states_types`."""
set_states_types!(value::SCRX, val) = value.states_types = val


text:
# Copyright (c) 2014: SCS.jl contributors
#
# Use of this source code is governed by an MIT-style license that can be found
# in the LICENSE.md file or at https://opensource.org/licenses/MIT.

if get(ENV, "BUILDKITE", "false") == "true"
    # This file requires a GPU in order to run. It gets tested as part of the
    # JuliaGPU CI on Buildkite. Contact @odow for more details.
    include("test_gpu.jl")
    exit(0)
end

using Test
using SCS

include("test_problems.jl")
for s in SCS.available_solvers
    feasible_basic_problems(s)
    test_options(s)
end

include("MOI_wrapper.jl")


text:
drop(gen::Function, n::Integer) = (for _ in 1:n gen() end; gen)
take(gen::Function, n::Integer) = collect(gen() for _ in 1:n)

function pgen(n::Number)
    x = 0
    return () -> (x += 1) ^ n
end

function genfilter(g1::Function, g2::Function)
    local r1
    local r2 = g2()
    return () -> begin
        r1 = g1()
        while r2 <  r1 r2 = g2() end
        while r1 == r2 r1 = g1() end
        return r1
    end
end

@show take(drop(genfilter(pgen(2), pgen(3)), 20), 10)

max_stars_repo_name: ethansaxenian/RosettaDecode

max_issues_repo_name: ethansaxenian/RosettaDecode

max_forks_repo_name: ethansaxenian/RosettaDecode


text:
include("plot_vb_results.jl")

# Read CB data
y, markernames = let
  function separatesamples(Y)
    sample_ids = sort(unique(Y.sample_id))
    return Matrix.(Y[Y.sample_id .== i, Not(:sample_id)]
                   for i in sample_ids)
  end

  path_to_data = "../data/cb_transformed_reduced.csv"
  Y = coalesce.(CSV.read(path_to_data), NaN)
  (separatesamples(Y), names(Y))
end

paths = [joinpath(root, file)
         for (root, dirs, files) in walkdir("results")
         for file in files
         if file == "output.bson"]

for path in paths
  println("Processing: $(path)")
  makeplots(y=y, path_to_output=path,
            markernames=markernames, nlam=30)
end

max_stars_repo_name: luiarthur/CytofResearch

max_issues_repo_name: luiarthur/CytofResearch

max_forks_repo_name: luiarthur/CytofResearch


text:
# *****************************************************************************
# Written by Ritchie Lee, ritchie.lee@sv.cmu.edu
# *****************************************************************************
# Copyright ã ``2015, United States Government, as represented by the
# Administrator of the National Aeronautics and Space Administration. All
# rights reserved.  The Reinforcement Learning Encounter Simulator (RLES)
# platform is licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. You
# may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0. Unless required by applicable
# law or agreed to in writing, software distributed under the License is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the specific language
# governing permissions and limitations under the License.
# _____________________________________________________________________________
# Reinforcement Learning Encounter Simulator (RLES) includes the following
# third party software. The SISLES.jl package is licensed under the MIT Expat
# License: Copyright (c) 2014: Youngjun Kim.
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED
# "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
# NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
# PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# *****************************************************************************

"""
Cross Entropy Method Optimization that uses a probabilistic context-free
grammar as the distribution.
"""
module CE

export CEESParams, CEESResult, ce_search, exprsearch, SearchParams, SearchResult, get_derivtree
export Samples

using Reexport
using ExprSearch
using DepthAwarePCFGs
using RLESUtils, GitUtils, CPUTimeUtils, Observers, LogSystems, MemPools, RandChannels
using LinearDerivTrees
@reexport using DerivationTrees  #for pretty strings
using CPUTime
using DerivTreeVis
using RLESTypes.SymbolTable

import Compat.view
import ..ExprSearch: exprsearch, get_fitness, get_derivtree, get_expr
import DerivationTrees.get_children

typealias MinDepthByRule Dict{Symbol,Int64}
typealias MinDepthByAction Dict{Symbol,Vector{Int64}}

immutable RuleNotFoundException <: Exception end
immutable DepthExceededException <: Exception end

const DEFAULT_EXPR = :()

include("logdefs.jl")

immutable CEESParams <: SearchParams
    num_samples::Int64  #number of samples
    iterations::Int64     #number of iterations
    elite_frac::Float64 #fraction of samples considered elite
    w_new::Float64      #blend new/old distributions (w_new) * dpcfg_new + (1-w_new) * dpcfg_old
    w_prior::Float64      #blend with prior dpcfg = (1-w_prior) * dpcfg + (w_prior) * dpcfg_prior
    maxdepth::Int64     #maximum depth of derivation tree (steps is unlimited)
    default_expr        #if derivation is incomplete, use default expr
    randchannel_width::Int64  #number of random numbers to pre-generate per sample
    logsys::LogSystem   #to manage logging
    userargs::SymbolTable #passed to get_fitness if specified
end
function CEESParams(num_samples::Int64, iterations::Int64, elite_frac::Float64,
    w_new::Float64, w_prior::Float64, maxdepth::Int64, default_expr, randchannel_width::Int64,
    logsys::LogSystem=logsystem(); userargs::SymbolTable=SymbolTable())

    CEESParams(num_samples, iterations, elite_frac, w_new, w_prior, maxdepth, default_expr,
        randchannel_width, logsys, userargs)
end

type CEESResult <: SearchResult
    tree::DerivationTree
    fitness::Float64
    expr
    best_at_eval::Int64
    totalevals::Int64
end
CEESResult(grammar::Grammar) = CEESResult(DerivationTree(DerivTreeParams(grammar)), realmax(Float64),
    DEFAULT_EXPR, 0, 0)

exprsearch(p::CEESParams, problem::ExprProblem) = ce_search(p, problem::ExprProblem)

get_derivtree(result::CEESResult) = result.tree
get_expr(result::CEESResult) = result.expr
get_fitness(result::CEESResult) = result.fitness

typealias Sample LinearDerivTree
typealias Samples Vector{Sample}

function ce_search(p::CEESParams, problem::ExprProblem)
    @notify_observer(p.logsys.observer, "verbose1", ["Starting CE search"])
    @notify_observer(p.logsys.observer, "computeinfo", ["starttime", string(now())])

    initialize!(problem)
    cfg = get_grammar(problem)
    result = CEESResult(cfg)
    dpcfg = DepthAwarePCFG(cfg) #initialize to uniform probabilities
    dpcfg_elite = copy(dpcfg) #for blending of new and old
    dpcfg_prior = copy(dpcfg) #uniform prior to ensure full support over domain

    @notify_observer(p.logsys.observer, "dpcfg", [0, dpcfg])

    tree_params = LDTParams(cfg, typemax(Int64))
    samples = [LinearDerivTree(tree_params; nodepool=MemPool(DerivTreeNode, 20, 500))
        for i=1:p.num_samples]
    rc = RandChannel(p.num_samples, p.randchannel_width)
    wrc_vec = [WrappedRandChannel(rc, 0) for i=1:Threads.nthreads()]
    fitness = realmax(Float64)

    tstart = CPUtime_start()
    iter = 1
    while iter <= p.iterations
        # Draw samples from dpcfg
        if iter == 1
            ramped_rand!(wrc_vec, samples, dpcfg, p.maxdepth)
        else
            parallel_rand!(wrc_vec, samples, dpcfg, p.maxdepth)
        end

        # Evaluate fitnesses
        fitnesses = parallel_evaluate(p, samples, result, problem, p.default_expr)

        # Sort in ascending order, lower is better
        order = sortperm(fitnesses)

        # Compute elites
        elite_n = round(Int, p.elite_frac * p.num_samples)
        elite_samples = samples[order[1:elite_n]]

        @notify_observer(p.logsys.observer, "elite_samples", [iter, elite_samples])

        # Fit elite distribution
        fit_mle!(dpcfg_elite, elite_samples)

        @notify_observer(p.logsys.observer, "dpcfg_elite", [iter, dpcfg_elite])

        # Blend old and new distributions
        # dpcfg = (w_new) * dpcfg_elite + (1-w_new) * dpcfg_old
        weighted_sum!(dpcfg, 1.0-p.w_new, dpcfg_elite, p.w_new)

        # Include uniform prior
        # dpcfg = (1-w_prior) * dpcfg + (w_prior) * dpcfg_prior
        weighted_sum!(dpcfg, 1.0-p.w_prior, dpcfg_prior, p.w_prior)

        @notify_observer(p.logsys.observer, "dpcfg", [iter, dpcfg])

        @assert result.fitness <= fitnesses[order[1]] #result.fitness should be tracking global minimum

        fitness = get_fitness(result)
        code = string(get_expr(result))
        nevals = iter * p.num_samples

        @notify_observer(p.logsys.observer, "elapsed_cpu_s", [nevals, CPUtime_elapsed_s(tstart)])
        @notify_observer(p.logsys.observer, "fitness", Any[iter, fitness])
        @notify_observer(p.logsys.observer, "code", Any[iter, code])
        @notify_observer(p.logsys.observer, "samples", Any[iter, samples])
        @notify_observer(p.logsys.observer, "current_best", [nevals, fitness, code])

        iter += 1
        resample!(rc)
    end

    #dealloc trees in samples
    for s in samples
        rm_tree!(s.derivtree)
    end

    @notify_observer(p.logsys.observer, "result", [result.fitness, string(result.expr),
        result.best_at_eval, result.totalevals])

    #meta info
    @notify_observer(p.logsys.observer, "computeinfo", ["endtime",  string(now())])
    @notify_observer(p.logsys.observer, "computeinfo", ["hostname", gethostname()])
    @notify_observer(p.logsys.observer, "computeinfo", ["gitSHA",  get_SHA(dirname(@__FILE__))])
    @notify_observer(p.logsys.observer, "computeinfo", ["cpu_time", CPUtime_elapsed_s(tstart)])
    @notify_observer(p.logsys.observer, "parameters", ["num_samples", p.num_samples])
    @notify_observer(p.logsys.observer, "parameters", ["iterations", p.iterations])
    @notify_observer(p.logsys.observer, "parameters", ["elite_frac", p.elite_frac])
    @notify_observer(p.logsys.observer, "parameters", ["w_new", p.w_new])
    @notify_observer(p.logsys.observer, "parameters", ["w_prior", p.w_prior])
    @notify_observer(p.logsys.observer, "parameters", ["maxdepth", p.maxdepth])
    @notify_observer(p.logsys.observer, "parameters", ["default_expr", string(p.default_expr)])

    result
end

function ramped_rand!{T}(wrc_vec::Vector{WrappedRandChannel{T}}, samples::Vector{LinearDerivTree},
    dpcfg::DepthAwarePCFG, maxdepth::Int64)

    startmindepth = dpcfg.depths_by_rule[:start]
    iter = cycle(startmindepth:maxdepth)
    s = start(iter)
    for i = 1:length(samples)
        (d, s) = next(iter, s)
        wrc = wrc_vec[Threads.threadid()]
        set_channel!(wrc, i)
        rand!(wrc, samples[i], dpcfg, d)
    end
    samples
end

function parallel_rand!{T}(wrc_vec::Vector{WrappedRandChannel{T}}, samples::Vector{LinearDerivTree},
    dpcfg::DepthAwarePCFG, maxdepth::Int64)
    for i = 1:length(samples)
    #Threads.@threads for i = 1:length(samples)
        wrc = wrc_vec[Threads.threadid()]
        set_channel!(wrc, i)
        rand!(wrc, samples[i], dpcfg, maxdepth)
    end
end

#Sequential evaluation of fitnesses
function seq_evaluate(p::CEESParams, samples::Samples, result::CEESResult, problem::ExprProblem,
    default_expr)
    fitnesses = Array(Float64, p.num_samples)
    i = 1
    for s in samples
        try
            fitness = get_fitness(problem, s.derivtree, p.userargs)
            fitnesses[i] = fitness
            result.totalevals += 1
            if fitness < result.fitness
                result.fitness = fitness
                copy!(result.tree, s.derivtree)
                result.best_at_eval = result.totalevals
                result.expr = get_expr(s)
            end
        catch e
            if !isa(e, IncompleteException)
                rethrow(e)
            end
            fitnesses[i] = realmax(Float64)
        end
        i += 1
    end
    fitnesses
end

#threaded evaluation of fitnesses
function parallel_evaluate(p::CEESParams, samples::Samples, result::CEESResult,
    problem::ExprProblem, default_expr)
    fitnesses = fill(realmax(Float64), p.num_samples)
    #evaluate fitness in parallel
    for i = 1:p.num_samples #use this to disable threads
    #Threads.@threads for i = 1:p.num_samples
        try
            #get_fitness must be thread-safe!
            fitnesses[i] = get_fitness(problem, samples[i].derivtree, p.userargs)
        catch e
            if !isa(e, IncompleteException)
                println("Exception caught! ", e)
                rethrow(e)
            end
            fitnesses[i] = realmax(Float64)
        end
    end
    #update global result
    for i = 1:p.num_samples
        fitness = fitnesses[i]
        result.totalevals += 1
        if fitness < result.fitness
            s = samples[i]
            result.fitness = fitness
            copy!(result.tree, s.derivtree)
            result.best_at_eval = result.totalevals
            result.expr = get_expr(s)
        end
    end
    fitnesses
end

end #module

max_stars_repo_name: sisl/ExprSearch

max_issues_repo_name: sisl/ExprSearch


text:
const RHP_VARTYPE_X           = Cuint(0)   # continuous variable
const RHP_VARTYPE_B           = Cuint(1)   # binary variable
const RHP_VARTYPE_I           = Cuint(2)   # integer variable
const RHP_VARTYPE_S1          = Cuint(3)   # special order set 1 (SOS1)
const RHP_VARTYPE_S2          = Cuint(4)   # special order set 2 (SOS2)
const RHP_VARTYPE_SC          = Cuint(5)   # semi-continuous variable
const RHP_VARTYPE_SI          = Cuint(6)   # semi-integer variable
const RHP_VARTYPE_IND         = Cuint(7)   # indicator variable
const RHP_VARTYPE_POLYHEDRAL  = Cuint(8)   # variable in a polyhedral cone
const RHP_VARTYPE_SOC         = Cuint(9)   # variable in a SOC
const RHP_VARTYPE_RSOC        = Cuint(10)  # variable in a rotated SOC
const RHP_VARTYPE_EXP         = Cuint(11)  # variable in a EXP cone
const RHP_VARTYPE_DEXP        = Cuint(12)  # variable in a dual EXP
const RHP_VARTYPE_POWER       = Cuint(13)  # variable in a POWER cone
const RHP_VARTYPE_DPOWER      = Cuint(14)  # variable in a dual POWER cone

const RHP_CONE_R_PLUS       = Cuint(1)    # Non-negative real \f$\mathbb{R}_+\f$ */
const RHP_CONE_R_MINUS      = Cuint(2)    # Non-positive real \f$\mathbb{R}_-\f$  */
const RHP_CONE_R            = Cuint(3)    # Real \f$\mathbb{R}\f$ */
const RHP_CONE_0            = Cuint(4)    # Zero singleton */
const RHP_CONE_POLYHEDRAL   = Cuint(5)    # Zero singleton */
const RHP_CONE_SOC          = Cuint(6)    # Second Order cone */
const RHP_CONE_RSOC         = Cuint(7)    # Rotated Second Order cone */
const RHP_CONE_EXP          = Cuint(8)    # Exponential cone */
const RHP_CONE_DEXP         = Cuint(9)    # Dual Exponential cone */
const RHP_CONE_POWER        = Cuint(10)   # Power cone */
const RHP_CONE_DPOWER       = Cuint(11)   # Dual Power cone */

const RHP_Double   =  Cint(0)
const RHP_Integer  =  Cint(1)
const RHP_Boolean  =  Cint(2)
const RHP_String   =  Cint(3)

const RHP_BASIS_STATUS_LOWER      = Cint(0)
const RHP_BASIS_STATUS_UPPER      = Cint(1)
const RHP_BASIS_STATUS_BASIC      = Cint(2)
const RHP_BASIS_STATUS_SUPERBASIC = Cint(3)
const RHP_BASIS_STATUS_INVALID    = Cint(4)

const RHP_INDEX_NA      = -2
const RHP_INDEX_INVALID = -1

const solver_stat = [
   :Optimal,
   :IterationLimit,
   :TimeLimit,
   :SolverInterrupt,
   :EvalError,
   :Capability,
   :LicenseIssue,
   :UserInterrupt,
   :SetupError,
   :SolverError,
   :InternalError,
   :SolveSkipped,
   :SystemError
]

const model_stat = [
   :OptimalGlobal,
   :OptimalLocal,
   :Unbounded,
   :InfeasibleGlobal,
   :InfeasibleLocal,
   :InfeasibleIntermed,
   :Feasible,
   :Integer,
   :NonIntegerIntermed,
   :IntegerInfeasible,
   :LicenseError,
   :ErrorUnknown,
   :ErrorNoSolution,
   :NoSolutionReturned,
   :SolvedUnique,
   :Solved,
   :SolvedSingular,
   :UnboundedNoSolution,
   :InfeasibleNoSolution
]


text:
"""
    GreedyVector{T, TSubCon<:Construct{T}} <: Wrapper{T, Vector{T}}

Homogenous array of elements for unknown count of elements by parsing until end of stream.
"""
struct GreedyVector{T, TSubCon<:Construct{T}} <: Wrapper{T, Vector{T}}
    subcon::TSubCon
end

GreedyVector(type::Type) = GreedyVector(Construct(type))

subcon(wrapper::GreedyVector) = wrapper.subcon
function deserialize(array::GreedyVector{T, TSubCon}, s::IO; contextkw...) where {T, TSubCon}
    result = Vector{T}()
    fallback = 0
    try
        while !eof(s)
            fallback = position(s)
            push!(result, deserialize(array.subcon, s; contextkw...))
        end
    catch
        seek(s, fallback)
        # rethrow()
    end
    result
end
function serialize(array::GreedyVector{T, TSubCon}, s::IO, obj::Vector{T}; contextkw...) where {T, TSubCon}
    bytecount = 0
    for v in obj
        bytecount += serialize(array.subcon, s, v; contextkw...)
    end
    bytecount
end
estimatesize(::GreedyVector; contextkw...) = Interval(UInt(0), nothing)


text:
#=
  Who killed agatha? (The Dreadsbury Mansion Murder Mystery) in Julia + ConstraintSolver.jl.

  This is a standard benchmark for theorem proving.

  http://www.lsv.ens-cachan.fr/~goubault/H1.dist/H1.1/Doc/h1003.html
  """
  Someone in Dreadsbury Mansion killed Aunt Agatha.
  Agatha, the butler, and Charles live in Dreadsbury Mansion, and
  are the only ones to live there. A killer always hates, and is no
  richer than his victim. Charles hates noone that Agatha hates. Agatha
  hates everybody except the butler. The butler hates everyone not richer
  than Aunt Agatha. The butler hates everyone whom Agatha hates.
  Noone hates everyone. Who killed Agatha?
  """

  Originally from F. J. Pelletier:
  Seventy-five problems for testing automatic theorem provers.
  Journal of Automated Reasoning, 2: 191 216, 1986.
  http://www.sfu.ca/~jeffpell/papers/75ATPproblems86.pdf

  I have blogged about the problem here:
  * "Learning constraint programming - part II: Modeling with the Element constraint"
    http://www.hakank.org/constraint_programming_blog/2009/05/learning_constraint_programmin.html
  * "Learning Constraint Programming IV: Logical constraints: Who killed Agatha? revisited"
  http://www.hakank.org/constraint_programming_blog/2009/05/learning_constraint_programmin_3.html

  Model created by Hakan Kjellerstrand, hakank@gmail.com
  See also my Julia page: http://www.hakank.org/julia/

=#
using ConstraintSolver, JuMP
using Cbc, GLPK
const CS = ConstraintSolver
include("constraints_utils.jl")

function print_matrix(x)
    print_grid(x)
end

function who_killed_agatha()

    cbc_optimizer = optimizer_with_attributes(Cbc.Optimizer, "logLevel" => 0)
    glpk_optimizer = optimizer_with_attributes(GLPK.Optimizer)

    model = Model(optimizer_with_attributes(CS.Optimizer,   "all_solutions"=> true,
                                                            # "all_optimal_solutions"=>true,
                                                            "logging"=>[],

                                                            # "traverse_strategy"=>:BFS,
                                                            # "traverse_strategy"=>:DFS, # <-
                                                            # "traverse_strategy"=>:DBFS,

                                                            # "branch_split"=>:Smallest,
                                                            # "branch_split"=>:Biggest,
                                                            # "branch_split"=>:InHalf, # <-

                                                            # "simplify"=>false,
                                                            # "simplify"=>true, # default

                                                            "time_limit"=>16,

                                                            # "lp_optimizer" => cbc_optimizer, # 45.8s
                                                            # "lp_optimizer" => glpk_optimizer, # 21.5s
                                        ))

    n = 3
    agatha = 1
    butler = 2
    charles = 3
    @variable(model, 1 <= killer <= 3, Int)
    @variable(model, hates[1:n,1:n], Bin)
    @variable(model, richer[1:n,1:n], Bin)
    @variable(model, is_killer[1:3], Bin)

    # Connect killer to is_killer
    for i in 1:n
        @constraint(model, is_killer[i] := {killer == i})
    end
    @constraint(model, sum(is_killer) == 1)

    #
    # Constraints
    #
    # Agatha, the butler, and Charles live in Dreadsbury Mansion, and
    # are the only ones to live there.
    #

    # * A killer always hates, and is no richer than his victim.
    for i in 1:n
        @constraint(model, is_killer[i] => {hates[i, agatha] == 1})
        @constraint(model, is_killer[i] => {richer[i, agatha] == 0})
    end

    # * Define the concept of richer: no one is richer than him-/herself
    for i in 1:n
        @constraint(model,richer[i,i]== 0)
    end

    # (contd...) if i is richer than j then j is not richer than i
    for i in 1:n, j in 1:n
        if i != j
            @constraint(model, richer[i,j] => {richer[j,i] == 0})
            @constraint(model, !richer[j,i] => {richer[i,j] == 1})
        end
    end

    # * Charles hates no one that Agatha hates.
    for i in 1:n
        @constraint(model, hates[agatha, i] => {hates[charles, i] == 0})
    end

    # * Agatha hates everybody except the butler.
    @constraint(model,hates[agatha, butler] == 0)
    @constraint(model,hates[agatha, charles] == 1)
    @constraint(model,hates[agatha, agatha] == 1)

    # * The butler hates everyone not richer than Aunt Agatha.
    for i in 1:n
      @constraint(model, !richer[i, agatha] => {hates[butler, i] == 1})
    end

    # * The butler hates everyone whom Agatha hates.
    for i in 1:n
        @constraint(model, hates[agatha, i] => {hates[butler, i] == 1})
    end

    # * No one hates every one.
    for i in 1:n
        @constraint(model, sum([hates[i,j] for j in 1:n]) <= 2)
    end

    # * A killer always hates, and is no richer than his victim.
    for i in 1:n
       @constraint(model, is_killer[i] => {hates[i,agatha] == 1})
       @constraint(model, is_killer[i] => {richer[i,agatha] == 0})
    end

    # * Who killed Agatha?

    # Solve the problem
    println("solve")
    optimize!(model)

    status = JuMP.termination_status(model)
    println("status:$status")
    solutions = []
    if status == MOI.OPTIMAL
        num_sols = MOI.get(model, MOI.ResultCount())
        println("\nnum_sols:$num_sols\n")

        for sol in 1:num_sols
            # println("solution #$sol")
            xkiller = convert.(Integer,JuMP.value.(killer,result=sol))
            # println("killer: $xkiller\n")
            push!(solutions,xkiller)
        end
    end
    people = ["agatha","butler","charles"]
    println("solutions: $([people[sol] for sol in solutions])")
end

who_killed_agatha()

max_stars_repo_name: Wikunia/hakank

max_issues_repo_name: Wikunia/hakank

max_forks_repo_name: Wikunia/hakank


text:
module PkgPage

import Franklin
import CommonMark
import NodeJS

export newpage
export serve

export lx_lead, lx_figure, lx_table, lx_alert
export lx_begin, lx_end, lx_column

export hfun_col

const F = Franklin

include("instantiate.jl")

include("utils.jl")
include("coms/basic.jl")
include("coms/begin-end.jl")

end # module


text:
# Copyright 2018 Erik Edin
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

@testset "Gherkin Scenarios    " begin
    @testset "Scenario parser" begin
        @testset "Empty Scenario, no description; OK" begin
            # Arrange
            input = ParserInput("""
                Scenario:
            """)

            # Act
            parser = ScenarioParser()
            result = parser(input)

            # Assert
            @test result isa OKParseResult{Scenario}
            @test result.value.description == ""
            @test result.value.steps == []
        end

        @testset "Empty Scenario, some description; OK" begin
            # Arrange
            input = ParserInput("""
                Scenario: Some description
            """)

            # Act
            parser = ScenarioParser()
            result = parser(input)

            # Assert
            @test result isa OKParseResult{Scenario}
            @test result.value.description == "Some description"
            @test result.value.steps == []
        end

        @testset "Scenario Outline:, Not OK" begin
            # Arrange
            input = ParserInput("""
                Scenario Outline:
            """)

            # Act
            parser = ScenarioParser()
            result = parser(input)

            # Assert
            @test result isa BadParseResult{Scenario}
        end

        @testset "Two givens, Some new description; OK" begin
            # Arrange
            input = ParserInput("""
                Scenario: Some new description
                    Given some precondition
                    Given some other precondition
            """)

            # Act
            parser = ScenarioParser()
            result = parser(input)

            # Assert
            @test result isa OKParseResult{Scenario}
            @test result.value.description == "Some new description"
            @test result.value.steps == [Given("some precondition"), Given("some other precondition")]
        end

        @testset "Given/When/Then; OK" begin
            # Arrange
            input = ParserInput("""
                Scenario: Some new description
                    Given some precondition
                     When some action
                     Then some precondition
            """)

            # Act
            parser = ScenarioParser()
            result = parser(input)

            # Assert
            @test result isa OKParseResult{Scenario}
            @test result.value.description == "Some new description"
            @test result.value.steps == [Given("some precondition"), When("some action"), Then("some precondition")]
        end

        @testset "When/Then; OK" begin
            # Arrange
            input = ParserInput("""
                Scenario: Some new description
                     When some action
                     Then some precondition
            """)

            # Act
            parser = ScenarioParser()
            result = parser(input)

            # Assert
            @test result isa OKParseResult{Scenario}
            @test result.value.description == "Some new description"
            @test result.value.steps == [When("some action"), Then("some precondition")]
        end

        @testset "Then; OK" begin
            # Arrange
            input = ParserInput("""
                Scenario: Some new description
                     Then some precondition
            """)

            # Act
            parser = ScenarioParser()
            result = parser(input)

            # Assert
            @test result isa OKParseResult{Scenario}
            @test result.value.description == "Some new description"
            @test result.value.steps == [Then("some precondition")]
        end

        @testset "Two givens with a block text, Some new description; OK" begin
            # Arrange
            input = ParserInput("""
                Scenario: Some new description
                    Given some precondition
                        \"\"\"
                        Block text line.
                        \"\"\"
                    Given some other precondition
            """)

            # Act
            parser = ScenarioParser()
            result = parser(input)

            # Assert
            @test result isa OKParseResult{Scenario}
            @test result.value.description == "Some new description"
            @test result.value.steps == [
                Given("some precondition"; block_text="Block text line."),
                Given("some other precondition")]
        end

        @testset "A step has a data table; OK" begin
            # Arrange
            input = ParserInput("""
                Scenario: Some new description
                    Given some precondition
                        | Foo | Bar  |
                        | Baz | Quux |
            """)

            # Act
            parser = ScenarioParser()
            result = parser(input)

            # Assert
            @test result isa OKParseResult{Scenario}
            @test result.value.description == "Some new description"
            given = result.value.steps[1]
            @test given.text == "some precondition"
            @test given.datatable == [
                ["Foo", "Bar"],
                ["Baz", "Quux"]
            ]
        end

        @testset "A step has a data table and a block text; OK" begin
            # Arrange
            input = ParserInput("""
                Scenario: Some new description
                    Given some precondition
                        | Foo | Bar  |
                        | Baz | Quux |
                        \"\"\"
                        Some block text
                        \"\"\"
            """)

            # Act
            parser = ScenarioParser()
            result = parser(input)

            # Assert
            @test result isa OKParseResult{Scenario}
            @test result.value.description == "Some new description"
            given = result.value.steps[1]
            @test given.text == "some precondition"
            @test given.datatable == [
                ["Foo", "Bar"],
                ["Baz", "Quux"]
            ]
            @test given.block_text == "Some block text"
        end

        @testset "A step has block text and data table; OK" begin
            # Arrange
            input = ParserInput("""
                Scenario: Some new description
                    Given some precondition
                        \"\"\"
                        Some block text
                        \"\"\"
                        | Foo | Bar  |
                        | Baz | Quux |
            """)

            # Act
            parser = ScenarioParser()
            result = parser(input)

            # Assert
            @test result isa OKParseResult{Scenario}
            @test result.value.description == "Some new description"
            given = result.value.steps[1]
            @test given.text == "some precondition"
            @test given.datatable == [
                ["Foo", "Bar"],
                ["Baz", "Quux"]
            ]
            @test given.block_text == "Some block text"
        end
    end

    @testset "RuleParser" begin
        @testset "Empty Rule, no description; OK" begin
            # Arrange
            input = ParserInput("""
                Rule:
            """)

            # Act
            parser = RuleParser()
            result = parser(input)

            # Assert
            @test result isa OKParseResult{Rule}
            @test result.value.description == ""
            @test result.value.scenarios == []
        end

        @testset "Empty Rule, Some rule description; OK" begin
            # Arrange
            input = ParserInput("""
                Rule: Some rule description
            """)

            # Act
            parser = RuleParser()
            result = parser(input)

            # Assert
            @test result isa OKParseResult{Rule}
            @test result.value.description == "Some rule description"
            @test result.value.scenarios == []
        end

        @testset "Rule with one scenario; OK" begin
            # Arrange
            input = ParserInput("""
                Rule: Some rule description
                    Scenario: Some scenario
            """)

            # Act
            parser = RuleParser()
            result = parser(input)

            # Assert
            @test result isa OKParseResult{Rule}
            @test result.value.description == "Some rule description"
            @test result.value.scenarios[1].description == "Some scenario"
        end

        @testset "Rule with two scenarios; OK" begin
            # Arrange
            input = ParserInput("""
                Rule: Some rule description
                    Scenario: Some scenario
                    Scenario: Some other scenario
            """)

            # Act
            parser = RuleParser()
            result = parser(input)

            # Assert
            @test result isa OKParseResult{Rule}
            @test result.value.description == "Some rule description"
            @test result.value.scenarios[1].description == "Some scenario"
            @test result.value.scenarios[2].description == "Some other scenario"
        end

        @testset "Rule with two scenarios any steps; OK" begin
            # Arrange
            input = ParserInput("""
                Rule: Some rule description
                    Scenario: Some scenario
                        Given some precondition
                        Given some other precondition
                    Scenario: Some other scenario
                        Given some third precondition
            """)

            # Act
            parser = RuleParser()
            result = parser(input)

            # Assert
            @test result isa OKParseResult{Rule}
            @test result.value.description == "Some rule description"
            @test result.value.scenarios[1].description == "Some scenario"
            @test result.value.scenarios[1].steps == [
                Given("some precondition"), Given("some other precondition")
            ]
            @test result.value.scenarios[2].description == "Some other scenario"
            @test result.value.scenarios[2].steps == [
                Given("some third precondition")
            ]
        end

        @testset "Rule with two scenarios any steps separated by blank lines; OK" begin
            # Arrange
            input = ParserInput("""
                Rule: Some rule description

                    Scenario: Some scenario
                        Given some precondition
                        Given some other precondition

                    Scenario: Some other scenario
                        Given some third precondition
            """)

            # Act
            parser = RuleParser()
            result = parser(input)

            # Assert
            @test result isa OKParseResult{Rule}
            @test result.value.description == "Some rule description"
            @test result.value.scenarios[1].description == "Some scenario"
            @test result.value.scenarios[1].steps == [
                Given("some precondition"), Given("some other precondition")
            ]
            @test result.value.scenarios[2].description == "Some other scenario"
            @test result.value.scenarios[2].steps == [
                Given("some third precondition")
            ]
        end
    end

    @testset "Scenario Outlines" begin
        @testset "Scenario Outline one step, no description; OK" begin
            # Arrange
            input = ParserInput("""
                Scenario Outline:
                    Given some value <Foo>

                    Examples:
                        | Foo |
                        | bar |
            """)

            # Act
            parser = ScenarioOutlineParser()
            result = parser(input)

            # Assert
            @test result isa OKParseResult{ScenarioOutline}
            @test result.value.description == ""
            @test result.value.tags == []
            @test result.value.steps == [Given("some value <Foo>")]
            @test result.value.placeholders == ["Foo"]
            @test result.value.examples == [["bar"]]
        end

        @testset "Scenario Outline, then EOF; OK" begin
            # Arrange
            input = ParserInput("""
                Scenario Outline:
                    Given some value <Foo>

                    Examples:
                        | Foo |
                        | bar |
            """)

            # Act
            parser = Sequence{Union{ScenarioOutline, Nothing}}(
                        ScenarioOutlineParser(),
                        EOFParser())
            result = parser(input)

            # Assert
            @test result isa OKParseResult{Vector{Union{ScenarioOutline, Nothing}}}
            @test result.value[1].description == ""
            @test result.value[1].steps == [Given("some value <Foo>")]
            @test result.value[1].placeholders == ["Foo"]
            @test result.value[1].examples == [["bar"]]
            @test result.value[2] === nothing
        end

        @testset "Scenario Outline one step, and a description; OK" begin
            # Arrange
            input = ParserInput("""
                Scenario Outline: Some scenario outline
                    Given some value <Foo>

                    Examples:
                        | Foo |
                        | bar |
            """)

            # Act
            parser = ScenarioOutlineParser()
            result = parser(input)

            # Assert
            @test result isa OKParseResult{ScenarioOutline}
            @test result.value.description == "Some scenario outline"
        end

        @testset "Scenario Outline with tags; OK" begin
            # Arrange
            input = ParserInput("""
                @tag1 @tag2
                Scenario Outline: Some scenario outline
                    Given some value <Foo>

                    Examples:
                        | Foo |
                        | bar |
            """)

            # Act
            parser = ScenarioOutlineParser()
            result = parser(input)

            # Assert
            @test result isa OKParseResult{ScenarioOutline}
            @test result.value.tags == ["@tag1", "@tag2"]
        end

        @testset "Scenario Outline with Given/When/Then; OK" begin
            # Arrange
            input = ParserInput("""
                @tag1 @tag2
                Scenario Outline: Some scenario outline
                    Given some value <Foo>
                     When some action
                     Then some postcondition

                    Examples:
                        | Foo |
                        | bar |
            """)

            # Act
            parser = ScenarioOutlineParser()
            result = parser(input)

            # Assert
            @test result isa OKParseResult{ScenarioOutline}
            @test result.value.steps == [
                Given("some value <Foo>"),
                 When("some action"),
                 Then("some postcondition")
            ]
        end

        @testset "Scenario Outline a longer description; OK" begin
            # Arrange
            input = ParserInput("""
                @tag1 @tag2
                Scenario Outline: Some scenario outline

                    This is a long description.
                    On two lines.

                    Given some value <Foo>
                     When some action
                     Then some postcondition

                    Examples:
                        | Foo |
                        | bar |
            """)

            # Act
            parser = ScenarioOutlineParser()
            result = parser(input)

            # Assert
            @test result isa OKParseResult{ScenarioOutline}
            @test result.value.long_description == "This is a long description.\nOn two lines."
        end

        @testset "Scenario Outline with two placeholders; OK" begin
            # Arrange
            input = ParserInput("""
                @tag1 @tag2
                Scenario Outline: Some scenario outline

                    Given some value <Foo>
                     When some action
                     Then some postcondition

                    Examples:
                        | Foo | Bar  |
                        | baz | quux |
            """)

            # Act
            parser = ScenarioOutlineParser()
            result = parser(input)

            # Assert
            @test result isa OKParseResult{ScenarioOutline}
            @test result.value.placeholders == ["Foo", "Bar"]
        end

        @testset "Scenario Outline with two columns of examples; OK" begin
            # Arrange
            input = ParserInput("""
                @tag1 @tag2
                Scenario Outline: Some scenario outline

                    Given some value <Foo>
                     When some action
                     Then some postcondition

                    Examples:
                        | Foo | Bar  |
                        | baz | quux |
            """)

            # Act
            parser = ScenarioOutlineParser()
            result = parser(input)

            # Assert
            @test result isa OKParseResult{ScenarioOutline}
            @test result.value.examples[1] == ["baz", "quux"]
        end

        @testset "Scenario Outline with two rows of examples; OK" begin
            # Arrange
            input = ParserInput("""
                @tag1 @tag2
                Scenario Outline: Some scenario outline

                    Given some value <Foo>
                     When some action
                     Then some postcondition

                    Examples:
                        | Foo   | Bar     |
                        | baz   | quux    |
                        | fnord | quuxbaz |
            """)

            # Act
            parser = ScenarioOutlineParser()
            result = parser(input)

            # Assert
            @test result isa OKParseResult{ScenarioOutline}
            @test result.value.examples[1] == ["baz", "quux"]
            @test result.value.examples[2] == ["fnord", "quuxbaz"]
        end
    end

    @testset "And/But*" begin
        @testset "Scenario has an And; OK" begin
            # Arrange
            input = ParserInput("""
                Scenario: Some new description
                    Given some precondition
                      And some other precondition
            """)

            # Act
            parser = ScenarioParser()
            result = parser(input)

            # Assert
            @test result isa OKParseResult{Scenario}
            @test result.value.description == "Some new description"
            @test result.value.steps == [Given("some precondition"), And("some other precondition")]
        end
    end
end


text:
function set_global_volume(volume::Real)
    ccall((:sfListener_setGlobalVolume, libcsfml_audio), Void, (Cfloat,), volume)
end

function get_global_volume()
    ccall((:sfListener_getGlobalVolume, libcsfml_audio), Cfloat, ())
end

function set_listener_position(pos::Vector3f)
    ccall((:sfListener_setPosition, libcsfml_audio), Void, (Vector3f,), pos)
end

function get_listener_position()
    ccall((:sfListener_getPosition, libcsfml_audio), Vector3f, ())
end

function set_listener_direction(direction::Vector3f)
    ccall((:sfListener_setDirection, libcsfml_audio), Void, (Vector3f,), direction)
end

function get_listener_direction(direction::Vector3f)
    ccall((:sfListener_getDirection, libcsfml_audio), Vector3f, ())
end

function set_listener_upvector(vect::Vector3f)
    ccall((:sfListener_setUpVector, libcsfml_audio), Void, (Vector3f,), vect)
end

function get_listener_upvector()
    ccall((:sfListener_getUpVector, libcsfml_audio), Vector3f, ())
end


text:
#=
  Utils for Julia

  Here are utils for my Julia programming.

  This Julia program was created by Hakan Kjellerstrand, hakank@gmail.com
  See also my Julia page: http://www.hakank.org/julia/

=#

using Printf

# TODO:
# Add the relevant stuff from euler/Euler.jl

#
# Return a Dict of the elements and their occurences
# in the collection a.
#
function make_hash(a)
    d = Dict()
    for e in collect(a)
        # get!(d,e,0)
        if !haskey(d,e)
            d[e] = 0
        end
        d[e] += 1
    end
    return d
end

#
# All k combinations of elements in x without replacements
# (or 1..n if x in an integer).
# cf odometer / combinations_with_replacement
function combinations(k,x::Int)
    return combinations(k,1:x)
end

function combinations(k,x)
    if k===0
        return [[]]
    elseif x === [] || length(x) === 0
        return []
    else
        y, ys... = x
        t = map(c->append!([y],c),combinations(k-1,ys))
        return append!(t,combinations(k,ys))
    end
    return nothing
end

# julia> [length(all_combinations(1:n)) for n in 1:10]'
# 1×10 adjoint(::Vector{Int64}) with eltype Int64:
# 1  3  7  15  31  63  127  255  511  1023
# i.e. 2^length(x)-1
function all_combinations(x)
    cs = []
    for k in 1:length(x)
        push!(cs,combinations(k,x)...)
    end
    return cs
end

#=
  This is the odometer function: i.e.
  possible ordered combinations of x with replacements.
  If x in an integer, it will be interpreted as the range 0..n-1.

  Cf combinations(k,x)
=#
function odometer(k,x::Int)
    odometer(k, 1:x)
end

function odometer(k,x)
    if k===0
        return [[]]
    elseif x === [] || length(x) === 0
        return []
    else
        first, rest... = x
        t = map(c->append!([first],c), odometer(k-1,x))
        return append!(t, odometer(k,rest))
    end
    return nothing
end

function combinations_with_replacement(k,x)
    odometer(k,x)
end

# next permutation of array p
function next_permutation(p)
    perm = p
    n = length(perm)
    k = n - 1
    while perm[k] > perm[k+1] && k >= 0
        k = k - 1
    end
    if k > 0
        j = n
        while perm[k] > perm[j]
            j = j - 1
        end
        perm[k],perm[j] = perm[j], perm[k]
        r = n
        s = k + 1
        while r > s
            perm[r],perm[s] = perm[s],perm[r]
            r = r - 1
            s = s + 1
        end
    end
    return perm
end

max_stars_repo_name: tias/hakank

max_issues_repo_name: tias/hakank

max_forks_repo_name: tias/hakank


text:
# Note that this script can accept some limited command-line arguments, run
# `julia build_tarballs.jl --help` to see a usage message.
using BinaryBuilder, Pkg

name = "libavtp"
version = v"0.1.0"

# Collection of sources required to complete build
sources = [
    ArchiveSource("https://github.com/Avnu/libavtp/archive/refs/tags/v$(version).tar.gz", "9c1587431281a8d2404060e4bfd39f5cf0f211be6251e6afb1100e6148c1e591")
]

# Bash recipe for building across all platforms
script = raw"""
cd $WORKSPACE/srcdir/libavtp-*
mkdir build
cd build
meson --cross-file=${MESON_TARGET_TOOLCHAIN}
ninja -j${nproc}
ninja install
"""

# These are the platforms we will build for by default, unless further
# platforms are passed in on the command line
platforms = filter!(platform -> Sys.islinux(platform) && libc(platform) == "glibc", supported_platforms())

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

# Dependencies that must be installed before this package can be built
dependencies = [
    BuildDependency(PackageSpec(name="cmocka_jll", uuid="f83fd561-6387-5ecc-9835-b38c8eaffb11"))
]

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

max_stars_repo_name: sharanry/Yggdrasil

max_issues_repo_name: sharanry/Yggdrasil

max_forks_repo_name: sharanry/Yggdrasil


text:
R=8.31451;p=101325;T=293.15

molemass=[
    16.0430,30.0700,44.0970,58.1230,58.1230,72.1500,72.1500,72.1500,
    86.1770,86.1770,86.1770,86.1770,86.1770,100.204,114.231,128.258,
    142.285,28.0540,42.0810,56.1080,56.0180,56.1080,56.1080,70.1340,
    40.0650,54.0920,54.0920,26.0380,70.1340,84.1610,98.1880,84.1610,
    98.1880,112.215,78.1140,92.1410,106.167,106.167,32.0420,48.1090,
    2.01590,18.0153,34.0820,17.0306,27.0260,28.0100,60.0760,76.1430,
    4.00260,20.1797,39.9480,28.0135,31.9988,44.0100,64.0650,44.0129,
    83.8000,131.290]
mol_heat_high=[
    891.090,1561.41,2220.13,2878.57,2869.38,3537.17,3530.24,3516.01,
    4196.58,4188.95,4191.54,4179.15,4186.93,4855.29,5513.88,6173.46,
    6832.31,1411.65,2058.72,2717.75,2711.00,2707.40,2701.10,3376.57,
    1943.53,2594.45,2541.43,1301.21,3320.88,3970.93,4630.19,3954.47,
    4602.35,5264.98,3302.15,3948.84,4608.32,4597.46,764.590,1239.83,
    285.990,44.2240,562.190,383.160,671.600,282.950,548.190,1104.41]
mol_heat_low=[
    802.650,1428.74,2043.23,2657.45,2648.26,3271.83,3264.89,3250.67,
    3887.01,3879.38,3881.97,3869.59,3877.36,4501.49,5115.87,5731.22,
    6345.85,1323.20,1926.05,2540.86,2534.10,2530.50,2524.20,3155.45,
    1855.08,2461.78,2408.76,1256.98,3099.76,3705.59,4320.63,3689.13,
    4292.78,4911.19,3169.48,3771.95,4387.20,4376.34,676.140,1151.39,
    241.760,0.00000,517.970,316.820,649.500,282.950,548.190,1104.41]
z=[
    0.9981,0.9920,0.9834,0.9682,0.9710,0.9450,0.953,0.959,
    0.9190,0.9260,0.9280,0.9350,0.9340,0.8760,0.817,0.735,
    0.6230,0.9940,0.9850,0.9720,0.9690,0.9690,0.972,0.952,
    0.9840,0.9650,0.9730,0.9930,0.9500,0.9270,0.885,0.924,
    0.8940,0.8380,0.9360,0.8920,0.8370,0.8210,0.892,0.978,
    1.0006,0.9520,0.9900,0.9890,0.9200,0.9996,0.988,0.965,
    1.0005,1.0005,0.9993,0.9997,0.9993,0.9944,0.980]
b=[0.0436,0.0894,0.1288,0.1783,0.1703,0.2345,0.2168,0.2025,
0.2846,0.2720,0.2683,0.2550,0.2569,0.3521,0.4278,0.5148,
0.6140,0.0775,0.1225,0.1673,0.1761,0.1761,0.1673,0.2191,
0.1265,0.1871,0.1643,0.0837,0.2236,0.2702,0.3391,0.2757,
0.3256,0.4025,0.2530,0.3286,0.4037,0.4231,0.3286,0.1483,
-0.0051,0.2191,0.1000,0.1049,0.2828,0.0200,0.1095,0.1871,
0.0000,0.0000,0.0265,0.0173,0.0265,0.0728,0.1414]
N=48;N1=55
hhv_mole(x)=sum(mol_heat_high[1:N].*x[1:N])
lhv_mole(x)=sum(mol_heat_low[1:N].*x[1:N])
mole_mass(x)=sum(molemass.*x)
hhv_mass(x)=hhv_mole(x)/mole_mass(x)
lhv_mass(x)=lhv_mole(x)/mole_mass(x)
vol2mol(x)=x[1:N1]./z/sum(x[1:N1]./z)
zmix(x)=1.0-sum(x[1:N1].*b)
lhv_vol(x)=lhv_mole(x)*p/R/T
hhv_vol(x)=hhv_mole(x)*p/R/T
lhv_real_vol(x)=lhv_vol(x)/zmix(x)
hhv_real_vol(x)=hhv_vol(x)/zmix(x)
rel_ρ(x)=sum(x*mole_mass(x)/28.9625)
abs_ρ(x)=sum(x*mole_mass(x))*p/R/T
real_rel_ρ(x)=rel_ρ(x)*0.99963/zmix(x)
real_abs_ρ(x)=abs_ρ(x)/zmix(x)

function calorific(x,out)
    if out==:mol
        return (lhv_mole(x),hhv_mole(x))
    elseif out==:mass
        return (lhv_mass(x),hhv_mass(x))
    elseif out==:vol
        return (lhv_real_vol(x),hhv_real_vol(x))
    elseif out==:rho
        return (real_rel_ρ(x),real_abs_ρ(x))
    end
end

"""
    ng_calorific(mode=:mol,outoption=:mol;CH4=100.0,C2H6=0,C3H8=0,C4H10=0,C4H10_1=0,C5H12=0,C5H12_1=0.,C5H12_2=0,C6H14=0,
    C6H14_1=0.0,C6H14_2=0.0,C6H14_3=0,C6H14_4=0,C7H16=0,C8H18=0.0,C9H20=0.0,C10H22=0.0,C2H4=0.0,
    C3H6=0.0,C4H8=0.0,C4H8_1=0.0,C4H8_2=0.0,C4H8_3=0.0,C5H10=0.0,C3H4=0.0,C4H6=0.0,C4H6_1=0.0,C2H2=0.0,
    C5H10_1=0.0,C6H12=0.0,C7H12=0.0,C6H12_1=0.0,C7H14=0.0,C8H16=0.0,C6H6=0.0,C7H8=0.0,C8H10=0.0,C8H10_1=0.0,
    CH4O=0.0,C2H6HgS2=0.0,H2=0.0,H2O=0.0,H2S=0.0,NH3=0.0,CHN=0.0,CO2=0.0,COS=0.0,CS2=0.0,He=0.0,Ne=0.0,Ar=0.0,
    N2=0.0,O2=0.0,CO2=0.0,O2S=0.0,N2O=0.0,Kr=0.0,Xe=0.0)
# Augument
- `mode`: `:mol` mol heat;`:mass` mass heat;`:vol heat` volume heat
- `outoption` : `:mol` (mole_low_heat,mole_high_heat) kJ/mo1;`:mass` (mass_low_heat,mass_high_heat) MJ/kg;`:vol`(vol_low_heat,vol_high_heat) u"MJ/m3";
                `:rho` (real rel_density,real abs_density u"kg/m3")
"""
function ng_calorific(mode=:mol,outoption=:mol;CH4=1.0,C2H6=0,C3H8=0,nC4H10=0,iC4H10=0,nC5H12=0,iC5H12=0.,
    C5H12_2=0,nC6H14=0,iC6H14=0.0,C6H14_2=0.0,C6H14_3=0,C6H14_4=0,nC7H16=0,nC8H18=0.0,nC9H20=0.0,nC10H22=0.0,
    C2H4=0.0,C3H6=0.0,C4H8=0.0,C4H8_1=0.0,C4H8_2=0.0,C4H8_3=0.0,C5H10=0.0,C3H4=0.0,C4H6=0.0,C4H6_1=0.0,C2H2=0.0,
    C5H10_1=0.0,C6H12=0.0,C7H12=0.0,C6H12_1=0.0,C7H14=0.0,C8H16=0.0,C6H6=0.0,C7H8=0.0,C8H10=0.0,C8H10_1=0.0,
    CH4O=0.0,C2H6HgS2=0.0,H2=0.0,H2O=0.0,H2S=0.0,NH3=0.0,CHN=0.0,CO=0.0,COS=0.0,CS2=0.0,He=0.0,Ne=0.0,Ar=0.0,
    N2=0.0,O2=0.0,CO2=0.0,O2S=0.0,N2O=0.0,Kr=0.0,Xe=0.0)
    x=[CH4,C2H6,C3H8,nC4H10,iC4H10,nC5H12,iC5H12,C5H12_2,nC6H14,
    iC6H14,C6H14_2,C6H14_3,C6H14_4,nC7H16,nC8H18,nC9H20,nC10H22,C2H4,
    C3H6,C4H8,C4H8_1,C4H8_2,C4H8_3,C5H10,C3H4,C4H6,C4H6_1,C2H2,
    C5H10_1,C6H12,C7H12,C6H12_1,C7H14,C8H16,C6H6,C7H8,C8H10,C8H10_1,
    CH4O,C2H6HgS2,H2,H2O,H2S,NH3,CHN,CO,COS,CS2,He,Ne,Ar,
    N2,O2,CO2,O2S,N2O,Kr,Xe]
    if mode==:vol;x=vol2mol(x);end
    calorific(x,outoption)

end

"""
    ng_calorific_cn(mode=:mol,outoption=:mol;甲烷=100,乙烷=0,丙烷=0,丁烷=0,二甲基丙烷=0,戊烷=0,二甲基丁烷=0,
    二二甲基丙烷=0,已烷=0,二甲基戊烷=0,三甲基戊烷=0,二二甲基丁烷=0,二三甲基丁烷=0,庚烷=0,辛烷=0,
    壬烷=0,癸烷=0,乙烯=0,丙烯=0,一丁烯=0,顺二丁烯=0,反二丁烯=0,二甲基丙烯=0,一戊烯=0,丙二烯=0,一二丁二烯=0,
    一三丁二烯=0,乙炔=0,环戊烷=0,甲基环戊烷=0,乙基环戊烷=0,环己烷=0,甲基环己烷=0,乙基环己烷=0,苯=0,
    甲苯=0,乙苯=0,邻二甲苯=0,甲醇=0,甲硫醇=0,氢气=0,水=0,硫化氢=0,氨=0,氰化氢=0,一氧化碳=0,硫氧碳=0,
    二硫化碳=0,氦气=0,氖气=0,氩气=0,氮气=0,氧气=0,二氧化碳=0,二氧化硫=0,一氧化二氮=0,氪气=0,氙气=0)
# Augument
- `mode`: `:mol` mol heat;`:mass` mass heat;`:vol heat` volume heat
- `outoption` : `:mol` (mole_low_heat,mole_high_heat) kJ/mo1;`:mass` (mass_low_heat,mass_high_heat) MJ/kg;`:vol`(vol_low_heat,vol_high_heat) u"MJ/m3";
                `:rho` (real rel_density,real abs_density u"kg/m3")
"""
function ng_calorific_cn(mode=:mol,outoption=:mol;甲烷=1,乙烷=0,丙烷=0,丁烷=0,二甲基丙烷=0,戊烷=0,二甲基丁烷=0,
    二二甲基丙烷=0,已烷=0,二甲基戊烷=0,三甲基戊烷=0,二二甲基丁烷=0,二三甲基丁烷=0,庚烷=0,辛烷=0,
    壬烷=0,癸烷=0,乙烯=0,丙烯=0,一丁烯=0,顺二丁烯=0,反二丁烯=0,二甲基丙烯=0,一戊烯=0,丙二烯=0,一二丁二烯=0,
    一三丁二烯=0,乙炔=0,环戊烷=0,甲基环戊烷=0,乙基环戊烷=0,环己烷=0,甲基环己烷=0,乙基环己烷=0,苯=0,
    甲苯=0,乙苯=0,邻二甲苯=0,甲醇=0,甲硫醇=0,氢气=0,水=0,硫化氢=0,氨=0,氰化氢=0,一氧化碳=0,硫氧碳=0,
    二硫化碳=0,氦气=0,氖气=0,氩气=0,氮气=0,氧气=0,二氧化碳=0,二氧化硫=0,一氧化二氮=0,氪气=0,氙气=0)

    x=[甲烷,乙烷,丙烷,丁烷,二甲基丙烷,戊烷,二甲基丁烷,
    二二甲基丙烷,已烷,二甲基戊烷,三甲基戊烷,二二甲基丁烷,二三甲基丁烷,庚烷,辛烷,
    壬烷,癸烷,乙烯,丙烯,一丁烯,顺二丁烯,反二丁烯,二甲基丙烯,一戊烯,丙二烯,一二丁二烯,
    一三丁二烯,乙炔,环戊烷,甲基环戊烷,乙基环戊烷,环己烷,甲基环己烷,乙基环己烷,苯,
    甲苯,乙苯,邻二甲苯,甲醇,甲硫醇,氢气,水,硫化氢,氨,氰化氢,一氧化碳,硫氧碳,
    二硫化碳,氦气,氖气,氩气,氮气,氧气,二氧化碳,二氧化硫,一氧化二氮,氪气,氙气]
    if mode==:vol;x=vol2mol(x);end
    calorific(x,outoption)
end

"""
    ng_calorific_en(mode=:mol,outoption=:mol;Methane=100.0,Ethane=0.0,Propane=0.0,nButane=0.0,Alkanes=0.0,nPentane=0.0,
    Methylbutane_2=0.0,Dimethylpropane_2_2=0.0,nHexane=0.0,Methylpentane_2=0.0,Methoylpentane_3=0.0,
    Dimethylbutane_2_2=0.0,Dimethylbutane_2_3=0.0,nHeptane=0.0,nOctane=0.0,nNonane=0.0,nDecane=0.0,
    Ethylene=0.0,Propylene=0.0,    Butene_1=0.0,cis_2_Butene=0.0,trans_2_Butene=0.0,Methylpropene_2=0.0,
    Pentene_1=0.0,    Propadiene=0.0,Butadiene_1_2=0.0,Butadiene_1_3=0.0,Acetylene=0.0,Cyclopentane=0.0,
    Methylcyclopentane=0.0,Ethylcyclopentane=0.0,Cyclohexane=0.0,Methylcyclohexane=0.0,Ethylcyclohexane=0.0,
    Benzene=0.0,Toluene=0.0,Ethylbenzene=0.0,o_Xylene=0.0,Methanol=0.0,Methanethiol=0.0,Hydrogen=0.0,
    Water=0.0,Hydrogen_sulfide=0.0,Ammonia=0.0,Hydrogen_cyanide=0.0,Carbon_monoxide=0.0,Carbonyl_sulfide=0.0,
    Carbon_disulfide=0.0,Helium=0.0,Neon=0.0,Argon=0.0,Nitrogen=0.0,Oxygen=0.0,Carbon_dioxide=0.0,Sulfur_Dioxide=0.0,
    Dinitrogen_monoxide=0.0,Krypton=0.0,Xenon=0.0)
# Augument
- `mode`: `:mol` mol heat;`:mass` mass heat;`:vol heat` volume heat
- `outoption` : `:mol` (mole_low_heat,mole_high_heat) kJ/mo1;`:mass` (mass_low_heat,mass_high_heat) MJ/kg;`:vol`(vol_low_heat,vol_high_heat) u"MJ/m3";
                `:rho` (real rel_density,real abs_density u"kg/m3")
"""
function ng_calorific_en(mode=:mol,outoption=:mol;Methane=1.0,Ethane=0.0,Propane=0.0,nButane=0.0,Alkanes=0.0,nPentane=0.0,
    Methylbutane_2=0.0,Dimethylpropane_2_2=0.0,nHexane=0.0,Methylpentane_2=0.0,Methoylpentane_3=0.0,
    Dimethylbutane_2_2=0.0,Dimethylbutane_2_3=0.0,nHeptane=0.0,nOctane=0.0,nNonane=0.0,nDecane=0.0,
    Ethylene=0.0,Propylene=0.0,    Butene_1=0.0,cis_2_Butene=0.0,trans_2_Butene=0.0,Methylpropene_2=0.0,
    Pentene_1=0.0,    Propadiene=0.0,Butadiene_1_2=0.0,Butadiene_1_3=0.0,Acetylene=0.0,Cyclopentane=0.0,
    Methylcyclopentane=0.0,Ethylcyclopentane=0.0,Cyclohexane=0.0,Methylcyclohexane=0.0,Ethylcyclohexane=0.0,
    Benzene=0.0,Toluene=0.0,Ethylbenzene=0.0,o_Xylene=0.0,Methanol=0.0,Methanethiol=0.0,Hydrogen=0.0,
    Water=0.0,Hydrogen_sulfide=0.0,Ammonia=0.0,Hydrogen_cyanide=0.0,Carbon_monoxide=0.0,Carbonyl_sulfide=0.0,
    Carbon_disulfide=0.0,Helium=0.0,Neon=0.0,Argon=0.0,Nitrogen=0.0,Oxygen=0.0,Carbon_dioxide=0.0,Sulfur_Dioxide=0.0,
    Dinitrogen_monoxide=0.0,Krypton=0.0,Xenon=0.0)

    x=[Methane,Ethane,Propane,nButane,Alkanes,nPentane,Methylbutane_2,Dimethylpropane_2_2,nHexane,Methylpentane_2,Methoylpentane_3,
    Dimethylbutane_2_2,Dimethylbutane_2_3,nHeptane,nOctane,nNonane,nDecane,Ethylene,Propylene,Butene_1,cis_2_Butene,trans_2_Butene,
    Methylpropene_2,Pentene_1,Propadiene,Butadiene_1_2,Butadiene_1_3,Acetylene,Cyclopentane,Methylcyclopentane,Ethylcyclopentane,
    Cyclohexane,Methylcyclohexane,Ethylcyclohexane,Benzene,Toluene,Ethylbenzene,o_Xylene,Methanol,Methanethiol,Hydrogen,Water,
    Hydrogen_sulfide,Ammonia,Hydrogen_cyanide,Carbon_monoxide,Carbonyl_sulfide,Carbon_disulfide,Helium,Neon,Argon,Nitrogen,Oxygen,
    Carbon_dioxide,Sulfur_Dioxide,Dinitrogen_monoxide,Krypton,Xenon]
    if mode==:vol;x=vol2mol(x);end
    calorific(x,outoption)
end

export ng_calorific,ng_calorific_cn,ng_calorific_en

max_stars_repo_name: hzgzh/NG

max_issues_repo_name: hzgzh/NG

max_forks_repo_name: hzgzh/NG


text:
H = Hilbert(10)
@test Matrix(H)[10,10] == 1//(10+10-1)


text:
module VizCLIMA

greet() = "Hello World!"

end # module


text:
# Autogenerated wrapper script for Libiconv_jll for x86_64-w64-mingw32
export libcharset, libiconv

JLLWrappers.@generate_wrapper_header("Libiconv")
JLLWrappers.@declare_library_product(libcharset, "libcharset-1.dll")
JLLWrappers.@declare_library_product(libiconv, "libiconv-2.dll")
function __init__()
    JLLWrappers.@generate_init_header()
    JLLWrappers.@init_library_product(
        libcharset,
        "bin\\libcharset-1.dll",
        RTLD_LAZY | RTLD_DEEPBIND,
    )

    JLLWrappers.@init_library_product(
        libiconv,
        "bin\\libiconv-2.dll",
        RTLD_LAZY | RTLD_DEEPBIND,
    )

    JLLWrappers.@generate_init_footer()
end  # __init__()


text:
using BenchmarkTools
import SearchBall
sb = SearchBall

pos = sb.Posture([0.0, 0.0], 0.0)
pos[1]

p = rand(2)
a = rand()
@benchmark pos = sb.Posture(p, a)

@benchmark pos = sb.Posture(rand(2), rand())

@benchmark pos[Int(round(rand())) + 1]

function getVal(i::Int, pos::sb.Posture)
    pos[i]
end

getVal(1, pos)

@benchmark getVal(2, pos)


text:
function gen_sys(ebn0db::Ranges{Float64}, sprlen::Ranges{Int}; system::Symbol=:UTURUniChannelCSK, args...)
  if system == :UTURUniChannelCSK
    uturunichannelcsk_gen_sys(ebn0db, sprlen; args...)
  else
    error("sim_ber was called with invalid arguments.")
  end
end

gen_sys(ebn0db::Float64, sprlen::Ranges{Int}; system::Symbol=:UTURUniChannelCSK, args...) =
  gen_sys(ebn0db:ebn0db, sprlen; system=system, args...)

gen_sys(ebn0db::Ranges{Float64}, sprlen::Int; system::Symbol=:UTURUniChannelCSK, args...) =
  gen_sys(ebn0db, sprlen:sprlen; system=system, args...)

gen_sys(ebn0db::Float64, sprlen::Int; system::Symbol=:UTURUniChannelCSK, args...) =
  gen_sys(ebn0db:ebn0db, sprlen:sprlen; system=system, args...)

function sim_ber(s::DigitalSystem, bit::Int, n::Int64)
  nbiterrors::Int64 = 0
  ndecfails::Int64 = 0

  for i = 1:n
    bit_estimate = sim_sys(s, bit)
    if in(bit_estimate, [-1, 1])
      if bit_estimate != bit
        nbiterrors += 1
      end
    else
      ndecfails += 1
    end
  end

  nbiterrors, ndecfails, nbiterrors/(n-ndecfails)
end

function sim_ber{T<:DigitalSystem}(s::Vector{T}, bit::Int, n::Int64; verbose::Bool=false)
  slen = length(s)
  output = cell(slen)
  local meter

  if verbose
    println("Execution started at ", now(), "\n\nSimulating BER...")
    meter = ProgressMeter.Progress(slen, "  ")
  end

  for i = 1:slen
    output[i] = sim_ber(s[i], bit, n)
    if verbose; ProgressMeter.next!(meter); end
  end

  if verbose; println("\nExecution completed at ", now()); end

  return output
end

function sim_ber{T<:DigitalSystem}(s::Matrix{T}, bit::Int, n::Int64; verbose::Bool=false)
  nrows, ncols = size(s)
  output = cell(nrows, ncols)
  local meter

  if verbose
    println("Execution started at ", now(), "\n\nSimulating BER...")
    meter = ProgressMeter.Progress(nrows*ncols, "  ")
  end

  for i = 1:nrows
    for j = 1:ncols
      output[i, j] = sim_ber(s[i, j], bit, n)
      if verbose; ProgressMeter.next!(meter); end
    end
  end

  if verbose; println("\nExecution completed at ", now()); end

  return output
end

function pfor_sim_ber(s::DigitalSystem, bit::Int, n::Int64)
  ndecfails, nbiterrors =
  (@parallel (+) for i = 1:n
    bit_estimate = sim_sys(s, bit)
    in(bit_estimate, [-1, 1]) ? (bit_estimate == bit ? [0, 0]: [0, 1]) : [1, 0]
  end)

  nbiterrors, ndecfails, nbiterrors/(n-ndecfails)
end

function pmap_sim_ber(s::DigitalSystem, bit::Int, n::Int64)
  nbiterrors::Int64 = 0
  ndecfails::Int64 = 0
  sim_function(bit::Int) = sim_sys(s, bit)

  bit_estimates = pmap(sim_function, fill(bit, n))

  for i = 1:n
    if in(bit_estimates[i], [-1, 1])
      if bit_estimates[i] != bit
        nbiterrors += 1
      end
    else
      ndecfails += 1
    end
  end

  nbiterrors, ndecfails, nbiterrors/(n-ndecfails)
end

function psim_ber(s::DigitalSystem, bit::Int, n::Int64; ptype::Symbol=:pfor)
  if ptype == :pfor
    pfor_sim_ber(s, bit, n)
  elseif ptype == :pmap
    pmap_sim_ber(s, bit, n)
  else
    error("$ptype parallel implementation not known.")
  end
end

function psim_ber{T<:DigitalSystem}(s::Vector{T}, bit::Int, n::Int64; ptype::Symbol=:pfor, verbose::Bool=false)
  slen = length(s)
  output = cell(slen)
  local meter

  if verbose
    println("Execution started at ", now(), "\n\nSimulating BER...")
    meter = ProgressMeter.Progress(slen, "  ")
  end

  for i = 1:slen
    output[i] = psim_ber(s[i], bit, n; ptype=ptype)
    if verbose; ProgressMeter.next!(meter); end
  end

  if verbose; println("\nExecution completed at ", now()); end

  return output
end

function psim_ber{T<:DigitalSystem}(s::Matrix{T}, bit::Int, n::Int64; ptype::Symbol=:pfor, verbose::Bool=false)
  nrows, ncols = size(s)
  output = cell(nrows, ncols)
  local meter

  if verbose
    println("Execution started at ", now(), "\n\nSimulating BER...")
    meter = ProgressMeter.Progress(nrows*ncols, "  ")
  end

  for i = 1:nrows
    for j = 1:ncols
      output[i, j] = psim_ber(s[i, j], bit, n; ptype=ptype)
      if verbose; ProgressMeter.next!(meter); end
    end
  end

  if verbose; println("\nExecution completed at ", now()); end

  return output
end

function ber_lb{T<:DigitalSystem}(s::Vector{T}; args...)
  slen = length(s)
  output = Array(Float64, slen)

  for i = 1:slen
    output[i] = ber_lb(s[i]; args...)
  end

  return output
end

function ber_lb{T<:DigitalSystem}(s::Matrix{T}; args...)
  nrows, ncols = size(s)
  output = Array(Float64, nrows, ncols)

  for i = 1:nrows
    for j = 1:ncols
      output[i, j] = ber_lb(s[i, j]; args...)
    end
  end

  return output
end


text:
@testset "AffineMean" begin
    N = 20
    D = 3
    x = rand()
    X = [rand(D) for _ in 1:N]
    b = randn()
    w = randn(D)
    μ₀ = AffineMean(w, b; opt=Descent(1.0))
    st = AGP.init_priormean_state((;), μ₀)
    @test μ₀ isa AffineMean{Float64,Vector{Float64},<:Descent}
    @test_nowarn AffineMean(3)(X)
    @test repr("text/plain", μ₀) == "Affine Mean Prior (size(w) = $D, b = $b)"
    @test μ₀(X) == dot.(X, Ref(w)) .+ b
    @test_throws DimensionMismatch AffineMean(4)(X)
    g = Zygote.gradient(μ₀) do m
        sum(m(X))
    end
    AGP.update!(μ₀, st, first(g))
    @test all(μ₀.w .== (w + first(g).w))
    @test first(μ₀.b) == b + first(g).b[1]
end