text:
module DragInts

Base.Experimental.@optlevel 1

using Redux
using CImGui
import ..ReduxImGui: get_label, get_values, get_value

# actions
abstract type AbstractDragIntAction <: AbstractSyncAction end

"""
    Rename(label, new_label)
Change label to `new_label`.
Note that renaming may also change the identifier, please refer to `help?> CImGui.PushID`.
"""
struct Rename <: AbstractDragIntAction
    label::String
    new_label::String
end

"""
    ChangeSize(label, size)
Change widget size to `size`.
Note changing size also changes widget appearance. If the old size is bigger,
those unused states are left intact.
"""
struct ChangeSize <: AbstractDragIntAction
    label::String
    size::Int
end

"""
    ChangeSpeed(label, speed)
Change value's moving speed to `speed`.
"""
struct ChangeSpeed <: AbstractDragIntAction
    label::String
    speed::Cfloat
end

"""
    ChangeRange(label, range)
Change widget range to `range`.
"""
struct ChangeRange <: AbstractDragIntAction
    label::String
    range::Tuple{Cint,Cint}
end

"""
    ChangeRangeMaxTo(label, max)
Change widget max range to `max`.
"""
struct ChangeRangeMaxTo <: AbstractDragIntAction
    label::String
    max::Cint
end

"""
    ChangeRangeMinTo(label, min)
Change widget min range to `min`.
"""
struct ChangeRangeMinTo <: AbstractDragIntAction
    label::String
    min::Cint
end

"""
    ChangeFormat(label, format)
Change value's format to `format`, e.g. "%d".
"""
struct ChangeFormat <: AbstractDragIntAction
    label::String
    format::String
end

# state
struct State <: AbstractImmutableState
    label::String
    vals::Vector{Cint}
    size::Int
    speed::Cfloat
    range::Tuple{Cint,Cint}
    format::String
end
State(
    label::AbstractString;
    vals::Vector{Cint} = Cint[0, 0, 0, 0],
    size = 1,
    speed = 1.0f0,
    range = (Cint(0),Cint(0)),
    format = "%d",
) = State(label, vals, size, speed, range, format)

State(label::AbstractString, val::Integer; args...) =
    State(label; vals = Cint[val, 0, 0, 0], args...)

# reducers
drag_int(state::AbstractState, action::AbstractAction) = state
drag_int(state::Vector{<:AbstractState}, action::AbstractAction) = state
drag_int(state::Dict{String,<:AbstractState}, action::AbstractAction) = state

function drag_int(state::Dict{String,State}, action::AbstractDragIntAction)
    s = Dict{String,State}()
    for (k, v) in state
        s[k] = get_label(v) == action.label ? drag_int(v, action) : v
    end
    return s
end

drag_int(s::State, a::Rename) = State(a.new_label, s.vals, s.size, s.speed, s.range, s.format)
drag_int(s::State, a::ChangeSize) = State(s.label, s.vals, a.size, s.speed, s.range, s.format)
drag_int(s::State, a::ChangeSpeed) = State(s.label, s.vals, s.size, a.speed, s.range, s.format)
drag_int(s::State, a::ChangeRange) = State(s.label, s.vals, s.size, s.speed, a.range, s.format)
drag_int(s::State, a::ChangeRangeMaxTo) = State(s.label, s.vals, s.size, s.speed, (s.range[1], a.max), s.format)
drag_int(s::State, a::ChangeRangeMinTo) = State(s.label, s.vals, s.size, s.speed, (a.min, s.range[2]), s.format)
drag_int(s::State, a::ChangeFormat) = State(s.label, s.vals, s.size, s.speed, s.range, a.format)

# helper
"""
    DragInt(store::AbstractStore, get_state=Redux.get_state) -> Bool
Return `true` when triggered.
"""
function DragInt(store::AbstractStore, get_state = Redux.get_state)
    s = get_state(store)
    min, max = s.range
    if s.size == 1
        is_triggered = CImGui.DragInt(get_label(s), s.vals, s.speed, min, max, s.format)
    elseif s.size == 2
        is_triggered = CImGui.DragInt2(get_label(s), s.vals, s.speed, min, max, s.format)
    elseif s.size == 3
        is_triggered = CImGui.DragInt3(get_label(s), s.vals, s.speed, min, max, s.format)
    elseif s.size == 4
        is_triggered = CImGui.DragInt4(get_label(s), s.vals, s.speed, min, max, s.format)
    else
        is_triggered = false
    end
    return is_triggered
end

get_label(s::State) = s.label
get_values(s::State) = s.vals
get_value(s::State) = first(s.vals)

end # module


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

mutable struct IoK8sApiAuthorizationV1beta1NonResourceAttributes <: SwaggerModel
    path::Any # spec type: Union{ Nothing, String } # spec name: path
    verb::Any # spec type: Union{ Nothing, String } # spec name: verb

    function IoK8sApiAuthorizationV1beta1NonResourceAttributes(;path=nothing, verb=nothing)
        o = new()
        validate_property(IoK8sApiAuthorizationV1beta1NonResourceAttributes, Symbol("path"), path)
        setfield!(o, Symbol("path"), path)
        validate_property(IoK8sApiAuthorizationV1beta1NonResourceAttributes, Symbol("verb"), verb)
        setfield!(o, Symbol("verb"), verb)
        o
    end
end # type IoK8sApiAuthorizationV1beta1NonResourceAttributes

const _property_map_IoK8sApiAuthorizationV1beta1NonResourceAttributes = Dict{Symbol,Symbol}(Symbol("path")=>Symbol("path"), Symbol("verb")=>Symbol("verb"))
const _property_types_IoK8sApiAuthorizationV1beta1NonResourceAttributes = Dict{Symbol,String}(Symbol("path")=>"String", Symbol("verb")=>"String")
Base.propertynames(::Type{ IoK8sApiAuthorizationV1beta1NonResourceAttributes }) = collect(keys(_property_map_IoK8sApiAuthorizationV1beta1NonResourceAttributes))
Swagger.property_type(::Type{ IoK8sApiAuthorizationV1beta1NonResourceAttributes }, name::Symbol) = Union{Nothing,eval(Meta.parse(_property_types_IoK8sApiAuthorizationV1beta1NonResourceAttributes[name]))}
Swagger.field_name(::Type{ IoK8sApiAuthorizationV1beta1NonResourceAttributes }, property_name::Symbol) =  _property_map_IoK8sApiAuthorizationV1beta1NonResourceAttributes[property_name]

function check_required(o::IoK8sApiAuthorizationV1beta1NonResourceAttributes)
    true
end

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

ext: jl


text:
# This is an exact model of a velocity controlled differential drive
# under the following assumptions:
# - the control was applied at the beginning of the time slot
# - the control took effect immediately
# - the wheels don't slip

L = 0.13    # m : distance between the wheels
r = 0.033   # m : wheel radius

# Creates a new state based upon the previous one assuming that the
# specified control that was executed for the specified time.
function new_state(state, control, elapsed_time)
    x, y, θ = state
    ω_left, ω_right = control

    θ⁺ = θ + Δθ(ω_left, ω_right, elapsed_time)
    x⁺ = x + Δx(ω_left, ω_right, θ, θ⁺, elapsed_time)
    y⁺ = y + Δy(ω_left, ω_right, θ, θ⁺, elapsed_time)

    return [x⁺ y⁺ θ⁺]
end

# Change in the x position after the elapsed time.
function Δx(ω_left, ω_right, θ_init, θ_new, elapsed_time)
    if ω_left != ω_right
        L/2.0 * (ω_left + ω_right)/(ω_right - ω_left) * (sin(θ_new) - sin(θ_init))
    else
        r/2.0 * (ω_left + ω_right) * cos(θ_init) * elapsed_time
    end
end

# Change in the y position after the elapsed time.
function Δy(ω_left, ω_right, θ_init, θ_new, elapsed_time)
    if ω_left != ω_right
        L/2.0 * (ω_left + ω_right)/(ω_right - ω_left) * (cos(θ_init) - cos(θ_new))
    else
        r/2.0 * (ω_left + ω_right) * sin(θ_init) * elapsed_time
    end
end

# Change in the orientation after the elapsed time.
Δθ(ω_left, ω_right, elapsed_time) = r/L * (ω_right - ω_left) * elapsed_time

# Creates a new state given with the specified x, y and orientation
# components. The components should be in identical coordinate systems,
# e.g. world.
initial_state(x_world, y_world, θ_world) = [x_world y_world θ_world]

max_stars_repo_name: grgomrton/robot-model

max_issues_repo_name: grgomrton/robot-model

max_forks_repo_name: grgomrton/robot-model


text:
# ---
# title: 306. Additive Number
# id: problem306
# author: Tian Jun
# date: 2020-10-31
# difficulty: Medium
# categories: Backtracking
# link: <https://leetcode.com/problems/additive-number/description/>
# hidden: true
# ---
#
# Additive number is a string whose digits can form additive sequence.
#
# A valid additive sequence should contain **at least** three numbers. Except
# for the first two numbers, each subsequent number in the sequence must be the
# sum of the preceding two.
#
# Given a string containing only digits `'0'-'9'`, write a function to determine
# if it's an additive number.
#
# **Note:** Numbers in the additive sequence **cannot** have leading zeros, so
# sequence `1, 2, 03` or `1, 02, 3` is invalid.
#
#
#
# **Example 1:**
#
#
#
#     Input: "112358"
#     Output: true
#     Explanation: The digits can form an additive sequence: 1, 1, 2, 3, 5, 8.
#                  1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8
#
#
# **Example 2:**
#
#
#
#     Input: "199100199"
#     Output: true
#     Explanation: The additive sequence is: 1, 99, 100, 199.
#                  1 + 99 = 100, 99 + 100 = 199
#
#
#
#
# **Constraints:**
#
#   * `num` consists only of digits `'0'-'9'`.
#   * `1 <= num.length <= 35`
#
# **Follow up:**
# How would you handle overflow for very large input integers?
#
#
## @lc code=start
using LeetCode

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


text:
using FactCheck

using SimpleHttpIO

facts("Test io") do
    data = String["For God so loved the world, that he gave his ",
            "only begotten Son, that whosoever ",
            "believeth in him should not perish, but ",
            "have everlasting life.",
            "(John 3:16)"]

    num_lines = length(data)

    context("writer") do
        io = IOSocket(IOBuffer())

        for d in data
            writeln(io, d)
        end

        seekstart(io.io)

        @fact UTF8String(io.io.data) --> (join(data, CRLF) * "\r\n")
    end

    context("reader") do
        io = IOSocket(IOBuffer())

        for d in data
            writeln(io, d)
        end

        seekstart(io.io)

        context("readbyte") do
            eline = data[1]
            for i in 1:5
                byte = readbyte(io)
                @fact char(byte) --> eline[i]
            end
        end

        seekstart(io.io)

        context("readline") do
            for eline in data
                eline = copy((eline * CRLF).data)
                line = readline(io)
                @fact line --> eline
            end
        end

        seekstart(io.io)

        context("readlinebare") do
            for eline in data
                line = readlinebare(io)
                @fact line --> eline.data
            end
        end

        seekstart(io.io)

        context("readlinestr") do
            for eline in data
                eline = eline * CRLF
                line = readlinestr(io)
                @fact line --> eline
            end
        end

        seekstart(io.io)

        context("readlinebarestr") do
            for eline in data
                line = readlinebarestr(io)
                @fact line --> eline
            end
        end

        context("Base.eachline") do
            seekstart(io.io)

            context("loop Base.eachline :s") do
                i = 1
                for line in eachline(io, :s)
                    @fact line --> (data[i] * CRLF)

                    if i == num_lines
                        break
                    end

                    i += 1
                end
            end

            seekstart(io.io)

            context("Base.eachline :s") do
                eachline(io, :s) do itr, line
                    @fact line --> (data[itr.count] * CRLF)
                    if eof(io.io)
                        stop()
                    end
                end
            end

            seekstart(io.io)

            context("Base.eachline :s!") do
                eachline(io, :s!) do itr, line
                    @fact line --> data[itr.count]
                    if eof(io.io)
                        stop()
                    end
                end
            end

            seekstart(io.io)

            context("Base.eachline :b") do
                eachline(io, :b) do itr, line
                    @fact line --> append!(copy(data[itr.count].data), CRLF.data)
                    if eof(io.io)
                        stop()
                    end
                end
            end

            seekstart(io.io)

            context("Base.eachline :b!") do
                eachline(io, :b!) do itr, line
                    @fact line --> data[itr.count].data
                    if eof(io.io)
                        stop()
                    end
                end
            end
        end
    end

end


text:
import Documenter
import DocumenterMarkdown
import DocumenterLaTeX
import Literate
import PredictMD

import Random
Random.seed!(999)

ENV["PREDICTMD_IS_MAKE_DOCS"] = "true"

generate_examples_output_directory = PredictMD.package_directory(
    "docs",
    "src",
    "examples",
    )

rm(
    generate_examples_output_directory;
    force = true,
    recursive = true,
    )

PredictMD.generate_examples(
    generate_examples_output_directory;
    execute_notebooks = false,
    markdown = true,
    notebooks = true,
    scripts = true,
    include_test_statements = false,
    )

Documenter.makedocs(
    modules = [
        PredictMD,
        PredictMD.Cleaning,
        PredictMD.Compilation,
        PredictMD.GPU,
        PredictMD.Server,
        ],
    pages = [
        "Home" => "index.md",
        "Requirements for plotting (optional)" => "requirements_for_plotting.md",
        "Docker image" => "docker_image.md",
        "Examples" => [
            "Generating these example files on your computer" => "generate_examples/generate_examples.md",
            "Boston housing (single label regression)" => [
                "1\\.  Preprocess data" => "examples/cpu_examples/boston_housing/src/01_preprocess_data.md",
                "2\\.  Linear regressions" => "examples/cpu_examples/boston_housing/src/02_linear_regression.md",
                "3\\.  Random forest regression" => "examples/cpu_examples/boston_housing/src/03_random_forest_regression.md",
                "4\\.  Knet neural network regression" => "examples/cpu_examples/boston_housing/src/04_knet_mlp_regression.md",
                "5\\.  Compare models" => "examples/cpu_examples/boston_housing/src/05_compare_models.md",
                "6\\.  Directly access model output" => "examples/cpu_examples/boston_housing/src/06_get_model_output.md",
                ],
            "Breast cancer biopsy (single label binary classification)" => [
                "1\\.  Preprocess data" => "examples/cpu_examples/breast_cancer_biopsy/src/01_preprocess_data.md",
                "2\\.  Apply SMOTE algorithm" => "examples/cpu_examples/breast_cancer_biopsy/src/02_smote.md",
                "3\\.  Logistic classifier" => "examples/cpu_examples/breast_cancer_biopsy/src/03_logistic_classifier.md",
                "4\\.  Random forest classifier" => "examples/cpu_examples/breast_cancer_biopsy/src/04_random_forest_classifier.md",
                "5\\.  C-SVC support vector machine classifier" => "examples/cpu_examples/breast_cancer_biopsy/src/05_c_svc_svm_classifier.md",
                "6\\.  nu-SVC support vector machine classifier" => "examples/cpu_examples/breast_cancer_biopsy/src/06_nu_svc_svm_classifier.md",
                "7\\.  Knet neural network classifier" => "examples/cpu_examples/breast_cancer_biopsy/src/07_knet_mlp_classifier.md",
                "8\\.  Compare models" => "examples/cpu_examples/breast_cancer_biopsy/src/08_compare_models.md",
                "9\\.  Directly access model output" => "examples/cpu_examples/breast_cancer_biopsy/src/09_get_model_output.md",
                ],
            ],
        "Library" => [
            "Internals" => "library/internals.md",
            ],
        ],
    root = PredictMD.package_directory(
        "docs",
        ),
    sitename = "PredictMD documentation",
    )

ENV["PREDICTMD_IS_MAKE_DOCS"] = "false"

ENV["PREDICTMD_IS_DEPLOY_DOCS"] = "true"

COMPILED_MODULES_CURRENT_VALUE = strip(
    lowercase(strip(get(ENV, "COMPILED_MODULES", "")))
    )
COMPILED_MODULES_VALUE_FOR_DOCS = strip(
    lowercase(strip(get(ENV, "COMPILED_MODULES_VALUE_FOR_DOCS", "")))
    )
JULIA_VERSION_FOR_DOCS = strip(
    lowercase(strip(get(ENV, "JULIA_VERSION_FOR_DOCS", "")))
    )

@debug("COMPILED_MODULES_CURRENT_VALUE: ", COMPILED_MODULES_CURRENT_VALUE,)
@debug("COMPILED_MODULES_VALUE_FOR_DOCS: ", COMPILED_MODULES_VALUE_FOR_DOCS,)

if COMPILED_MODULES_CURRENT_VALUE == COMPILED_MODULES_VALUE_FOR_DOCS
    Documenter.deploydocs(
        target = "build",
        repo = "github.com/bcbi/PredictMD.jl.git",
        branch = "gh-pages",
        devbranch = "master",
        devurl = "development",
        )
end

ENV["PREDICTMD_IS_DEPLOY_DOCS"] = "false"


text:
using UnitfulDual
using Unitful
using Test
using Suppressor
using NamedTupleTools

@testset "UnitfulDual.jl" begin

    # Creation of UnitDual numbers with tuple and args - unnamed
    a = 1.0u"mol/L"
    da = UnitDual(a, 1.0)
    da2 = UnitDual(a, (1.0, ))
    @test da === da2
    @test da isa UnitDual
    @test value(da) === a
    @test partials(da) === UnitPartials((1.0))

    # Creation of UnitDual numbers with tuple and args - named
    nda = UnitDual(a, a = 1.0)
    @test nda isa UnitDual
    @test value(nda) === a
    @test partials(nda) === UnitPartials((a = 1.0,))

    # Dual numbers with several partials - unnamed
    a = 1.0u"mol/L"
    b = 0.5u"mol/L"
    c = 1.0u"1/s"
    da = UnitDual(a, 1.0, 0.0, zero(a/c))
    db = UnitDual(b, 0.0, 1.0, zero(b/c))
    dc = UnitDual(c, zero(c/a), zero(c/b), 1.0)
    @test length(partials(da)) == 3
    @test partials(da)[1] == 1.0
    @test partials(da)[3] isa Quantity

    du = UnitDual(1.0, 1.0)

    # Dual numbers with several partials - named
    nda = UnitDual(a, a = 1.0, b = 0.0, c = zero(a/c))
    ndb = UnitDual(b, a = 0.0, b = 1.0, c = zero(b/c))
    ndc = UnitDual(c, a = zero(c/a), b = zero(c/b), c = 1.0)
    @test length(partials(nda)) == 3
    @test partials(nda)[1] == 1.0
    @test partials(nda)[3] isa Quantity

    ndu = UnitDual(1.0, u = 1.0)

    # Addition of Dual Numbers - unnamed
    dd = da + db
    @test dd isa UnitDual
    @test length(partials(dd)) == 3
    @test value(dd) == a + b
    @test partials(dd) === UnitPartials(1.0, 1.0, zero(a/c))
    @test_throws Unitful.DimensionError da + dc
    @test_throws Unitful.DimensionError da + 1
    ddu = du + 1.0
    @test value(ddu) == 2.0
    @test partials(ddu) === UnitPartials(1.0)
    @test du + 1.0 === 1.0 + du

    # Addition of Dual Numbers - named
    ndd = nda + ndb
    @test ndd isa UnitDual
    @test length(partials(ndd)) == 3
    @test value(ndd) == a + b
    @test partials(ndd) === UnitPartials(a = 1.0, b = 1.0, c = zero(a/c))
    @test_throws Unitful.DimensionError nda + ndc
    @test_throws Unitful.DimensionError nda + 1
    nddu = ndu + 1.0
    @test value(nddu) == 2.0
    @test partials(nddu) === UnitPartials(u = 1.0)
    @test ndu + 1.0 === 1.0 + ndu

    # Substraction of Dual Numbers - unnamed
    dd = da - db
    @test dd isa UnitDual
    @test length(partials(dd)) == 3
    @test value(dd) == a - b
    @test partials(dd) === UnitPartials(1.0, -1.0, zero(a/c))
    @test_throws Unitful.DimensionError da - dc
    @test_throws Unitful.DimensionError da - 1
    ddu = du - 1.0
    @test value(ddu) == 0.0
    @test partials(ddu) === UnitPartials(1.0)
    ddu = 1.0 - du
    @test value(ddu) == 0.0
    @test partials(ddu) === UnitPartials(-1.0)

    # Substraction of Dual Numbers - named
    ndd = nda - ndb
    @test ndd isa UnitDual
    @test length(partials(ndd)) == 3
    @test value(ndd) == a - b
    @test partials(ndd) === UnitPartials(a = 1.0, b = -1.0, c = zero(a/c))
    @test_throws Unitful.DimensionError nda - ndc
    @test_throws Unitful.DimensionError nda - 1
    nddu = ndu - 1.0
    @test value(nddu) == 0.0
    @test partials(nddu) === UnitPartials(u = 1.0)
    nddu = 1.0 - ndu
    @test value(nddu) == 0.0
    @test partials(nddu) === UnitPartials(u = -1.0)

    # Negation of Dual Numbers - unnamed
    dd = -da
    @test dd isa UnitDual
    @test length(partials(dd)) == 3
    @test value(dd) == -a
    @test partials(dd) === UnitPartials((-t for t in partials(da))...)

    # Negation of Dual Numbers - named
    ndd = -nda
    @test ndd isa UnitDual
    @test length(partials(ndd)) == 3
    @test value(ndd) == -a
    @test partials(ndd) === UnitPartials(a = -partials(nda).a,
                    b = -partials(nda).b, c = -partials(nda).c)

    # Multiplication of Dual Numbers - unnamed
    dd = da*db
    @test dd isa UnitDual
    @test length(partials(dd)) == 3
    @test value(dd) == a*b
    @test partials(dd) === UnitPartials(b, a, zero(a*b/c))
    ddr = da*3
    ddl = 3*da
    @test ddr === ddl
    @test ddr isa UnitDual
    @test value(ddr) == 3*a
    @test partials(ddr) == UnitPartials((3*t for t in partials(da))...)
    ddu = du*3
    @test value(ddu) == 3.0
    @test partials(ddu) === UnitPartials(3.0)

    # Multiplication of Dual Numbers - named
    ndd = nda*ndb
    @test ndd isa UnitDual
    @test length(partials(ndd)) == 3
    @test value(ndd) == a*b
    @test partials(ndd) === UnitPartials(a = b, b = a, c = zero(a*b/c))
    nddr = nda*3
    nddl = 3*nda
    @test nddr === nddl
    @test nddr isa UnitDual
    @test value(nddr) == 3*a
    @test partials(nddr) == UnitPartials(a = 3*partials(nda).a,
    b = 3*partials(nda).b, c = 3*partials(nda).c)
    nddu = ndu*3
    @test value(nddu) == 3.0
    @test partials(nddu) === UnitPartials(u = 3.0)

    # Division of Dual Numbers - unnamed
    dd = da/db
    @test dd isa UnitDual
    @test length(partials(dd)) == 3
    @test value(dd) == a/b
    @test partials(dd) === UnitPartials(1/b, -a/b^2, zero(1/c))
    ddr = da/2
    ddl = 2/da
    @test typeof(ddr) != typeof(ddl)
    @test value(ddr) == a/2
    @test value(ddl) == 2/a
    @test partials(ddr) === UnitPartials((t/2 for t in partials(da))...)
    @test partials(ddl) === UnitPartials((-2/a^2*t for t in partials(da))...)
    ddur = du/3
    ddul = 3/du
    @test typeof(ddur) == typeof(ddul)
    @test value(ddur) == 1/3
    @test value(ddul) == 3.0
    @test partials(ddur) === UnitPartials(1/3)
    @test partials(ddul) === UnitPartials(-3.0)
    @test inv(db) === 1/db

    # Division of Dual Numbers - named
    ndd = nda/ndb
    @test ndd isa UnitDual
    @test length(partials(ndd)) == 3
    @test value(ndd) == a/b
    @test partials(ndd) === UnitPartials(a = 1/b, b = -a/b^2, c = zero(1/c))
    nddr = nda/2
    nddl = 2/da
    @test typeof(nddr) != typeof(nddl)
    nddur = ndu/3
    nddul = 3/ndu
    @test typeof(nddur) == typeof(nddul)
    @test value(nddur) == 1/3
    @test value(nddul) == 3.0
    @test partials(nddur) === UnitPartials(u = 1/3)
    @test partials(nddul) === UnitPartials(u = -3.0)
    @test inv(ndb) === 1/ndb

    # Power - unnamed
    dd = db^2
    @test dd isa UnitDual
    @test value(dd) === b^2
    @test partials(dd) === UnitPartials((2*b*t for t in partials(db))...)

    # Power - named
    ndd = ndb^2
    @test ndd isa UnitDual
    @test value(ndd) === b^2
    @test partials(ndd) === UnitPartials(a = 2*b*partials(ndb).a,
                    b = 2*b*partials(ndb).b, c = 2*b*partials(ndb).c)

    # Logical operators - unnamed
    @test da >= db
    @test da >= b
    @test_throws Unitful.DimensionError da >= b.val
    @test db <= da
    @test b <= da
    @test_throws Unitful.DimensionError b.val <= da
    @test da == 2*db
    @test da == 2*b
    @test da ≈ UnitDual(a*(1.0 +  + eps(Float64)), 1.0, 0.0, zero(a/c))
    @test da != 2*b.val
    @test du >= 0.5
    @test du <= 1.5
    @test 0.5 <= du
    @test du == 1.0
    @test 1.0 == du
    @test du ≈ 1.0 + eps(Float64)
    @test 1.0 + eps(Float64) ≈ du

    # Logical operators - named
    @test nda >= ndb
    @test nda >= b
    @test_throws Unitful.DimensionError nda >= b.val
    @test ndb <= nda
    @test b <= nda
    @test_throws Unitful.DimensionError b.val <= nda
    @test nda == 2*ndb
    @test nda == 2*b
    @test nda ≈ UnitDual(a*(1.0 +  + eps(Float64)), a = 1.0, b = 0.0, c = zero(a/c))
    @test nda != 2*b.val
    @test ndu >= 0.5
    @test ndu <= 1.5
    @test 0.5 <= ndu
    @test ndu == 1.0
    @test 1.0 == ndu
    @test ndu ≈ 1.0 + eps(Float64)
    @test 1.0 + eps(Float64) ≈ ndu

    # Unary mathematical functions (most of them only works with unitless variables) - unnamed
    @test sqrt(db) ≈ db^(1//2)
    @test cbrt(db) ≈ db^(1//3)
    @test abs(-db) === db
    @test abs2(-db) === db^2
    @test_throws MethodError log(db)
    @test log(du) == log(1.0)
    @test_throws MethodError log10(db)
    @test log10(du) == log10(1.0)
    @test_throws MethodError log2(db)
    @test log2(du) == log2(1.0)
    @test_throws MethodError exp(db)
    @test exp(du) == exp(1.0)
    @test_throws MethodError sin(db)
    @test sin(du) == sin(1.0)
    @test_throws MethodError cos(db)
    @test cos(du) == cos(1.0)
    @test_throws MethodError tan(db)
    @test tan(du) == tan(1.0)
    @test_throws MethodError sec(db)
    @test sec(du) == sec(1.0)
    @test_throws MethodError csc(db)
    @test csc(du) == csc(1.0)
    @test_throws MethodError cot(db)
    @test cot(du) == cot(1.0)
    @test_throws MethodError acos(db)
    @test acos(du) == acos(1.0)
    @test_throws MethodError atan(db)
    @test atan(du) == atan(1.0)
    @test_throws MethodError asec(db)
    @test asec(du) == asec(1.0)
    @test_throws MethodError acsc(db)
    @test acsc(du) == acsc(1.0)
    @test_throws MethodError acot(db)
    @test acot(du) == acot(1.0)

    # Unary mathematical functions (most of them only works with unitless variables) - named
    @test sqrt(ndb) ≈ ndb^(1//2)
    @test cbrt(ndb) ≈ ndb^(1//3)
    @test abs(-ndb) === ndb
    @test abs2(-ndb) === ndb^2
    @test_throws MethodError log(ndb)
    @test log(ndu) == log(1.0)
    @test_throws MethodError log10(ndb)
    @test log10(ndu) == log10(1.0)
    @test_throws MethodError log2(ndb)
    @test log2(ndu) == log2(1.0)
    @test_throws MethodError exp(ndb)
    @test exp(ndu) == exp(1.0)
    @test_throws MethodError sin(ndb)
    @test sin(ndu) == sin(1.0)
    @test_throws MethodError cos(ndb)
    @test cos(ndu) == cos(1.0)
    @test_throws MethodError tan(ndb)
    @test tan(ndu) == tan(1.0)
    @test_throws MethodError sec(ndb)
    @test sec(ndu) == sec(1.0)
    @test_throws MethodError csc(ndb)
    @test csc(ndu) == csc(1.0)
    @test_throws MethodError cot(ndb)
    @test cot(ndu) == cot(1.0)
    @test_throws MethodError acos(ndb)
    @test acos(ndu) == acos(1.0)
    @test_throws MethodError atan(ndb)
    @test atan(ndu) == atan(1.0)
    @test_throws MethodError asec(ndb)
    @test asec(ndu) == asec(1.0)
    @test_throws MethodError acsc(ndb)
    @test acsc(ndu) == acsc(1.0)
    @test_throws MethodError acot(ndb)
    @test acot(ndu) == acot(1.0)

    # Printing - unnamed
    printdual = @capture_out print(da)
    @test '{' in printdual
    @test occursin("mol" , printdual)

    # Printing - named
    printdual = @capture_out print(nda)
    @test '{' in printdual
    @test '=' in printdual
    @test occursin("mol" , printdual)

    # Convenience functions  - unnamed
    da0 = zero(da)
    @test da0 isa UnitDual
    @test value(da0) === zero(a)
    @test partials(da0) === UnitPartials((zero(p) for p in partials(da))...)
    @test zeros(typeof(da), 2) == [da0, da0]
    @test zeros(typeof(da), 2)  == [da0, da0]

    # Convenience functions  - named
    nda0 = zero(typeof(nda))
    @test nda0 isa UnitDual
    @test value(nda0) === zero(a)
    # The following tests have some issues with conversion of FreeUnits into Float64
    @test_broken partials(nda0) == UnitPartials(a = zero(a/a), b = zero(a/b), c = zero(a/c))
    @test_broken zeros(typeof(nda), 2) == [nda0, nda0]
    @test_broken zeros(typeof(nda), 2)  == [nda0, nda0]

    # Iteration- unnamed
    @test length(da) === 1
    @test da.*[1,2] == [da, 2*da]

    # Iteration- named
    @test length(nda) === 1
    @test nda.*[1,2] == [nda, 2*nda]

    # Automatically generate UnitDual objects with partial derivatives
    duals_dict = initialize_dual(Dict(:a => a, :b => b, :c => c), (:a, :b))
    @test duals_dict isa Dict
    @test length(duals_dict) == 3
    @test Symbol.(keys(duals_dict)) == [:a, :b, :c]
    @test all([length(partials(dual)) == 2 for dual in values(duals_dict)])
    @test partials(duals_dict[:a]).a === 1.0
    @test partials(duals_dict[:a]).b === 0.0
    @test partials(duals_dict[:b]).a === 0.0
    @test partials(duals_dict[:b]).b === 1.0
    @test partials(duals_dict[:c]).a === zero(c/a)
    @test partials(duals_dict[:c]).b === zero(c/b)

    duals_ntuple = initialize_dual((a = a, b = b, c = c), (:a, :b))
    @test duals_ntuple isa NamedTuple
    @test length(duals_ntuple) == 3
    @test keys(duals_ntuple) == (:a, :b, :c)
    @test all([length(partials(dual)) == 2 for dual in values(duals_ntuple)])
    @test partials(duals_ntuple[:a]).a === 1.0
    @test partials(duals_ntuple[:a]).b === 0.0
    @test partials(duals_ntuple[:b]).a === 0.0
    @test partials(duals_ntuple[:b]).b === 1.0
    @test partials(duals_ntuple[:c]).a === zero(c/a)
    @test partials(duals_ntuple[:c]).b === zero(c/b)

end


text:
include("../../utils.jl")
using Random

# This program generates random length strings made up of ACTG characters.
# The idea is that there will be a significant number of repeated strings.
# The repeated strings are counted but the strings themselves are garbage.
# The result should be significant multi-sized fragmentation in the heap.

mutable struct TreeNode
   key::String
   count::Int
   left::TreeNode
   right::TreeNode
   next::TreeNode
   TreeNode() = new()
   TreeNode(x) = new(x,1)
   TreeNode(x,y) = new(x,y)
   TreeNode(n::TreeNode) = new(n.key, n.count)
end

function getKey(x::TreeNode) return x.key end
function getCount(x::TreeNode) return x.count end

function compare(g, x::TreeNode, y::TreeNode)
   if (g(x) < g(y))
      return -1
   elseif (g(x) == g(y))
      return 0
   else
      return 1
   end
end

function compareCount(x::TreeNode, y::TreeNode)
  return compare(getCount, x, y)
end

function compareKey(x::TreeNode, y::TreeNode)
  return compare(getKey, x, y)
end

function duplicateKey(root::TreeNode, n::TreeNode)
  root.count = root.count + 1;
end

function duplicateCount(root::TreeNode,n::TreeNode)
  if !isdefined(root,:next)
     root.next = n
  else
     n.next = root.next
     root.next = n
  end
end

function insert(root::TreeNode,n::TreeNode,compare,duplicate)
   result = compare(root,n)
   if result < 0
      if !isdefined(root,:left)
         root.left = TreeNode(n)
      else
         insert(root.left, n, compare, duplicate)
      end
   elseif result > 0
      if !isdefined(root,:right)
         root.right = TreeNode(n)
      else
         insert(root.right, n, compare, duplicate)
      end
   else
      duplicate(root,n)
  end
end

function traverse(n::TreeNode, f)
   if isdefined(n,:left)
      traverse(n.left, f)
   end

   f(n)

   if isdefined(n,:right)
      traverse(n.right, f)
   end
end

function print(n::TreeNode)
   count = 1
   while (isdefined(n,:next))
      n = n.next
      count = count + 1
   end
   println("There was/were ", count,  " string(s) that was/were repeated ", n.count, " times")
end

function tree(root::TreeNode, n)
   for i in 1:n
      insert(root, TreeNode(randstring("ACTG", rand(1:32))), compareKey,duplicateKey)
   end
end

resultRoot = TreeNode("end")

function insertHelper(n::TreeNode)
   insert(resultRoot, n, compareCount, duplicateCount)
end

#Build the tree sorted by count
function SortTree(n::TreeNode)
   traverse(n::TreeNode, insertHelper)
   return resultRoot
end

function test(n)
   startroot = TreeNode("start")
   buildtree = tree(startroot, n)
   result = SortTree(startroot)
#   println("done with sort")
#   traverse(result, print)
   return 6847
end

@gctime test(1024 * 1024 * 8)

max_stars_repo_name: vtjnash/GCBenchmarks

max_issues_repo_name: vtjnash/GCBenchmarks

max_forks_repo_name: vtjnash/GCBenchmarks


text:
# @rosimport visualization_msgs.msg: Marker
# rostypegen()
using Colors
import visualization_msgs.msg: Marker

# const CAR_X = 4.22100019455    # VTD car
# const CAR_Y = 1.76199996471
# const CAR_dX = 1.3654999733

const CAR_X  = 3.79    # X1 equivalent
const CAR_Y  = 1.87
const CAR_dX = 0.095

function car_marker(body_frame_id, color=(255,0,0), alpha=1.0)
    color isa String && (color = parse(Colorant, color))
    color isa RGB && (color = (color.r.i, color.g.i, color.b.i))
    eltype(color) isa Integer && (color = (c/255 for c in color))

    m = Marker()
    m.header.frame_id = body_frame_id
    m.ns = "rectangle"
    m.id = 0
    m.type = Marker[:CUBE]
    m.pose.position.x = CAR_dX
    m.pose.orientation.w = 1.0
    m.scale.x = CAR_X
    m.scale.y = CAR_Y
    m.scale.z = 1.0
    m.color.r = color[1]/255
    m.color.g = color[2]/255
    m.color.b = color[3]/255
    m.color.a = alpha
    m.frame_locked = true
    m
end

function text_marker(body_frame_id, color=(255,0,0), s=1.0, alpha=1.0)
    color isa String && (color = parse(Colorant, color))
    color isa RGB && (color = (color.r.i, color.g.i, color.b.i))
    eltype(color) isa Integer && (color = (c/255 for c in color))

    m = Marker()
    m.header.frame_id = body_frame_id
    m.ns = "text"
    m.id = 1
    m.type = Marker[:TEXT_VIEW_FACING]
    m.pose.orientation.w = 1.0
    m.pose.position.z = 1.0
    m.scale.z = s
    m.color.r = color[1]/255
    m.color.g = color[2]/255
    m.color.b = color[3]/255
    m.color.a = alpha
    m.frame_locked = true
    m
end


text:
points(H::Hermite,n) = gausshermite(n)[1] ./ sqrt.(H.L)

plan_transform(H::Hermite,v::AbstractVector) = TransformPlan(H,gausshermite(length(v)),Val{false})
plan_itransform(H::Hermite,cfs::AbstractVector) = ITransformPlan(H,points(Hermite(),length(cfs)),Val{false})

function *(P::TransformPlan{T,H,false},vals::AbstractVector) where {T,H<:Hermite}
    x,w = P.plan
    V=hermitep.(0:length(vals)-1,transpose(x))
    nrm=(V.^2)*w
    V*(w.*vals)./nrm
end

*(P::ITransformPlan{T,H,false},cfs::AbstractVector) where {T,H<:Hermite} =
    hermitep.((0:length(cfs)-1)',P.plan)*cfs


text:
using Base.Meta
using .Compiler: IRCode, IncrementalCompact, process_node!, BasicBlock, Const, Bottom, quoted,
    stmt_effect_free

function agressive_new_tfunc(stmt, t, ir, sv)
    isconst = true
    args = Vector{Any}(undef, length(stmt.args) - 1)
    for i = 2:length(stmt.args)
        at = Compiler.argextype(stmt.args[i], ir, sv.sp)
        if at === Bottom
            t = Bottom
            isconst = false
            break
        elseif at isa Const
            if !(at.val isa fieldtype(t, i - 1))
                t = Bottom
                isconst = false
                break
            end
            args[i-1] = at.val
        else
            isconst = false
        end
    end
    if isconst
        t = Const(ccall(:jl_new_structv, Any, (Any, Ptr{Cvoid}, UInt32), t, args, length(args)))
    end
    t
end

function refine_types!(ir, sv)
    for i = 1:length(ir.stmts)
        stmt = ir.stmts[i]
        if isexpr(stmt, :static_parameter)
            @assert isa(ir.types[i], Const)
            ir.stmts[i] = ir.types[i].val
            continue
        end
        (isexpr(stmt, :call) || isexpr(stmt, :new)) || continue
        arg1t = Compiler.argextype(stmt.args[1], ir, sv.sp)
        # This is a more agressive version of the tfunc inference we do for :new
        if isexpr(stmt, :new)
            if !isa(arg1t, Const) || arg1t.val.mutable
                continue
            end
            t = agressive_new_tfunc(stmt, arg1t.val, ir, sv)
            ir.types[i] = t
            if isa(t, Const) && stmt_effect_free(stmt, t, ir, ir.spvals)
                ir.stmts[i] = t.val
            end
            continue
        end
        f = Compiler.singleton_type(arg1t)
        f === nothing && continue
        if isa(f, Core.Builtin)
            argtypes = Any[Compiler.argextype(stmt.args[i], ir, sv.sp) for i in 2:length(stmt.args)]
            rt = Compiler.builtin_tfunction(f, argtypes, nothing, sv.params)
            ir.types[i] = rt
        end
    end
    ir
end

# Kills a bunch of debris that is left over, but base julia cannot yet prove
# to be effect free. Ideally this function wouldn't exist
function kill_useless_stmts!(ir)
    for i = 1:length(ir.stmts)
        stmt = ir.stmts[i]
        if isexpr(stmt, :gc_preserve_begin) || isexpr(stmt, :gc_preserve_end)
            ir.stmts[i] = nothing
        elseif isexpr(stmt, :foreigncall)
            if isa(stmt.args[1], QuoteNode) && stmt.args[1].value == :jl_value_ptr
                ir.stmts[i] = C_NULL
            end
        end
    end
end

function run_xla_embedding_passes!(ir, sv)
    Compiler.verify_ir(ir);
    ir = Compiler.compact!(ir, true)
    kill_useless_stmts!(ir)
    Compiler.verify_ir(ir);
    domtree = Compiler.construct_domtree(ir.cfg);
    ir = Compiler.domsort_ssa!(ir, domtree);
    Compiler.verify_ir(ir);
    ir = Compiler.cfg_simplify!(ir)
    Compiler.verify_ir(ir);
    ir = Compiler.compact!(ir, true)
    ir = refine_types!(ir, sv)
    ir = Compiler.ssa_inlining_pass!(ir, ir.linetable, sv)
    ir = Compiler.compact!(ir, true)
    for i = 1:3
        domtree = Compiler.construct_domtree(ir.cfg);
        ir = Compiler.domsort_ssa!(ir, domtree)
        Compiler.verify_ir(ir);
        ir = Compiler.cfg_simplify!(ir)
        ir = Compiler.compact!(ir, true)
    end
    ir = Compiler.compact!(ir)
    ir = Compiler.compact!(ir)
    Compiler.verify_ir(ir);
    ir, sv
end


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

@doc raw"""Adapts a ConfigMap into a projected volume.  The contents of the target ConfigMap's Data field will be presented in a projected volume as files using the keys in the Data field as the file names, unless the items element is populated with specific mappings of keys to paths. Note that this is identical to a configmap volume source without the default mode.

    IoK8sApiCoreV1ConfigMapProjection(;
        items=nothing,
        name=nothing,
        optional=nothing,
    )

    - items::Vector{IoK8sApiCoreV1KeyToPath} : If unspecified, each key-value pair in the Data field of the referenced ConfigMap will be projected into the volume as a file whose name is the key and content is the value. If specified, the listed keys will be projected into the specified paths, and unlisted keys will not be present. If a key is specified which is not present in the ConfigMap, the volume setup will error unless it is marked optional. Paths must be relative and may not contain the '..' path or start with '..'.
    - name::String : Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names
    - optional::Bool : Specify whether the ConfigMap or its keys must be defined
"""
mutable struct IoK8sApiCoreV1ConfigMapProjection <: SwaggerModel
    items::Any # spec type: Union{ Nothing, Vector{IoK8sApiCoreV1KeyToPath} } # spec name: items
    name::Any # spec type: Union{ Nothing, String } # spec name: name
    optional::Any # spec type: Union{ Nothing, Bool } # spec name: optional

    function IoK8sApiCoreV1ConfigMapProjection(;items=nothing, name=nothing, optional=nothing)
        o = new()
        validate_property(IoK8sApiCoreV1ConfigMapProjection, Symbol("items"), items)
        setfield!(o, Symbol("items"), items)
        validate_property(IoK8sApiCoreV1ConfigMapProjection, Symbol("name"), name)
        setfield!(o, Symbol("name"), name)
        validate_property(IoK8sApiCoreV1ConfigMapProjection, Symbol("optional"), optional)
        setfield!(o, Symbol("optional"), optional)
        o
    end
end # type IoK8sApiCoreV1ConfigMapProjection

const _property_map_IoK8sApiCoreV1ConfigMapProjection = Dict{Symbol,Symbol}(Symbol("items")=>Symbol("items"), Symbol("name")=>Symbol("name"), Symbol("optional")=>Symbol("optional"))
const _property_types_IoK8sApiCoreV1ConfigMapProjection = Dict{Symbol,String}(Symbol("items")=>"Vector{IoK8sApiCoreV1KeyToPath}", Symbol("name")=>"String", Symbol("optional")=>"Bool")
Base.propertynames(::Type{ IoK8sApiCoreV1ConfigMapProjection }) = collect(keys(_property_map_IoK8sApiCoreV1ConfigMapProjection))
Swagger.property_type(::Type{ IoK8sApiCoreV1ConfigMapProjection }, name::Symbol) = Union{Nothing,eval(Base.Meta.parse(_property_types_IoK8sApiCoreV1ConfigMapProjection[name]))}
Swagger.field_name(::Type{ IoK8sApiCoreV1ConfigMapProjection }, property_name::Symbol) =  _property_map_IoK8sApiCoreV1ConfigMapProjection[property_name]

function check_required(o::IoK8sApiCoreV1ConfigMapProjection)
    true
end

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


text:
function _veccat(b::AbstractVector{S}, β::S, force=false) where S
    push!(b, β)
    b
end
function _veccat(b::AbstractSparseVector{S}, β::S, force=false) where S
    if force || β == zero(S)
        # If only homogeneous cuts, b stays sparse
        [b; sparsevec([β])]
    else
        # At the first non-homogeneous cut, b stops being sparse
        [b; β]
    end
end

# see https://github.com/JuliaLang/julia/issues/16661
function _matcat(A::AbstractMatrix{S}, a::AbstractVector{S}) where S
    [A; a']
end
function _matcat(A::AbstractSparseMatrix{S}, a::AbstractSparseVector{S}) where S
    [A; sparse(a')]
end

mutable struct CutStore{S}
    A::AbstractMatrix{S}
    b::AbstractVector{S}
    authors::Vector
    Anew::AbstractMatrix{S}
    bnew::AbstractVector{S}
    authorsnew::Vector

    followers::Vector
    needstored::Vector{Bool}

    storecuts::Symbol

    function CutStore{S}(nvars) where {S}
        # spzeros(S, 0) -> S[] : See julia#22225
        new{S}(spzeros(S, 0, nvars), S[], NLDS{S}[], spzeros(S, 0, nvars), S[], NLDS{S}[], Tuple{NLDS{S},Tuple{Symbol,Int}}[], Bool[], :IfNeededElseDelete)
    end
end

function checksparseness(a::AbstractVector)
    if true || countnz(a) * 2 < length(a)
        sparse(a)
    else
        a
    end
end

function addcut(store::CutStore{S}, a::AbstractVector{S}, β::S, author) where S
    a = checksparseness(a)
    store.Anew = _matcat(store.Anew, a)
    store.bnew = _veccat(store.bnew, β)
    push!(store.authorsnew, author)
end

function apply!(store::CutStore{S}) where S
    if !isempty(store.bnew)
        if store.storecuts == :Yes || (store.storecuts != :No && Compat.reduce(|, store.needstored, init=false))
            store.A = [store.A; store.Anew]
            store.b = [store.b; store.bnew]
            append!(store.authors, store.authorsnew)
        end

        for follower in store.followers
            notifynewcuts(follower[1], store.Anew, store.bnew, follower[2], store.authorsnew)
        end

        store.Anew = spzeros(S, 0, size(store.A, 2))
        store.bnew = S[] # See julia#22225
        store.authorsnew = NLDS{S}[]
    end
end

function addfollower(store::CutStore, nlds)
    push!(store.followers, nlds)
    push!(store.needstored, true)
end

function needstored!(store::CutStore, nlds)
    store.needstored[findfirst(f->f[1] === nlds, store.followers)] = true
end
function noneedstored!(store::CutStore{S}, nlds) where S
    store.needstored[findfirst(f->f[1] === nlds, store.followers)] = false
    if store.storecuts == :IfNeededElseDelete && !Compat.reduce(|, store.needstored, init=false)
        store.A = spzeros(S, 0, size(store.A, 2))
        store.b = S[] # See julia#22225
        store.authors = NLDS{S}[]
    end
end


text:
using Stardates
using Test
using TimeZones

@testset "Stardates.jl" begin
        @test Stardates.millisecond > 0.0
        @test length(canonical(Stardate())) == 20
        @test length(short(Stardate())) == 8
        @test abs(Stardate(ZonedDateTime(
                2019,
                8,
                26,
                19,
                33,
                42,
                tz"America/Los_Angeles",
        )).sd - 2019.652347222222261) < 3.0 * Stardates.second
        @test abs(Stardate(ZonedDateTime(2012, 1, 2, 3, 4, 5, tz"UTC")).sd -
                  2012.0030815181644) < 3.0 * Stardates.second
        @test abs(Stardate(ZonedDateTime(
                2014,
                9,
                30,
                17,
                17,
                27,
                tz"America/Los_Angeles",
        )).sd - 2014.747978420491791) < 3.0 * Stardates.second
        @test abs(nyse_closing_stardate("2014-09-30") -
                  2014.747488584474922) < 3.0 * Stardates.second
        @test abs(Stardate(DateTime(2012, 1, 2, 3, 4, 5)).sd -
                  2012.0030815181644) < 3.0 * Stardates.second

        sd1 = Stardate()
        sleep(1.0)
        f1 = tempname()
        write(f1, "Hello")
        sd2 = Stardate(stat(f1))
        rm(f1)
        sleep(1.0)
        sd3 = Stardate()
        @test sd1.sd <= sd2.sd
        @test sd2.sd <= sd3.sd

    # Test against Python implementation output
        @test stardate(ZonedDateTime(
                2019,
                10,
                11,
                11,
                7,
                0,
                tz"America/Los_Angeles",
        )) ≈ 2019.7774105783867

end


text:
export rarefaction_wave_builder

function rarefaction_wave_builder(;
    width::Number = 1.0,
    ρ::Number = 1.0,
    u::Number = 2.0,
    number_of_particles::Integer = 200,
    γ::Number = 1.4,
)
    exterior_boundary_positions = Bounds(-0.5 * width, 0.5 * width)
    interior_boundary_positions = Float[]
    mass_densities = [ρ]
    mass_distribution = PiecewiseUniformMassDistribution(
        exterior_boundary_positions,
        interior_boundary_positions,
        mass_densities,
        number_of_particles,
    )
    energy_distribution = UniformEnergyDistribution{1}(u)

    SimulationBuilder(
        mass_distribution,
        energy_distribution,
        eos = AdiabaticIdealGasEOS(γ, NORMALIZED),
        velocity_distribution = StaticVelocityDistribution{1}(),
    )
end

max_stars_repo_name: lars-frogner/Whirl

max_issues_repo_name: lars-frogner/Whirl

max_forks_repo_name: lars-frogner/Whirl


text:
function lock_clock(cur_player::AbstractPlayer)

  cur_uuid = UUIDs.uuid4()

  cur_player.clock.lock = cur_uuid

  max_time = Dates.Millisecond(500)

  wait_time = max_time

  start_now = now()

  cur_player.clock.last_move = Nullable{DateTime}()

  @async while check_clock(cur_player, :lock, cur_uuid)

    isnull(cur_player.clock.last_move) &&
      ( cur_player.clock.last_move = start_now )

    cur_time = max(
      start_now,
      cur_player.clock.last_move
    )

    time_diff = ( now() - cur_time )

    if time_diff < max_time
      sleep(max_time - time_diff)
      continue
    end

    glue_piece!(cur_player)
    break

  end

end


text:
## train.jl  Likelihood calculation and em training for GMMs.
## (c) 2013--2014 David A. van Leeuwen

using StatsBase: sample
using Logging
using LinearAlgebra
using Arpack

## Greate a GMM with only one mixture and initialize it to ML parameters
function GMM(x::DataOrMatrix{T}; kind=:diag) where T <: AbstractFloat
    n, sx, sxx = stats(x, kind=kind)
    μ = sx' ./ n                        # make this a row vector
    d = length(μ)
    if kind == :diag
        Σ = collect((sxx' - n*μ.*μ) ./ (n-1))
    elseif kind == :full
        ci = cholinv((sxx - n*(μ'*μ)) / (n-1))
        Σ = typeof(ci)[ci]
    else
        error("Unknown kind")
    end
    hist = History(@sprintf("Initlialized single Gaussian d=%d kind=%s with %d data points",
                            d, kind, n))
    GMM(ones(T,1), μ, Σ, [hist], n)
end
## Also allow a Vector, :full makes no sense
GMM(x::Vector{T}) where T <: AbstractFloat = GMM(reshape(x, length(x), 1))  # strange idiom...

## constructors based on data or matrix
function GMM(n::Int, x::DataOrMatrix{T}; method::Symbol=:kmeans, kind=:diag,
             nInit::Int=50, nIter::Int=10, nFinal::Int=nIter, sparse=0) where T
    if n < 2
        GMM(x, kind=kind)
    elseif method==:split
        GMM2(n, x, kind=kind, nIter=nIter, nFinal=nFinal, sparse=sparse)
    elseif method==:kmeans
        GMMk(n, x, kind=kind, nInit=nInit, nIter=nIter, sparse=sparse)
    else
        error("Unknown method ", method)
    end
end
## a 1-dimensional Gaussian can be initialized with a vector, skip kind=
GMM(n::Int, x::Vector{T}; method::Symbol=:kmeans, nInit::Int=50, nIter::Int=10, nFinal::Int=nIter, sparse=0) where T = GMM(n, reshape(x, length(x), 1); method=method, kind=:diag, nInit=nInit, nIter=nIter, nFinal=nFinal, sparse=sparse)

## we sometimes end up with pathological gmms
function sanitycheck!(gmm::GMM)
    pathological=NTuple{2}[]
    for i in findall(isnan.(gmm.μ) .| isinf.(gmm.μ))
        gmm.μ[i] = 0
        push!(pathological, CartesianIndices(gmm.μ)[i])
    end
    if kind(gmm) == :diag
        for i in findall(isnan.(gmm.Σ) .| isinf.(gmm.Σ))
            gmm.Σ[i] = 1
            push!(pathological, CartesianIndices(gmm.Σ)[i])
        end
    else
        for (si, s) in enumerate(gmm.Σ)
            for i in findall(isnan.(s) .| isinf.(s))
                s[i] = 1
                push!(pathological, (si, i))
            end
        end
    end
    if (np=length(pathological)) > 0
        mesg = string(np, " pathological elements normalized")
        addhist!(gmm, mesg)
        @warn(mesg)
    end
    pathological
end

## initialize GMM using Clustering.kmeans (which uses a method similar to kmeans++)
function GMMk(n::Int, x::DataOrMatrix{T}; kind=:diag, nInit::Int=50, nIter::Int=10, sparse=0) where T
    nₓ, d = size(x)
    hist = [History(@sprintf("Initializing GMM, %d Gaussians %s covariance %d dimensions using %d data points", n, diag, d, nₓ))]
    @info(last(hist).s)
    ## subsample x to max 1000 points per mean
    nneeded = 1000*n
    if nₓ < nneeded
        if isa(x, Matrix)
            xx = x
        else
            xx = collect(x)             # convert to an array
        end
    else
        if isa(x, Matrix)
            xx = x[sample(1:nₓ, nneeded, replace=false),:]
        else
            ## Data.  Sample an equal amount from every entry in the list x. This reads in
            ## all data, and may require a lot of memory for very long lists.
            yy = Matrix[]
            for y in x
                ny = size(y,1)
                nsample = min(ny, @compat ceil(Integer, nneeded / length(x)))
                push!(yy, y[sample(1:ny, nsample, replace=false),:])
            end
            xx = vcat(yy...)
        end
    end
    #if Logging._root.level ≤ Logging.DEBUG
        loglevel = :iter
    #elseif Logging._root.level ≤ Logging.INFO
    #    loglevel = :final
    #else
    #    loglevel = :none
    #end
    km = Clustering.kmeans(xx'[:,:], n, maxiter=nInit, display = loglevel)
    μ::Matrix{T} = km.centers'
    if kind == :diag
        ## helper that deals with centers with singleton datapoints.
        function variance(i::Int)
            sel = km.assignments .== i
            if length(sel) < 2
                return ones(1,d)
            else
                return var(xx[sel,:],dims=1)
            end
        end
        Σ = convert(Matrix{T},vcat(map(variance, 1:n)...))
    elseif kind == :full
        function cholinvcov(i::Int)
            sel = km.assignments .== i
            if sum(sel) < d
                return cholinv(eye(d))
            else
                return cholinv(cov(xx[sel,:]))
            end
        end
        Σ = convert(FullCov{T},[cholinvcov(i) for i=1:n])
    else
        error("Unknown kind")
    end
    w::Vector{T} = km.counts ./ sum(km.counts)
    nxx = size(xx,1)
    ng = length(w)
    push!(hist, History(string("K-means with ", nxx, " data points using ", km.iterations, " iterations\n", @sprintf("%3.1f data points per parameter",nxx/((d+1)ng)))))
    @info(last(hist).s)
    gmm = GMM(w, μ, Σ, hist, nxx)
    sanitycheck!(gmm)
    em!(gmm, x; nIter=nIter, sparse=sparse)
    gmm
end

## Train a GMM by consecutively splitting all means.  n most be a power of 2
## This kind of initialization is deterministic, but doesn't work particularily well, its seems
## We start with one Gaussian, and consecutively split.
function GMM2(n::Int, x::DataOrMatrix; kind=:diag, nIter::Int=10, nFinal::Int=nIter, sparse=0)
    log2n = round(Int,log2(n))
    2^log2n == n || error("n must be power of 2")
    gmm = GMM(x, kind=kind)
    tll = [avll(gmm,x)]
    @info("0: avll = ", tll[1])
    for i=1:log2n
        gmm = gmmsplit(gmm)
        avll = em!(gmm, x; nIter=i==log2n ? nFinal : nIter, sparse=sparse)
        @info(i, ": avll = ", avll)
        append!(tll, avll)
    end
    @info("Total log likelihood: ", tll)
    gmm
end

## weighted logsumexp
function logsumexpw(x::Matrix, w::Vector)
    y = x .+ log.(w)'
    logsumexp(y, 2)
end

## split a mean according to the covariance matrix
function gmmsplit(μ::Vector{T}, Σ::Matrix{T}, sep=0.2) where T
    tsep::T = sep
    d, v = eigs(Σ, nev=1)
    p1 = tsep * d[1] * v[:,1]                         # first principal component
    μ - p1, μ + p1
end

function gmmsplit(μ::Vector{T}, Σ::Vector{T}, sep=0.2) where T
    tsep::T = sep
    maxi = argmax(Σ)
    p1 = zeros(length(μ))
    p1[maxi] = tsep * Σ[maxi]
    μ - p1, μ + p1
end

## Split a gmm in order to to double the amount of gaussians
function gmmsplit(gmm::GMM{T}; minweight=1e-5, sep=0.2) where T
    tsep::T = sep
    ## In this function i, j, and k all index Gaussians
    maxi = reverse(sortperm(gmm.w))
    offInd = findall(gmm.w .< minweight)
    if (length(offInd)>0)
        @info("Removing Gaussians with no data");
    end
    for i=1:length(offInd)
        gmm.w[maxi[i]] = gmm.w[offInd[i]] = gmm.w[maxi[i]]/2;
        gmm.μ[offInd[i],:] = gmm.μ[maxi[i],:] + tsep * √gmm.Σ[maxi[i],:]
        gmm.μ[maxi[i],:] = gmm.μ[maxi[i],:] - tsep * √gmm.Σ[maxi[i],:]
    end
    gmmkind = kind(gmm)
    n = gmm.n
    d = gmm.d
    w = similar(gmm.w, 2n)
    μ = similar(gmm.μ, 2n, d)
    if gmmkind == :diag
        Σ = similar(gmm.Σ, 2n, d)
    else
        Σ = similar(gmm.Σ, 2n)
    end
    for oi=1:n
        ni = 2oi-1 : 2oi
        w[ni] .= gmm.w[oi]/2
        if gmmkind == :diag
            μ[ni,:] = hcat(gmmsplit(vec(gmm.μ[oi,:]), vec(gmm.Σ[oi,:]), tsep)...)'
            for k=ni
                Σ[k,:] = gmm.Σ[oi,:]    # implicity copy
            end
        elseif gmmkind == :full
            μ[ni,:] = hcat(gmmsplit(vec(gmm.μ[oi,:]), covar(gmm.Σ[oi]), tsep)...)'
            for k=ni
                Σ[k] = copy(gmm.Σ[oi])
            end
        else
            error("Unknown kind")
        end
    end
    hist = vcat(gmm.hist, History(@sprintf("split to %d Gaussians", 2n)))
    GMM(w, μ, Σ, hist, gmm.nx)
end

# This function runs the Expectation Maximization algorithm on the GMM, and returns
# the log-likelihood history, per data frame per dimension
## Note: 0 iterations is allowed, this just computes the average log likelihood
## of the data and stores this in the history.
function em!(gmm::GMM, x::DataOrMatrix; nIter::Int = 10, varfloor::Float64=1e-3, sparse=0, debug=1)
    size(x,2)==gmm.d || error("Inconsistent size gmm and x")
    d = gmm.d                   # dim
    ng = gmm.n                  # n gaussians
    initc = gmm.Σ
    ll = zeros(nIter)
    gmmkind = kind(gmm)

    @logmsg moreInfo "Running $nIter iterations EM on $gmmkind cov GMM with $ng Gaussians in $d dimensions"

    for i=1:nIter
        ## E-step
        nₓ, ll[i], N, F, S = stats(gmm, x, parallel=true)
        ## M-step
        gmm.w = N / nₓ
        gmm.μ = F ./ N
        if gmmkind == :diag
            gmm.Σ = S ./ N - gmm.μ.^2
            ## var flooring
            tooSmall = any(gmm.Σ .< varfloor, dims=2)[:]
            if (any(tooSmall))
                ind = findall(tooSmall)
                @warn("Variances had to be floored ", ind)
                gmm.Σ[ind,:] = initc[ind,:]
            end
        elseif gmmkind == :full
            for k=1:ng
                if N[k] < d
                    @warn(@sprintf("Too low occupancy count %3.1f for Gausian %d", N[k], k))
                else
                    μk = vec(gmm.μ[k,:]) ## v0.5 arraymageddon
                    gmm.Σ[k] = cholinv(S[k] / N[k] - μk * μk')
                end
            end
        else
            error("Unknown kind")
        end
        sanitycheck!(gmm)
        loginfo = @sprintf("iteration %d, average log likelihood %f",
                           i, ll[i] / (nₓ*d))
        addhist!(gmm, loginfo)
    end
    if nIter>0
        ll /= nₓ * d
        finalll = ll[nIter]
    else
        finalll = avll(gmm, x)
        nₓ = size(x,1)
    end
    gmm.nx = nₓ
    addhist!(gmm,@sprintf("EM with %d data points %d iterations avll %f\n%3.1f data points per parameter",nₓ,nIter,finalll,nₓ/nparams(gmm)))
    ll
end

## this function returns the contributions of the individual Gaussians to the LL
## ll_ij = log p(x_i | gauss_j)
## This is a fast implementation of llpg for diagonal covariance GMMs
## It relies on fast matrix multiplication, and takes up more memory
## TODO: do this the way we do in stats(), which is currently more memory-efficient
function llpg(gmm::GMM{GT,DCT}, x::Matrix{T}) where DCT <: DiagCov{GT} where {GT, T}
    RT = promote_type(GT,T)
    ## ng = gmm.n
    (nₓ, d) = size(x)
    prec::Matrix{RT} = 1 ./ gmm.Σ       # ng × d
    mp = gmm.μ .* prec                  # mean*precision, ng × d
    ## note that we add exp(-sm2p/2) later to pxx for numerical stability
    normalization = 0.5 * (d * log(2π) .+ sum(log.(gmm.Σ), dims=2)) # ng × 1
    sm2p = sum(mp .* gmm.μ, dims=2)   # sum over d mean^2*precision, ng × 1
    ## from here on data-dependent calculations
    xx = x.^2                           # nₓ × d
    pxx = sm2p' .+ xx * prec'           # nₓ × ng
    mpx = x * mp'                       # nₓ × ng
    # L = broadcast(*, a', exp(mpx-0.5pxx)) # nₓ × ng, Likelihood per frame per Gaussian
    mpx-0.5pxx .- normalization'
end

## A function we see more often... Λ is in chol(inv(Σ)) form
## compute Δ_i = (x_i - μ)' Λ (x_i - μ)
## Note: the return type of Δ should be the promote_type of x and μ/ciΣ
function xμTΛxμ!(Δ::Matrix, x::Matrix, μ::Vector, ciΣ::UpperTriangular)
    # broadcast!(-, Δ, x, μ)      # size: nₓ × d, add ops: nₓ * d
    (nₓ, d) = size(x)
    @inbounds for j = 1:d
        μj = μ[j]
        for i = 1:nₓ
            Δ[i,j] = x[i,j] - μj
        end
    end
    tmp = Δ*ciΣ' # size: nₓ × d, mult ops nₓ*d^2

    Δ[:,:] .= tmp[:,:]
end

## full covariance version of llpg()
function llpg(gmm::GMM{GT,FCT}, x::Matrix{T}) where FCT <: FullCov{GT} where {GT, T}
    RT = promote_type(GT,T)
    (nₓ, d) = size(x)
    ng = gmm.n
    d==gmm.d || error("Inconsistent size gmm and x")
    ll = Array{RT}(undef, nₓ, ng)
    Δ = Array{RT}(undef, nₓ, d)
    ## Σ's now are inverse choleski's, so logdet becomes -2sum(log(diag))
    normalization = [0.5d*log(2π) - sum(log.(diag((gmm.Σ[k])))) for k=1:ng]
    for k=1:ng
        ## Δ = (x_i - μ_k)' Λ_κ (x_i - m_k)
        xμTΛxμ!(Δ, x, vec(gmm.μ[k,:]), gmm.Σ[k])
        ll[:,k] = -0.5 * sum(abs2,Δ,dims=2) .- normalization[k]
    end
    return ll::Matrix{RT}
end

## Average log-likelihood per data point and per dimension for a given GMM
function avll(gmm::GMM, x::Matrix{T}) where T<:AbstractFloat
    gmm.d == size(x,2) || error("Inconsistent size gmm and x")
    mean(logsumexpw(llpg(gmm, x), gmm.w)) / gmm.d
end

## Data version
function avll(gmm::GMM, d::Data)
    llpf = dmap(x->logsumexpw(llpg(gmm,x), gmm.w), d)
    sum(map(sum, llpf)) / sum(map(length, llpf)) / gmm.d
end

## import Distributions.posterior
## this function returns the posterior for component j: p_ij = p(j | gmm, x_i)
## TODO: This is a slow and memory-intensive implementation.  It is better to
## use the approaches used in stats()
function gmmposterior(gmm::GMM{GT}, x::Matrix{T}) where {GT, T}     # nₓ × ng
    RT = promote_type(GT,T)
    (nₓ, d) = size(x)
    ng = gmm.n
    d == gmm.d || error("Inconsistent size gmm and x")
    ll = llpg(gmm, x)
    logp = ll .+ log.(gmm.w')
    logsump = logsumexp(logp, 2)
    broadcast!(-, logp, logp, logsump)
    exp.(logp)::Matrix{RT}, ll::Matrix{RT}
end


text:
using JSON

@fieldproxy struct DecodedElement
  name::String
  attributes::Dict{String, Any}
  children::Array{DecodedElement, 1}

  DecodedElement() = new("", Dict{String, Any}(), DecodedElement[])
  DecodedElement(name::String, attributes::Dict{String, Any}, children::Array{DecodedElement, 1}) = new(name, attributes, children)
end attributes

function getVarLength(fh::IOBuffer)
  res = 0
  count = 0
  while true
    byte = read(fh, UInt8)
    res += (byte & 127) << (count * 7)
    count += 1
    if (byte >> 7) == 0
      return res
    end
  end
end

function writeVarLength(fh::IOBuffer, n::Integer)
  res = UInt8[]
  while n > 127
    push!(res, n & 127 | 0b10000000)
    n = floor(Int, n / 128)
  end
  push!(res, n)
  write(fh, res)
end

function readString(fh::IOBuffer)
  length = getVarLength(fh)
  res = ""

  for i in 1:length
    b = read(fh, UInt8)
    res *= string(Char(b))
  end
  return res
end

function writeString(fh::IOBuffer, s::String)
  s = [UInt8(c) for c in s]
  writeVarLength(fh, length(s))
  write(fh, s)
end

function readRunLengthEncoded(fh::IOBuffer)
  byteCount = read(fh, Int16)
  data = Array{UInt8, 1}(undef, byteCount)
  parts = Array{String, 1}(undef, div(byteCount, 2))
  partIndex = 1
  readbytes!(fh, data, byteCount)
  for i = 1:2:byteCount
    times, char = data[i], data[i + 1]
    parts[partIndex] = string(Char(char)) ^ times
    partIndex += 1
  end
  return join(parts)
end

look(lookup, fh) = lookup[read(fh, UInt16) + 1]

function decodeValue(type::UInt8, lookup::Array{String, 1}, fh::IOBuffer)
  if type == 0
    return read(fh, Bool)
  elseif type == 1
    return read(fh, UInt8)
  elseif type == 2
    return read(fh, Int16)
  elseif type == 3
    return read(fh, Int32)
  elseif type == 4
    return read(fh, Float32)
  elseif type == 5
    return look(lookup, fh)
  elseif type == 6
    return readString(fh)
  elseif type == 7
    return readRunLengthEncoded(fh)
  end
end

function encodeRunLength(s::String)
  count::UInt8 = 1
  res = UInt8[]
  current::Char = s[1]

  for (i, c) in enumerate(s[2:end])
    if c != current || count == 255
      push!(res, count)
      push!(res, current)

      count = 1
      current = c
    else
      count += 1
    end
  end

  push!(res, count)
  push!(res, current)

  return res
end

function encodeValue(buffer::IOBuffer, key::String, value::Bool, lookup::Dict{String, Int})
  write(buffer, 0x0)
  write(buffer, value)
end

# Number types are UInt8, Int16, Int32, prefered in that order
function encodeValue(buffer::IOBuffer, key::String, value::Integer, lookup::Dict{String, Int})
    if typemin(UInt8) <= value <= typemax(UInt8)
      write(buffer, UInt8(1))
      write(buffer, UInt8(value))
    elseif typemin(Int16) <= value <= typemax(Int16)
      write(buffer, UInt8(2))
      write(buffer, Int16(value))
    elseif typemin(Int32) <= value <= typemax(Int32)
      write(buffer, UInt8(3))
      write(buffer, Int32(value))
    end
end

function encodeValue(buffer::IOBuffer, key::String, value::AbstractFloat, lookup::Dict{String, Int})
  write(buffer, 0x4)
  write(buffer, Float32(value))
end

function encodeValue(buffer::IOBuffer, key::String, value::String, lookup::Dict{String, Int})
  index = get(lookup, value, 0) - 1

  if index < 0
    encodedValue = encodeRunLength(value)
    encodedLength = length(encodedValue)

    if encodedLength < length(value) && encodedLength <= typemax(Int16)
      write(buffer, 0x7)
      write(buffer, Int16(encodedLength))
      write(buffer, encodedValue)

    else
      write(buffer, 0x6)
      writeString(buffer, value)
    end

  else
    write(buffer, 0x5)
    write(buffer, Int16(index))
  end
end

function decodeElement(fh::IOBuffer, lookup::Array{String, 1})
  name = look(lookup, fh)

  attributeCount = read(fh, UInt8)
  attributes = Dict{String, Any}()

  for i in 1:attributeCount
    key = look(lookup, fh)
    type = read(fh, UInt8)

    value = decodeValue(type, lookup, fh)
    attributes[key] = value
  end

  childCount = read(fh, UInt16)
  children = Array{DecodedElement, 1}(undef, childCount)

  for i in 1:childCount
    children[i] = decodeElement(fh, lookup)
  end

  element = DecodedElement(name, attributes, children)

  return element
end

function decodeMap(fn::String, checkHeader::Bool=true)
  buffer = IOBuffer(open(read, fn))
  if checkHeader
    if readString(buffer) != "CELESTE MAP"
      println("Invalid Celeste map file.")
      close(buffer)

      return false
    end
  end
  package = readString(buffer)
  lookupLength = read(buffer, Int16)
  lookup = String[]
  for i = 1:lookupLength
    push!(lookup, readString(buffer))
  end

  res = decodeElement(buffer, lookup)
  res.attributes["package"] = package

  return res
end

function decodeAllMaps(maps::String, output::String)
  mapBins = [f for f in readdir(maps) if isfile(joinpath(maps, f)) && endswith(f, ".bin")]
  for fn in mapBins
    map = decodeMap(joinpath(maps, fn))
    open(joinpath(output, basename(fn) * ".json"), "w") do fh
      write(fh, JSON.json(map, 4))
    end
  end
end

function populateEncodeKeyNames!(d::Dict{String, Any}, seen::Set{String})
  name = d["__name"]
  push!(seen, name)

  for (k, v) in d
    if !startswith(k, "__")
      push!(seen, k)
    end

    if isa(v, String) && k != "innerText"
      push!(seen, v)
    end
  end

  children = get(d, "__children", nothing)

  if children !== nothing
    for child in children
      populateEncodeKeyNames!(child, seen)
    end
  end
end

function getAttributeNames(d::Dict{String, Any})
  attr = Dict{String, Any}()

  for (k, v) in d
    # Attributes starting with _ are magical, and contains data that shouldn't be written directly
    # Attributes with value nothing should not be written either, and is the lack of attribute instead
    if !startswith(k, "_") && v !== nothing
      attr[k] = v
    end
  end

  return attr
end

function encodeValue(buffer::IOBuffer, elements::Array{Dict{String, Any}}, lookup::Dict{String, Int})
  for element in elements
    encodeValue(buffer, element, lookup)
  end
end

function encodeValue(buffer::IOBuffer, element::Dict{String, Any}, lookup::Dict{String, Int})
  attributes = getAttributeNames(element)
  children = get(Array{Dict{String, Any}, 1}, element, "__children")

  write(buffer, UInt16(get(lookup, element["__name"], 0) - 1))
  write(buffer, UInt8(length(keys(attributes))))

  for (attr, value) in attributes
    write(buffer, UInt16(get(lookup, attr, 0) - 1))
    encodeValue(buffer, attr, value, lookup)
  end

  write(buffer, UInt16(length(children)))
  encodeValue(buffer, children, lookup)
end

function encodeMap(map::Dict{String, Any}, outfile::String)
  seen = Set{String}()
  populateEncodeKeyNames!(map, seen)

  lookup = collect(seen)
  lookupDict = Dict{String, Int}(s => i for (i, s) in enumerate(lookup))
  buffer = IOBuffer()

  writeString(buffer, "CELESTE MAP")
  writeString(buffer, map["_package"])
  write(buffer, Int16(length(lookup)))

  for s in lookup
    writeString(buffer, s)
  end

  encodeValue(buffer, map, lookupDict)

  open(outfile, "w") do fh
    write(fh, buffer.data)
  end
end

function attributes(element::DecodedElement)
  return element.attributes
end

function children(element::DecodedElement)
  return element.children
end

function children(element::Nothing)
  return DecodedElement[]
end

function findChildWithName(element::DecodedElement, name::String)
  for child in element.children
    if child.name == name
      return child
    end
  end
end

function findChildWithName(default::Union{Function, Type}, element::DecodedElement, name::String)
  res = findChildWithName(element, name)

  return res === nothing ? default() : res
end

max_stars_repo_name: CelestialCartographers/Maple

max_issues_repo_name: CelestialCartographers/Maple

max_forks_repo_name: CelestialCartographers/Maple


text:
using LinearAlgebra

struct BasicTrustRegion{T <: Real}
    η1:: T
    η2:: T
    γ1:: T
    γ2:: T
end

function BTRDefaults()
    return BasicTrustRegion(0.01,0.9,0.5,0.5)
end

mutable struct BTRState

    iter::Int
    x::Vector
    xcand::Vector
    g::Vector
    step::Vector
    Δ::Float64
    ρ::Float64

    tol::Float64

    trace
    keepTrace::Bool

    function BTRState()
        state = new()
        state.tol = 1e-6
        state.keepTrace = false
        return state
    end
end

function acceptCandidate!(state::BTRState, b::BasicTrustRegion)
    # If the iteration is successful, update the iterate
    if (state.ρ >= b.η1)
        return true
    else
        return false
    end
end

function updateRadius!(state::BTRState, b::BasicTrustRegion)
    if (state.ρ >= b.η2)
        stepnorm = norm(state.step)
        state.Δ = min(1e20,max(4*stepnorm,state.Δ))
    elseif (state.ρ >= b.η1)
        state.Δ *= b.γ2
    else
        state.Δ *= b.γ1
    end
end

function btr(f::Function, g!::Function, H!::Function, Step::Function,
    x0::Vector, state:: BTRState = BTRState(), ApproxH::Bool = false, verbose::Bool = false)

    b = BTRDefaults()
    state.iter = 0
    state.x = x0
    n=length(x0)

    tol2 = state.tol*state.tol

    state.g = zeros(n)
    # A better initialization procedure should be used with quasi-Newton approximations
    # We could rely on some preconditioner.
    H = zeros(n,n)+I

    fx = f(x0)
    g!(x0, state.g)
    state.Δ = 0.1*norm(state.g) # 1.0

    if (ApproxH)
        y = zeros(n)
        gcand = zeros(n)
        # H!(H, y, state.step)
    else
        H!(x0, H)
    end

    nmax = 100000
    if (state.keepTrace)
        state.trace= x0'
    end

    function model(s::Vector, g::Vector, H::Matrix)
        return dot(s, g)+0.5*dot(s, H*s)
    end

    while (dot(state.g,state.g) > tol2 && state.iter < nmax)
        # Compute the step by approximately minimize the model
        state.step = Step(state.g, H, state.Δ)
        state.xcand = state.x+state.step
	println("$(state.iter). $(state.Δ) $(state.step) $(state.g)")

        # Compute the actual reduction over the predicted reduction
        fcand = f(state.xcand)
        state.ρ = (fcand-fx)/(model(state.step, state.g, H))

        if (ApproxH)
            g!(state.xcand, gcand)
            y = gcand-state.g;
            H = H!(H, y, state.step)
        end

        if (acceptCandidate!(state, b))
            state.x = copy(state.xcand)
            if (ApproxH == false)
                g!(state.x, state.g)
                H!(state.x, H)
            else
                state.g = copy(gcand)
            end
            fx = fcand
        end

        if (state.keepTrace)
            state.trace= [state.trace ; state.x']
        end

        updateRadius!(state, b)
        state.iter += 1
    end

    return state
end

function CauchyStep(g::Vector, H::Matrix, Δ::Float64)
    q = dot(g,H*g)
    normg = norm(g)
    if (q <= 0)
        τ = 1.0
    else
        τ = min((normg*normg*normg)/(q*Δ),1.0)
    end
    return -τ*g*Δ/normg
end

function BFGSUpdate(B::Matrix, y::Vector, s::Vector)
    Bs = B*s
    return B - (Bs*Bs')/dot(s, Bs) + (y*y')/dot(s,y)
end

function stopCG(normg::Float64, normg0::Float64, k::Int, kmax::Int, χ::Float64 = 0.1, θ::Float64 = 0.5)
    if ((k == kmax) || (normg <= normg0*min(χ, normg0^θ)))
        return true
    else
        return false
    end
end

function TruncatedCG(g::Vector, H::Matrix, Δ::Float64)
    n = length(g)
    s = zeros(n)

    normg0 = norm(g)
    v = g
    d = -v
    gv = dot(g,v)
    norm2d = gv
    norm2s = 0
    sMd = 0
    k = 0
    Δ2 = Δ*Δ

    while (stopCG(norm(g), normg0, k, n) == false)
        Hd = H*d
        κ = dot(d,Hd)

        # Is the curvature negative in the direction d?
        if (κ <= 0)
            σ = (-sMd+sqrt(sMd*sMd+norm2d*(Δ2-dot(s,s))))/norm2d
            s += σ*d
            break
        end

        α = gv/κ

        # Check is the model minimizer is outside the trust region
        norm2s += α*(2*sMd+α*norm2d)
        if (norm2s >= Δ2)
            σ = (-sMd+sqrt(sMd*sMd+norm2d*(Δ2-dot(s,s))))/norm2d
            s += σ*d
            break
        end

        # The model minimizer is inside the trust region
        s += α*d
        g += α*Hd
        v = g
        newgv = dot(g,v)
        β = newgv/gv
        gv = newgv
        d = -v+β*d
        sMd = β*(sMd+α*norm2d)
        norm2d = gv+β*β*norm2d

        k += 1;
    end

    return s
end

defaultState = BTRState()

max_stars_repo_name: fbastin/optim

max_issues_repo_name: fbastin/optim

max_forks_repo_name: fbastin/optim


text:
module MapTiles

    import Logging, Parameters, ProgressMeter
    import HTTP, ImageMagick, ProtoBuf
    import RecipesBase, GeoInterface

    # include("protobuf/2.1/vector_tile.jl")

    mutable struct BaseMap{T}
        img::Matrix{T}
        zoom::Int
        xmin::Int
        xmax::Int
        ymin::Int
        ymax::Int
        tilesize::Tuple{Int,Int}
    end

    RecipesBase.@recipe function f(basemap::BaseMap)
        szx, szy = basemap.tilesize
        xlim --> (0, szx * (1 + basemap.xmax - basemap.xmin))
        ylim --> (0, szy * (1 + basemap.ymax - basemap.ymin))
        ticks --> nothing
        grid --> false
        aspect_ratio --> 1
        framestyle --> :none
        basemap.img
    end

    include("providers.jl")
    include("utils.jl")

    """
    Fetch map tiles composing a box at a given zoom level, and
    return the assembled image.
    """
    function fetchmap(
            minlon::Real, minlat::Real, maxlon::Real, maxlat::Real, z::Integer=18;
            maxtiles::Int = 16,
            provider::AbstractProvider = OpenStreetMapProvider(variant="standard")
        )
        xmin, ymin, xmax, ymax = tilebox(minlon, minlat, maxlon, maxlat, z)
        xmin, ymin, xmax, ymax = correctbox(xmin, ymin, xmax, ymax, z)
        sx, sy = boxsize(provider, xmin, ymin, xmax, ymax)
        while sx * sy >= min(maxtiles, provider.maxtiles)
            z -= 1
            xmin, ymin, xmax, ymax = tilebox(minlon, minlat, maxlon, maxlat, z)
            xmin, ymin, xmax, ymax = correctbox(xmin, ymin, xmax, ymax, z)
            sx, sy = boxsize(provider, xmin, ymin, xmax, ymax)
        end
        Logging.@info(string("Setting zoom to ", z))
        Logging.@info(string("Converting bounding latlon to tiles: ",
            xmin, ",", ymin, ",", xmax, ",", ymax, " (xmin,ymin,xmax,ymax)"
        ))
        fetchtiles(xmin, ymin, xmax, ymax, z, maxtiles=maxtiles, provider=provider)
    end

    function fetchtiles(
            xmin::Integer, ymin::Integer, xmax::Integer, ymax::Integer, z::Integer;
            maxtiles::Int = 16,
            provider::AbstractProvider = OpenStreetMapProvider(variant="standard")
        )
        sx, sy = boxsize(provider, xmin, ymin, xmax, ymax)
        tmptile = fetchrastertile(provider, xmin, ymin, z) # fetch a tile for metadata
        T = eltype(tmptile)
        tilesizey, tilesizex = size(tmptile)
        Logging.@info(string("Tiles: Matrix{",T,"}(", tilesizey, ",", tilesizex, ")"))
        img = Matrix{T}(undef, sy*tilesizey, sx*tilesizex)
        Logging.@info(string("Requesting ", sx, " x ", sy, " tiles"))
        ProgressMeter.@showprogress for x in xmin:xmax, y in ymin:ymax
            px = tilesizex * (x - xmin); py = tilesizey * (y - ymin)
            img[py .+ (1:tilesizey), px .+ (1:tilesizex)] =
                fetchrastertile(provider, x, y, z)
        end
        BaseMap(img, z,
            min(xmin, xmax), max(xmin, xmax),
            min(ymin, ymax), max(ymin, ymax),
            (tilesizey, tilesizex)
        )
    end

    function project(
            ::Type{GeoInterface.Point},
            basemap::BaseMap,
            geom::GeoInterface.AbstractGeometry
        )
        lon,lat = GeoInterface.coordinates(geom)
        GeoInterface.Point(collect(lonlat2tile(basemap,lon,lat)))
    end

    function project(
            ::Type{GeoInterface.MultiPoint},
            basemap::BaseMap,
            geom::GeoInterface.AbstractGeometry
        )
        GeoInterface.MultiPoint([
            collect(lonlat2tile(basemap,lon,lat))
            for (lon,lat) in GeoInterface.coordinates(geom)
        ])
    end

    function project(
            ::Type{GeoInterface.LineString},
            basemap::BaseMap,
            geom::GeoInterface.AbstractGeometry
        )
        GeoInterface.LineString([
            collect(lonlat2tile(basemap,lon,lat))
            for (lon,lat) in GeoInterface.coordinates(geom)
        ])
    end

    function project(
            ::Type{GeoInterface.MultiLineString},
            basemap::BaseMap,
            geom::GeoInterface.AbstractGeometry
        )
        GeoInterface.MultiLineString([
            [collect(lonlat2tile(basemap,lon,lat)) for (lon,lat) in line]
            for line in GeoInterface.coordinates(geom)
        ])
    end

    function project(
            ::Type{GeoInterface.Polygon},
            basemap::BaseMap,
            geom::GeoInterface.AbstractGeometry
        )
        GeoInterface.Polygon([
            [collect(lonlat2tile(basemap,lon,lat)) for (lon,lat) in ring]
            for ring in GeoInterface.coordinates(geom)
        ])
    end

    function project(
            ::Type{GeoInterface.MultiPolygon},
            basemap::BaseMap,
            geom::GeoInterface.AbstractGeometry
        )
        GeoInterface.MultiPolygon([[
                [collect(lonlat2tile(basemap,lon,lat)) for (lon,lat) in ring]
                for ring in poly
            ]
            for poly in GeoInterface.coordinates(geom)
        ])
    end

    project(basemap::BaseMap, geom::GeoInterface.AbstractPoint) =
        project(GeoInterface.Point, basemap, geom)
    project(basemap::BaseMap, geom::GeoInterface.AbstractMultiPoint) =
        project(GeoInterface.MultiPoint, basemap, geom)
    project(basemap::BaseMap, geom::GeoInterface.AbstractLineString) =
        project(GeoInterface.LineString, basemap, geom)
    project(basemap::BaseMap, geom::GeoInterface.AbstractMultiLineString) =
        project(GeoInterface.MultiLineString, basemap, geom)
    project(basemap::BaseMap, geom::GeoInterface.AbstractPolygon) =
        project(GeoInterface.Polygon, basemap, geom)
    project(basemap::BaseMap, geom::GeoInterface.AbstractMultiPolygon) =
        project(GeoInterface.MultiPolygon, basemap, geom)

    function project(basemap::BaseMap, geom::GeoInterface.AbstractGeometry)
        gtype = GeoInterface.geotype(geom)
        if gtype == :Point
            return project(GeoInterface.Point, basemap, geom)
        elseif gtype == :MultiPoint
            return project(GeoInterface.MultiPoint, basemap, geom)
        elseif gtype == :LineString
            return project(GeoInterface.LineString, basemap, geom)
        elseif gtype == :MultiLineString
            return project(GeoInterface.MultiLineString, basemap, geom)
        elseif gtype == :Polygon
            return project(GeoInterface.Polygon, basemap, geom)
        else
            @assert gtype == :MultiPolygon
            return project(GeoInterface.MultiPolygon, basemap, geom)
        end
    end

end


text:
eps = 1e-5
# list of losses
binomialLosses = [
    HingeLoss(),
    LogisticLoss(),
    SquaredLoss()
]

multinomialLosses = [
    MultinomialLogisticLoss()
]

fv, y = [2.; 4.; 0.; 40; 40], [-1; -1; 1; 1; -1]
# expected values for f and y
expected_values(::HingeLoss) = [3.0, 5.0, 1.0, 0.0, 41.0]
expected_derivs(::HingeLoss) = [1.0, 1.0, -1.0, 0.0, 1.0]

expected_values(::LogisticLoss) = [2.12693, 4.01815, 0.693147, 0.0, 40.0]
expected_derivs(::LogisticLoss) = [0.88079, 0.98201,-0.5, 0.0, 1.0]
expected_values(::MultinomialLogisticLoss) = expected_values(LogisticLoss())
expected_derivs(::MultinomialLogisticLoss) = [1-0.88079, 1-0.98201,-0.5, 0.0, 1-1.0]

expected_values(::SquaredLoss) = [4.5, 12.5, 0.5, 760.5,840.5]
expected_derivs(::SquaredLoss) = [3.0, 5.0, -1.0, 39.0, 41.0]

for loss in binomialLosses
    print(" - ")
    println(loss)

    # check values
    @test_approx_eq_eps RegERMs.values(loss, fv, y) expected_values(loss) eps
    for i in 1:3
        @test_approx_eq_eps value(loss, fv[i], y[i]) expected_values(loss)[i] eps
    end
    @test_approx_eq_eps tloss(loss, fv, y) sum(expected_values(loss)) eps

    # check derivatives
    @test_approx_eq_eps derivs(loss, fv, y) expected_derivs(loss) eps
    for i in 1:3
        @test_approx_eq_eps deriv(loss, fv[i], y[i]) expected_derivs(loss)[i] eps
    end

    # check values and derivatives
    for i in 1:3
        @test_approx_eq_eps [value_and_deriv(loss, fv[i], y[i])...] [expected_values(loss)[i], expected_derivs(loss)[i]] eps
    end
end

# multinomial version for k=2 should be identical to binomial loss
fv_mul, y_mul = fv'', round(Int, (-y+3)/2)
for loss in multinomialLosses
    loss = multinomialLosses[1]
    print(" - ")
    println(loss)

    # check values
    @test_approx_eq_eps RegERMs.values(loss, fv_mul, y_mul) expected_values(loss) eps
    for i in 1:3
        @test_approx_eq_eps value(loss, vec(fv_mul[i,:]), y_mul[i]) expected_values(loss)[i] eps
    end
    @test_approx_eq_eps tloss(loss, fv_mul, y_mul) sum(expected_values(loss)) eps

    # check derivatives
    @test_approx_eq_eps derivs(loss, fv_mul, y_mul) expected_derivs(loss) eps

end


text:
"""
    timeevolution.schroedinger(tspan, psi0, H; fout)

Integrate Schroedinger equation.

# Arguments
* `tspan`: Vector specifying the points of time for which output should be displayed.
* `psi0`: Initial state vector (can be a bra or a ket).
* `H`: Arbitrary operator specifying the Hamiltonian.
* `fout=nothing`: If given, this function `fout(t, psi)` is called every time
        an output should be displayed. ATTENTION: The state `psi` is neither
        normalized nor permanent! It is still in use by the ode solver and
        therefore must not be changed.
"""
function schroedinger(tspan, psi0::T, H::AbstractOperator{B,B};
                fout::Union{Function,Nothing}=nothing,
                kwargs...) where {B<:Basis,T<:StateVector{B}}
    tspan_ = convert(Vector{Float64}, tspan)
    dschroedinger_(t::Float64, psi::T, dpsi::T) = dschroedinger(psi, H, dpsi)
    x0 = psi0.data
    state = T(psi0.basis, psi0.data)
    dstate = T(psi0.basis, psi0.data)
    integrate(tspan_, dschroedinger_, x0, state, dstate, fout; kwargs...)
end

"""
    timeevolution.schroedinger_dynamic(tspan, psi0, f; fout)

Integrate time-dependent Schroedinger equation.

# Arguments
* `tspan`: Vector specifying the points of time for which output should be displayed.
* `psi0`: Initial state vector (can be a bra or a ket).
* `f`: Function `f(t, psi) -> H` returning the time and or state dependent Hamiltonian.
* `fout=nothing`: If given, this function `fout(t, psi)` is called every time
        an output should be displayed. ATTENTION: The state `psi` is neither
        normalized nor permanent! It is still in use by the ode solver and
        therefore must not be changed.
"""
function schroedinger_dynamic(tspan, psi0::T, f::Function;
                fout::Union{Function,Nothing}=nothing,
                kwargs...) where T<:StateVector
    tspan_ = convert(Vector{Float64}, tspan)
    dschroedinger_(t::Float64, psi::T, dpsi::T) = dschroedinger_dynamic(t, psi, f, dpsi)
    x0 = psi0.data
    state = Ket(psi0.basis, psi0.data)
    dstate = Ket(psi0.basis, psi0.data)
    integrate(tspan_, dschroedinger_, x0, state, dstate, fout; kwargs...)
end

recast!(x::D, psi::StateVector{B,D}) where {B<:Basis, D<:Vector{ComplexF64}} = (psi.data = x);
recast!(psi::StateVector{B,D}, x::D) where {B<:Basis, D<:Vector{ComplexF64}} = nothing

function dschroedinger(psi::Ket{B}, H::AbstractOperator{B,B}, dpsi::Ket{B}) where B<:Basis
    QuantumOpticsBase.gemv!(complex(0,-1.), H, psi, complex(0.), dpsi)
    return dpsi
end

function dschroedinger(psi::Bra{B}, H::AbstractOperator{B,B}, dpsi::Bra{B}) where B<:Basis
    QuantumOpticsBase.gemv!(complex(0,1.), psi, H, complex(0.), dpsi)
    return dpsi
end

function dschroedinger_dynamic(t::Float64, psi0::T, f::Function, dpsi::T) where T<:StateVector
    H = f(t, psi0)
    dschroedinger(psi0, H, dpsi)
end

function check_schroedinger(psi::Ket, H::AbstractOperator)
    check_multiplicable(H, psi)
    check_samebases(H)
end

function check_schroedinger(psi::Bra, H::AbstractOperator)
    check_multiplicable(psi, H)
    check_samebases(H)
end


text:
@testset "Examples" begin
    using Markdown: @md_str

    @testset "Tutorials" begin
        include("examples/quicktutorial.jl")
        include("examples/advancedtutorial.jl")
    end

end


text:
"""
array_to_image(arr::Array{Float32},arr_permuted::Array{Float32}) -> image (darknet type with pointers)

Convert array to darknet image type, avoiding allocation
"""
function array_to_image(arr::Array{Float32},arr_permuted::Array{Float32})
    if length(size(arr)) == 3
        permutedims!(arr_permuted,arr,[2,1,3])
    else
        permutedims!(arr_permuted,arr,[2,1])
    end
    w = size(arr_permuted,1)
    h = size(arr_permuted,2)
    c = size(arr_permuted,3)
    return Image(w,h,c,arr_permuted)
end

"""
array_to_image(arr::Array{Float32}) -> image (darknet type with pointers)

Convert array to darknet image type
"""
function array_to_image(arr::Array{Float32})
    if length(size(arr)) == 3
        arr_permuted = permutedims(arr,[3,2,1])
    else
        arr_permuted = permutedims(arr,[2,1])
    end
    w = size(arr_permuted,1)
    h = size(arr_permuted,2)
    c = size(arr_permuted,3)
    return Image(w,h,c,arr_permuted)
end


text:
include("GB13.jl")
using DelimitedFiles
import GLM: fit, predict, LinearModel
using Distributions,SpecialFunctions
using LinearAlgebra, MultivariateStats
using StatsBase, Random, Distributed
using DelimitedFiles, DataStructures
using CSV
using DataFrames

rng = Random.seed!(2019)

gbdt = GB13.GBDT(;
  sampling_rate = 0.75,                # Sampling rate
  learning_rate = 0.1,                 # Learning rate
  num_iterations = 100,                # NuGBer of iterations
  tree_options = Dict(
      :nsubfeatures => 0,
      :min_samples_leaf => 1,
      :max_depth => 5))
gbl = GB13.GBLearner(gbdt, :regression)

x, y = GB13.test_data(500; p = 10, sigma = sqrt(10))
x_test, y_test = GB13.test_data(500; p = 10, sigma = sqrt(10.0))
mu = GB13.fried(x)
mu_test = GB13.fried(x_test)

hypers = GB13.Hypers(x,y,1,1,0.8)
hypers.σ = sqrt(1)
hypers.τ = 3 / 10 * var(y) / gbdt.num_iterations
hypers.α = 0.95
hypers.s = hypers.α .* ones(size(x, 2)) / size(x, 2)
#hypers.varcount = fill(0, size(hypers.s, 1))

hypers
# test the tree part
mytree    = GB13.build_tree(
    y            ,    # y vector
    x ,    # X matrix
    hypers,
    0,      # n_subfeatures
    5,      # max_depth
    1,      # min_samples_leaf
    2,      # min_samples_split
    0.)

GB13.print_tree(mytree)

root, indX = GB13._fit(
    x,
    y,
    fill(1.0, size(x, 1)),
    0,
    5,
    1,
    2,
    0.0,
    hypers,
    rng) # the results of the tree and the varcount match;
            # the varcount stores the splitting counting number in one tree

mymodel=GB13.fit!(gbl, x, y, hypers)
# get the fitted value
myfit  = GB13.predict!(gbl, x)

# get the residual sum of squares
sqrt(mean(y .- myfit) .^2) # 0.0103

# get prediction
mypred = GB13.predict!(gbl, x_test)

# get mse and root of mean squared error
sqrt(mean((y_test .- mypred ) .^2)) #3.8

sqrt(mean((mypred .- mu_test ) .^2)) #2.0
# 把公式25换了之后，rmse2 for p = 1000 is 2.548, which is lower than 3, better!!!

max_stars_repo_name: YinpuLi/SparsityBoosting

max_issues_repo_name: YinpuLi/SparsityBoosting

max_forks_repo_name: YinpuLi/SparsityBoosting


text:
# This file was generated, do not modify it. # hide
# And keep only the corresponding features values.
y = collect(skipmissing(y))
X = X[no_miss, :]

# Let's now split our dataset into a train and test sets.
train, test = partition(eachindex(y), 0.5, shuffle=true, rng=424);


text:
using Plots
pyplot()

push!(LOAD_PATH, "../")
push!(LOAD_PATH, "../../../../../myJLmodules/LinAlg_C")
using HeavyChain

#some parameters
xmin = -0.2
xmax = 3.8
dt = 1/250
all_t = 0:dt:30
all_u = [NaN for i = 1:length(all_t)]
massmat = zeros(21, 21)
fvec = zeros(21)

#create chain
chain = create_chain()

#define input u(t)
#u_in(t) = mod(t, 3)>1.0 ? 1.0:-1.0

#simulate and animate
anim = Animation()
iter=1
u_in = 1.0
for t = all_t
  #take frame
  if mod(t, 0.04)<dt*0.5 || mod(t, 0.04)>(0.04-dt*0.5)
    println("Frame at t = $(t)")
    l = Plots.@layout [a{0.7h}; b]
    fig = plot(layout = l, size = (1280, 720))
    heavychain_plot!(fig[1], chain, xmin, xmax, t)
    plot!(fig[2], all_t, all_u, lab = "u")
    frame(anim)
  end

  #simulate one step
  #if chain.q[1]>0.2
  #  u_in = -(chain.q[1]+0.7)^4
  #elseif chain.q[1]<-0.2
  #  u_in = (chain.q[1]-0.7)^4
  #end
  if t<0.1
    u_in = 10.0
  else
    u_in = 0.0
  end

  @time simulate!(chain, u_in, dt, massmat, fvec)
  all_u[iter] = u_in
  iter+=1
end
gif(anim, "animation.mp4", fps = round(Int, 1/0.04))

max_stars_repo_name: NikonPic/REINFORCEMENT-JULIA

max_issues_repo_name: NikonPic/REINFORCEMENT-JULIA

max_forks_repo_name: NikonPic/REINFORCEMENT-JULIA


text:
# This file was generated, do not modify it. # hide
function VtoW(V)
    # Makes ones on the diagonal
    W = V / Diagonal(diag(V))

    # Gaussian elimination to clear the top
    for editcol in 1:k
        for refcol in (editcol + 1):k
            m = -W[refcol, editcol]
            for i in refcol:n
                W[i, editcol] += m * W[i, refcol]
            end
        end
    end
    return W
end

max_stars_repo_name: cscherrer/InformativePrior

max_issues_repo_name: cscherrer/InformativePrior

max_forks_repo_name: cscherrer/InformativePrior


text:
using Flux, Flux.Data.MNIST, Statistics
using Flux: throttle, params
using Flux: @epochs, mse, onehotbatch, argmax, crossentropy
using Base.Iterators: repeated, partition
using Plots
using Colors
using Images

function generatedata_circle(r1, r2, N, σ=0.1)
	φ1 = LinRange(0, 2 * π, N)
	φ2 = LinRange(0, 2 * π, N)
	rx1 = r1 .+ σ * randn(N)
	rx2 = r2 .+ σ * randn(N)
	X1 = [rx1 .* cos.(φ1) rx1 .* sin.(φ1)]
	X2 = [rx2 .* cos.(φ2) rx2 .* sin.(φ2)]
	return X1', X2'
end

X1c, X2c = generatedata_circle(2, 0.5, 100)

X = [X1c X2c]
Y = [zeros(1, size(X1c, 2)) ones(1, size(X2c, 2))]

nHidden = 3

activeFunction = relu

m = Chain(
		Dense(size(X,1), nHidden, activeFunction),
		Dense(nHidden, nHidden, activeFunction),
		Dense(nHidden, 1, activeFunction)
		)

loss(x, y) = mse(m(x), y)
iters = 10000

dataset = repeated((X, Y), iters)

opt = ADAM()
evalcb = () -> @show([loss(X, Y)])

Flux.train!(loss, params(m), dataset, opt; cb = throttle(evalcb, 0.5))

function display_decision_boundaries(X1c, X2c, m, x1range, x2range, τ=0.0)
    D = [m([x1; x2])[1] for x2 in x2range, x1 in x1range]
    heatmap(
			x1range,
			x2range,
			sign.(D .- τ);
			color=:grays,
			xlim = [minimum(x1range),maximum(x1range)],
			ylim = [minimum(x2range),maximum(x2range)],
			)
    scatter!(
			X1c[1, :],
			X1c[2, :],
			color="red",
			label="Class 1",
			aspectratio=:1.0,
			)
    scatter!(
			X2c[1, :],
			X2c[2, :],
			color="blue",
			label="Class 2",
			)
end

x1range = range(-3; stop=3, length=200)
x2range = range(-3; stop=3, length=200)

display_decision_boundaries(X1c, X2c, m, x1range, x2range)
plot!(; title="Loss = $(round(loss(X,Y), digits=4))")

@show m.layers[1].W
@show m.layers[1].b
@show m.layers[1].σ;

max_stars_repo_name: aniketjivani/variational-autoencoders

max_issues_repo_name: aniketjivani/variational-autoencoders

max_forks_repo_name: aniketjivani/variational-autoencoders


text:
using Test
using LinearAlgebra
using PolynomialBasis
using ImplicitDomainQuadrature
# using Revise
using CutCell
include("useful_routines.jl")

function exact_linear_solution(x, e11, e22)
    return [x[1] * e11, x[2] * e22]
end

function quadratic_displacement(x)
    u1 = x[1]^2 + 2 * x[1] * x[2]
    u2 = x[2]^2 + 3x[1]
    return [u1, u2]
end

function quadratic_body_force(lambda, mu)
    b1 = -2 * (lambda + 2mu)
    b2 = -(4lambda + 6mu)
    return [b1, b2]
end

function test_full_quadratic_displacement_bc()
    polyorder = 2
    numqp = 3
    nelmts = 11
    L = 2.0
    W = 1.0

    lambda, mu = 1.0, 2.0
    penalty = 1e1

    dx = 0.1
    e11 = dx / L
    e22 = -lambda / (lambda + 2mu) * e11
    dy = e22

    stiffness = CutCell.HookeStiffness(lambda, mu, lambda, mu)

    basis = TensorProductBasis(2, polyorder)
    levelset = InterpolatingPolynomial(1, basis)
    nf = CutCell.number_of_basis_functions(basis)
    mesh = CutCell.Mesh([0.0, 0.0], [L, W], [nelmts, nelmts], nf)

    normal = [1.0, 0.0]
    x0 = [1.0, 0.0]
    levelsetcoeffs =
        CutCell.levelset_coefficients(x -> plane_distance_function(x, normal, x0), mesh)

    cutmesh = CutCell.CutMesh(levelset, levelsetcoeffs, mesh)
    cellquads = CutCell.CellQuadratures(levelset, levelsetcoeffs, cutmesh, numqp)
    interfacequads = CutCell.InterfaceQuadratures(levelset, levelsetcoeffs, cutmesh, numqp)
    facequads = CutCell.FaceQuadratures(levelset, levelsetcoeffs, cutmesh, numqp)

    bilinearforms = CutCell.BilinearForms(basis, cellquads, stiffness, cutmesh)
    interfacecondition =
        CutCell.coherent_interface_condition(basis, interfacequads, stiffness, cutmesh, penalty)

    onbottomboundary(x) = x[2] ≈ 0.0 ? true : false
    onrightboundary(x) = x[1] ≈ L ? true : false
    ontopboundary(x) = x[2] ≈ W ? true : false
    onleftboundary(x) = x[1] ≈ 0.0 ? true : false
    onboundary(x) =
        onbottomboundary(x) || onrightboundary(x) || ontopboundary(x) || onleftboundary(x)

    displacementbc = CutCell.DisplacementCondition(
        x -> quadratic_displacement(x),
        basis,
        facequads,
        stiffness,
        cutmesh,
        onboundary,
        penalty,
    )

    sysmatrix = CutCell.SystemMatrix()
    sysrhs = CutCell.SystemRHS()

    CutCell.assemble_bilinear_form!(sysmatrix, bilinearforms, cutmesh)
    CutCell.assemble_interface_condition!(sysmatrix, interfacecondition, cutmesh)
    CutCell.assemble_body_force_linear_form!(
        sysrhs,
        x -> quadratic_body_force(lambda, mu),
        basis,
        cellquads,
        cutmesh,
    )
    CutCell.assemble_penalty_displacement_bc!(sysmatrix, sysrhs, displacementbc, cutmesh)

    matrix = CutCell.make_sparse(sysmatrix, cutmesh)
    rhs = CutCell.rhs(sysrhs, cutmesh)

    sol = matrix \ rhs
    disp = reshape(sol, 2, :)

    err = mesh_L2_error(disp, x -> quadratic_displacement(x), basis, cellquads, cutmesh)

    @test isapprox(norm(err), 0.0, atol = 1e-13)
end

test_full_quadratic_displacement_bc()