text:
"""
    RegressionTable

Holds regression coefficients and std errors.
The order is determined at construction.
"""
struct RegressionTable
    d :: Vector{RegressorInfo}
end

## -----------  RegressionTable

"""
	RegressionTable()

Initialize empty table
"""
function RegressionTable()
    return RegressionTable(Vector{RegressorInfo}());
end

"""
	RegressionTable(nameV, coeffV, seV)

Initialize using vectors of names, coefficients, and std errors.
"""
function RegressionTable(nameV :: Vector{Symbol}, coeffV :: Vector{Float64}, seV :: Vector{Float64})
    rt = RegressionTable();
    for i1 = 1 : length(nameV)
        add_regressor(rt, nameV[i1], coeffV[i1], seV[i1]);
    end
    return rt
end

"""
	$(SIGNATURES)

Construct RegressionTable from `LinearModel`.

Renames the intercept into :constant.

Renames categorical regressors from "school: 3" to :school3

# Arguments
- `lm`: Output from `fit()`
- `interceptName`: new name of intercept
- `replaceNan`: replace NaN values of coefficients and std errors? This can be useful to deal with regressions that were, say, rank deficient. Coefficients are set to 0.0 and std errors are set to 1.0.
"""
function RegressionTable(lm :: StatsModels.TableRegressionModel;
    interceptName :: Symbol = :constant,
    replaceNan :: Bool = false)

    # Names are strings in GLM
    nameV = coefnames(lm);
    nameV[findfirst(nameV .== "(Intercept)")] = String(interceptName);
    # Normalize categorical variable names
    for i1 = 1 : length(nameV)
        nameV[i1] = replace(nameV[i1], ": " => "");
    end

    coeffV = coef(lm);
    seV = stderror(lm);
    if replaceNan
        coeffV[isnan.(coeffV)] .= 0.0;
        seV[isnan.(seV)] .= 1.0;
    end
    return RegressionTable(Symbol.(nameV), coeffV, seV)
end

## ----------  Modification

"""
	$(SIGNATURES)

Add a regressor that does not already exist.
"""
function add_regressor(rt :: RegressionTable, name :: Symbol, coeff :: Float64, se :: Float64)
    @assert !has_regressor(rt, name)  "Regressor $name exists"
    ri = RegressorInfo(name, coeff, se);
    validate_regressor(ri);
    push!(rt.d, ri);
    return nothing
end

function add_regressor(rt :: RegressionTable, ri :: RegressorInfo)
    @assert !has_regressor(rt, ri.name)  "Regressor $(ri.name) exists"
    validate_regressor(ri);
    push!(rt.d, ri);
    return nothing
end

"""
	$(SIGNATURES)

Drop regressors by name. Option to ignore missing regressors instead of throwing an error.
"""
function drop_regressor!(rt :: RegressionTable, name :: Symbol;
    errorOnMissing :: Bool = true)
    idx = get_regressor_index(rt, name);
    if !isnothing(idx)
        deleteat!(rt.d, idx);
    elseif errorOnMissing
        error("Regressor $name does not exist");
    end
    return nothing
end

function drop_regressors!(rt :: RegressionTable, nameV :: Vector{Symbol};
    errorOnMissing :: Bool = true)
    for name in nameV
        drop_regressor!(rt, name; errorOnMissing = errorOnMissing);
    end
end

"""
	$(SIGNATURES)

Change regressor.
"""
function change_regressor!(rt :: RegressionTable, ri :: RegressorInfo)
    validate_regressor(ri);
    idx = get_regressor_index(rt, ri.name);
    @assert !isnothing(idx)  "Regressor $(ri.name) not found"
    rt.d[idx] = ri;
    return nothing
end

"""
	$(SIGNATURES)

Rename a regressor. Errors if `oldName` does not exist.
"""
function rename_regressor(rt :: RegressionTable, oldName :: Symbol, newName :: Symbol)
    @assert !has_regressor(rt, newName)

    idx = get_regressor_index(rt, oldName);
    @assert !isnothing(idx)
    rt.d[idx].name = newName;
    return nothing
end

"""
	$(SIGNATURES)

Set missing regressors to 0. Useful for cases where dummies have no values.

Does not ensure both regressions have the same variable ordering.
"""
function set_missing_regressors!(rt :: RegressionTable, nameV :: Vector{Symbol})
    for name in nameV
        if !has_regressor(rt, name)
            add_regressor(rt, name, 0.0, 1.0);
        end
    end
    return nothing
end

## -----------  Retrieval

function n_regressors(rt :: RegressionTable)
    return length(rt.d)
end

"""
	$(SIGNATURES)

Does a regressor name exist in a `RegressionTable`?
"""
function has_regressor(rt :: RegressionTable, name :: Symbol)
    return !isnothing(get_regressor_index(rt, name))
end

"""
	get_regressor(rt, name)

Retrieve a [`RegressorInfo`](@ref) object.
"""
function get_regressor(rt :: RegressionTable, name :: Symbol)
    idx = get_regressor_index(rt, name);
    @assert !isnothing(idx)  "Regressor $name not found"
    return rt.d[idx]
end

function get_regressor(rt :: RegressionTable, name :: String)
    return get_regressor(rt, Symbol(name))
end

"""
	$(SIGNATURES)

Get index of regressor by name. Returns `nothing` if not found.
"""
function get_regressor_index(rt :: RegressionTable, name :: Symbol)
    idx = findfirst(x -> x.name == name, rt.d);
    return idx
end

"""
	get_coefficient(rt, name)

Return coefficient
Coefficient name may be Symbol or String
"""
function get_coefficient(rt :: RegressionTable, name)
    ri = get_regressor(rt, name);
    return ri.coeff
end

"""
	$(SIGNATURES)

Retrieve a standard error by name.
"""
function get_std_error(rt :: RegressionTable, name)
    ri = get_regressor(rt, name);
    return ri.se
end

"""
	get_coeff_se(rt, name)

Return coefficient and std error as tuple.  `name` can be Symbol or String.
"""
function get_coeff_se(rt :: RegressionTable, name)
    ri = get_regressor(rt, name);
    return ri.coeff, ri.se
end

"""
	get_coeff_se_multiple(rt, names)

Return multiple coefficients and std errors. `names` can be Symbol or String.
"""
function get_coeff_se_multiple(rt :: RegressionTable,  names :: Vector)
    n = length(names);
    coeffV = Vector{Float64}(undef, n);
    seV = Vector{Float64}(undef, n);
    for i1 = 1 : n
        coeffV[i1], seV[i1] = get_coeff_se(rt, names[i1]);
    end
    return coeffV, seV
end

"""
	get_all_coeff_se(rt)

Return all coefficients and std errors.
"""
function get_all_coeff_se(rt :: RegressionTable)
    nameV = get_names(rt);
    coeffV, seV = get_coeff_se_multiple(rt, nameV);
    return nameV, coeffV, seV
end

"""
	$(SIGNATURES)

Get regressor names.
"""
function get_names(rt :: RegressionTable)
    nameV = [rt.d[idx].name  for idx in 1 : length(rt.d)];
    return nameV
end

function get_name_strings(rt :: RegressionTable)
    return string.(get_names(rt));
end

"""
	$(SIGNATURES)

Make table where columns are regressor names, coefficients, std errors.
"""
function make_table(rt)
    if n_regressors(rt) < 1
        dataM = Matrix{Any}();
    else
        nameV, coeffV, seV = get_all_coeff_se(rt);
        nameV = string.(nameV);
        dataM = hcat(nameV, coeffV, seV)
    end
    return dataM :: Matrix
end

## ----------  Comparison

"""
	$(SIGNATURES)

Checks whether all regression coefficients and std errors are approximately the same.
"""
function isapprox(rt1 :: RegressionTable, rt2 :: RegressionTable;
    atol :: Float64 = 1e-6,  rtol :: Float64 = 1e-6)

    assert_same_regressors([rt1, rt2]);
    areEqual = true;
    nameV = get_names(rt1);
    for name in nameV
        if !Base.isapprox(get_coefficient(rt1, name), get_coefficient(rt2, name),
                atol = atol, rtol = rtol)
            areEqual = false;
            break;
        end
        if !Base.isapprox(get_std_error(rt1, name), get_std_error(rt2, name),
                atol = atol, rtol = rtol)
            areEqual = false;
            break;
        end
    end
    return areEqual
end

## --------------  Display

function Base.show(io :: IO, rt :: RegressionTable)
    if n_regressors(rt) < 1
        print(io, "Empty RegressionTable.")
    else
        dataM = make_table(rt);
        pretty_table(io, dataM; header = ["Regressor", "Coefficient", "StdError"]);
    end
    return nothing
end

## ------------  Vectors of RegressionTables

"""
	$(SIGNATURES)

Check whether all regressions have the same regressors.
"""
function have_same_regressors(rtV :: Vector{RegressionTable})
    areSame = true;
    nameV = sort(get_names(rtV[1]));
    for rt in rtV
        if !isequal(nameV, sort(get_names(rt)))
            areSame = false;
            break;
        end
    end
    return areSame
end

"""
	$(SIGNATURES)

Assert that all regressions have the same regressors. Error if not.
"""
function assert_same_regressors(rtV :: Vector{RegressionTable})
    if !have_same_regressors(rtV)
        @warn "RegressionTables have different regressors"
        for rt in rtV
            println(get_names(rt));
        end
        error("Aborted.")
    end
    return nothing
end

"""
	$(SIGNATURES)

Apply a function to all regressors and std errors in a vector of RegressionTables.

All must have the same coefficients.

Use case: Compute the means of all coefficients and std errors across several regressions.

`reduceFct` takes a vector of scalars and returns a scalar. Example: `mean`.
"""
function reduce_regr_tables(rtV :: Vector{RegressionTable}, reduceFct :: Function)
    assert_same_regressors(rtV)
    nameV = get_names(rtV[1]);
    rtOut = RegressionTable();

    n = length(rtV);
    for name in nameV
        ri = reduce_regr_infos([get_regressor(rtV[j], name)  for j = 1 : n], reduceFct);
        add_regressor(rtOut, ri);
    end

    return rtOut
end

"""
	$(SIGNATURES)

Defines the `mean` for a `Vector{RegressionTable}` as a convenience method.
"""
function mean(rtV :: Vector{RegressionTable})
    return reduce_regr_tables(rtV, StatsBase.mean);
end

"""
	$(SIGNATURES)

Defines the `std` for a `Vector{RegressionTable}`
"""
function std(rtV :: Vector{RegressionTable})
    return reduce_regr_tables(rtV, StatsBase.std);
end

# ------------


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

using Behavior: findmissingsteps, ExecutorEngine, suggestmissingsteps

@testset "Suggestions          " begin
    @testset "Find missing steps" begin
        @testset "One step missing; Step is listed as missing in result" begin
            # Arrange
            matcher = FromMacroStepDefinitionMatcher("""
                using Behavior
            """)

            executor = Executor(matcher, QuietRealTimePresenter())

            missinggiven = Given("some step")
            successfulscenario = Scenario("", String[], ScenarioStep[missinggiven])
            feature = Feature(FeatureHeader("", [], []), [successfulscenario])

            # Act
            result = findmissingsteps(executor, feature)

            # Assert
            @test missinggiven in result
        end

        @testset "No step missing; Step is not listed as missing in result" begin
            # Arrange
            matcher = FromMacroStepDefinitionMatcher("""
                using Behavior

                @given("some step") do context end
            """)

            executor = Executor(matcher, QuietRealTimePresenter())

            given = Given("some step")
            successfulscenario = Scenario("", String[], ScenarioStep[given])
            feature = Feature(FeatureHeader("", [], []), [successfulscenario])

            # Act
            result = findmissingsteps(executor, feature)

            # Assert
            @test !(given in result)
        end

        @testset "One step missing, two found; Only missing step is listed" begin
            # Arrange
            matcher = FromMacroStepDefinitionMatcher("""
                using Behavior

                @given("some precondition") do context end
                @when("some action") do context end
            """)

            executor = Executor(matcher, QuietRealTimePresenter())

            steps = [
                Given("some missing step"),
                Given("some precondition"),
                When("some action"),
            ]
            successfulscenario = Scenario("", String[], steps)
            feature = Feature(FeatureHeader("", [], []), [successfulscenario])

            # Act
            result = findmissingsteps(executor, feature)

            # Assert
            @test Given("some missing step") in result
            @test !(Given("some precondition") in result)
            @test !(When("some action") in result)
        end

        @testset "Two scenarios, two missing steps; Missing steps from both scenarios listed" begin
            # Arrange
            matcher = FromMacroStepDefinitionMatcher("""
                using Behavior

                @given("some precondition") do context end
            """)

            executor = Executor(matcher, QuietRealTimePresenter())

            scenario1 = Scenario("1", String[], ScenarioStep[Given("some missing step")])
            scenario2 = Scenario("2", String[], ScenarioStep[Given("some other missing step")])
            feature = Feature(FeatureHeader("", [], []), [scenario1, scenario2])

            # Act
            result = findmissingsteps(executor, feature)

            # Assert
            @test Given("some missing step") in result
            @test Given("some other missing step") in result
        end

        @testset "Two scenarios, one missing step; Step is only listed once" begin
            # Arrange
            matcher = FromMacroStepDefinitionMatcher("""
                using Behavior

                @given("some precondition") do context end
            """)

            executor = Executor(matcher, QuietRealTimePresenter())

            scenario1 = Scenario("1", String[], ScenarioStep[Given("some missing step")])
            scenario2 = Scenario("2", String[], ScenarioStep[Given("some missing step")])
            feature = Feature(FeatureHeader("", [], []), [scenario1, scenario2])

            # Act
            result = findmissingsteps(executor, feature)

            # Assert
            @test result == [Given("some missing step")]
        end

        @testset "Background has a missing step; Missing step is listed" begin
            # Arrange
            matcher = FromMacroStepDefinitionMatcher("""
                using Behavior

                @given("some precondition") do context end
            """)

            executor = Executor(matcher, QuietRealTimePresenter())

            background = Background("", ScenarioStep[Given("some missing step")])
            scenario1 = Scenario("1", String[], ScenarioStep[Given("some precondition")])
            feature = Feature(FeatureHeader("", [], []), background, [scenario1])

            # Act
            result = findmissingsteps(executor, feature)

            # Assert
            @test result == [Given("some missing step")]
        end

        @testset "Two missing steps with different block texts; Step is only listed once" begin
            # Arrange
            matcher = FromMacroStepDefinitionMatcher("""
                using Behavior

                @given("some precondition") do context end
            """)

            executor = Executor(matcher, QuietRealTimePresenter())

            scenario1 = Scenario("1", String[], ScenarioStep[Given("some missing step"; block_text="1")])
            scenario2 = Scenario("2", String[], ScenarioStep[Given("some missing step"; block_text="2")])
            feature = Feature(FeatureHeader("", [], []), [scenario1, scenario2])

            # Act
            result = findmissingsteps(executor, feature)

            # Assert
            @test length(result) == 1
        end
    end

    @testset "Suggestions" begin
        @testset "One missing step; Add step according to suggestion; Step is found" begin
            # Arrange
            matcher = FromMacroStepDefinitionMatcher("""
                using Behavior

                @given("successful step") do context end
            """)
            executor = Executor(matcher, QuietRealTimePresenter())

            scenario1 = Scenario("1", String[], ScenarioStep[Given("missing step")])
            feature = Feature(FeatureHeader("", [], []), [scenario1])

            # Act
            missingstepscode = suggestmissingsteps(executor, feature)

            # Assert
            missingmatcher = FromMacroStepDefinitionMatcher(missingstepscode)
            compositematcher = CompositeStepDefinitionMatcher()
            addmatcher!(compositematcher, matcher)
            addmatcher!(compositematcher, missingmatcher)

            assertexecutor = Executor(compositematcher, QuietRealTimePresenter())

            result = findmissingsteps(assertexecutor, feature)
            @test result == []
        end

        @testset "Many missing steps; Add steps according to suggestion; Steps are found" begin
            # Arrange
            matcher = FromMacroStepDefinitionMatcher("""
                using Behavior

                @given("successful step") do context end
            """)
            executor = Executor(matcher, QuietRealTimePresenter())

            missingsteps = ScenarioStep[
                Given("missing given"),
                When("missing when"),
                Then("missing then"),
            ]
            scenario1 = Scenario("1", String[], missingsteps)
            feature = Feature(FeatureHeader("", [], []), [scenario1])

            # Act
            missingstepscode = suggestmissingsteps(executor, feature)

            # Assert
            missingmatcher = FromMacroStepDefinitionMatcher(missingstepscode)
            compositematcher = CompositeStepDefinitionMatcher()
            addmatcher!(compositematcher, matcher)
            addmatcher!(compositematcher, missingmatcher)

            assertexecutor = Executor(compositematcher, QuietRealTimePresenter())

            result = findmissingsteps(assertexecutor, feature)
            @test result == []
        end

        @testset "Missing step ending with a double-quote; Suggestion works" begin
            # Arrange
            matcher = FromMacroStepDefinitionMatcher("""
                using Behavior

                @given("successful step") do context end
            """)
            executor = Executor(matcher, QuietRealTimePresenter())

            missingsteps = ScenarioStep[
                Given("missing given\""),
            ]
            scenario1 = Scenario("1", String[], missingsteps)
            feature = Feature(FeatureHeader("", [], []), [scenario1])

            # Act
            missingstepscode = suggestmissingsteps(executor, feature)

            # Assert
            missingmatcher = FromMacroStepDefinitionMatcher(missingstepscode)
            compositematcher = CompositeStepDefinitionMatcher()
            addmatcher!(compositematcher, matcher)
            addmatcher!(compositematcher, missingmatcher)

            assertexecutor = Executor(compositematcher, QuietRealTimePresenter())

            result = findmissingsteps(assertexecutor, feature)
            @test result == []
        end

        @testset "One missing step; Add step according to suggestion; Step fails when executed" begin
            # Arrange
            matcher = FromMacroStepDefinitionMatcher("""
                using Behavior
            """)
            executor = Executor(matcher, QuietRealTimePresenter())

            scenario1 = Scenario("1", String[], ScenarioStep[Given("missing step")])
            feature = Feature(FeatureHeader("", [], []), [scenario1])

            # Act
            missingstepscode = suggestmissingsteps(executor, feature)

            # Assert
            missingmatcher = FromMacroStepDefinitionMatcher(missingstepscode)
            compositematcher = CompositeStepDefinitionMatcher()
            addmatcher!(compositematcher, matcher)
            addmatcher!(compositematcher, missingmatcher)

            assertexecutor = Executor(compositematcher, QuietRealTimePresenter())

            featureresult = Behavior.executefeature(assertexecutor, feature)
            scenarioresult = featureresult.scenarioresults[1]
            @test scenarioresult.steps[1] isa Behavior.StepFailed
        end
    end

    @testset "Escaping PCRE metacharacters" begin
        function testsuggestionescaping(steps::AbstractVector{ScenarioStep})
            # Arrange
            matcher = FromMacroStepDefinitionMatcher("""
                using Behavior
            """)
            executor = Executor(matcher, QuietRealTimePresenter())

            scenario1 = Scenario("1", String[], steps)
            feature = Feature(FeatureHeader("", [], []), [scenario1])

            # Act
            missingstepscode = suggestmissingsteps(executor, feature)

            # Assert
            missingmatcher = FromMacroStepDefinitionMatcher(missingstepscode)
            compositematcher = CompositeStepDefinitionMatcher()
            addmatcher!(compositematcher, matcher)
            addmatcher!(compositematcher, missingmatcher)

            assertexecutor = Executor(compositematcher, QuietRealTimePresenter())

            featureresult = Behavior.executefeature(assertexecutor, feature)
            scenarioresult = featureresult.scenarioresults[1]
            @test scenarioresult.steps[1] isa Behavior.StepFailed
        end

        # Check that each PCRE metacharacter is escaped properly.
        # We do this by implementing the suggested step and check that it doesn't
        # throw an unexpected exception and that it can be found. If any metacharacter is
        # unescaped, one of those two things will happen, with at least one exception: the period.
        #
        # Since the step, like
        #   Given some step with (parentheses)
        # will be converted into a regex, we want those parentheses to be
        # escaped, so they are treated as the () themselves, not the regex
        # metacharacter.
        #
        # Note: Since . matches itself we can't use the same test as for everything else,
        # since a step
        #   Given some step with . in it
        # will match regardless if it's escaped or not, this means that we must instead test
        # that it _does not match_
        #   Given some step with x in it
        # which will ensure that the . is escaped.
        for (steps, testdescription) in [
                # Check that $ is escaped properly
                (ScenarioStep[Given("some step \$x")], "\$"),

                # Check ^
                (ScenarioStep[Given("some ^")], "^"),

                # Check ()
                (ScenarioStep[Given("some (and some)")], "parentheses"),

                # Check |
                (ScenarioStep[Given("some (x|y) or")], "pipe"),

                # Check []
                (ScenarioStep[Given("some [or]")], "square brackets"),

                # Check ?
                (ScenarioStep[Given("some question?")], "question mark"),

                # Check *
                (ScenarioStep[Given("some *")], "*"),

                # Check +
                (ScenarioStep[Given("some +")], "+"),

                # Check {}
                (ScenarioStep[Given("some {")], "{"),
                (ScenarioStep[Given("some }")], "}"),
            ]

            @testset "Escaping regular expressions characters: $testdescription" begin
                testsuggestionescaping(steps)
            end
        end
    end

    @testset "Escaping the PCRE metacharacter ." begin
        # Arrange
        matcher = FromMacroStepDefinitionMatcher("""
            using Behavior
        """)
        executor = Executor(matcher, QuietRealTimePresenter())

        steps = ScenarioStep[
            Given("some step with a . in it")
        ]
        scenario1 = Scenario("1", String[], steps)
        feature = Feature(FeatureHeader("", [], []), [scenario1])

        # Act
        missingstepscode = suggestmissingsteps(executor, feature)

        # Assert
        # Ensure that the step
        #   Given some step with a x in it
        # _does not_ have a matching step.
        missingmatcher = FromMacroStepDefinitionMatcher(missingstepscode)
        compositematcher = CompositeStepDefinitionMatcher()
        addmatcher!(compositematcher, matcher)
        addmatcher!(compositematcher, missingmatcher)

        assertexecutor = Executor(compositematcher, QuietRealTimePresenter())

        shouldbemissing = Given("some step with a x in it")
        newscenario = Scenario("1", String[], ScenarioStep[shouldbemissing])
        newfeature = Feature(FeatureHeader("", [], []), [newscenario])
        result = findmissingsteps(assertexecutor, newfeature)

        @test shouldbemissing in result
    end
end

ext: jl


text:
# This file is a part of Julia. License is MIT: http://julialang.org/license

function Base.length(blob::GitBlob)
    return ccall((:git_blob_rawsize, :libgit2), Int64, (Ptr{Void},), blob.ptr)
end

function rawcontent(blob::GitBlob)
    ptr = ccall((:git_blob_rawcontent, :libgit2), Ptr{UInt8}, (Ptr{Void},), blob.ptr)
    copy(unsafe_wrap(Array, ptr, (length(blob),), false))
end

function content(blob::GitBlob)
    s = String(rawcontent(blob))
    isvalid(s) || error("Blob does not contain valid UTF-8 data")
    return s
end

"""
Use a heuristic to guess if a file is binary: searching for NULL bytes and
looking for a reasonable ratio of printable to non-printable characters among
the first 8000 bytes.
"""
function isbinary(blob::GitBlob)
    bin_flag = ccall((:git_blob_is_binary, :libgit2), Cint, (Ptr{Void},), blob.ptr)
    return bin_flag == 1
end

function lookup(repo::GitRepo, oid::GitHash)
    blob_ptr_ptr = Ref{Ptr{Void}}(C_NULL)
    @check ccall((:git_blob_lookup, :libgit2), Cint,
                  (Ptr{Ptr{Void}}, Ptr{Void}, Ref{GitHash}),
                   blob_ptr_ptr, repo.ptr, Ref(oid))
    return GitBlob(blob_ptr_ptr[])
end

"""
    LibGit2.addblob!(repo::GitRepo, path::AbstractString)

Reads the file at `path` and adds it to the object database of `repo` as a loose blob.
Returns the `GitHash` of the resulting blob.
"""
function addblob!(repo::GitRepo, path::AbstractString)
    id_ref = Ref{GitHash}()
    @check ccall((:git_blob_create_fromdisk, :libgit2), Cint,
                 (Ptr{GitHash}, Ptr{Void}, Cstring),
                 id_ref, repo.ptr, path)
    return id_ref[]
end

function Base.show(io::IO, blob::GitBlob)
    if !isbinary(blob)
        conts   = split(content(blob), "\n")
        showlen = max(length(conts), 3)
        println(io, "GitBlob:\nBlob id: ", GitHash(blob), "\nContents:")
        for i in 1:showlen
            println(io, conts[i])
        end
    else
        println(io, "GitBlob:\nBlob id: ", GitHash(blob), "\nContents are binary.")
    end
end


text:
using SharpArithmetic
using Test

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


text:
"""
    shock_detector(Se, deg, S0 = -3.0 * log10(deg), κ = 4.0)

Detect if the solution belongs to a strong discontinuity

_P. O. Persson and J. Peraire. Sub-cell shock capturing for discontinuous Galerkin methods. 44th AIAA Aerospace Sciences Meeting and Exhibit, 2006._

- @arg Se = log10(<(u - û)²>/<u²>), u is the solution based on orthogonal polynomials, and û is the same solution with one lower truncated order
- @arg deg: polynomial degree of freedom
- @arg S0: reference point of Se
- @arg κ: empirical parameter that needs to be chosen sufficiently large so as to obtain a sharp but smooth shock profile
"""
function shock_detector(Se, deg, S0 = -3.0 * log10(deg), κ = 4.0)
    if Se < S0 - κ
        σ = 1.0
    elseif S0 - κ <= Se < S0 + κ
        σ = 0.5 * (1.0 - sin(0.5 * π * (Se - S0) / κ))
    else
        σ = 0.0
    end

    return σ < 0.99 ? true : false
end

"""
    positive_limiter(u::AbstractMatrix{T}, γ, weights, ll, lr) where {T<:AbstractFloat}

Slope limiter to preserve positivity

_R. Vandenhoeck and A. Lani. Implicit high-order flux reconstruction solver for high-speed compressible flows. Computer Physics Communications 242: 1-24, 2019."_

- @arg u: conservative variables with solution points in dim1 and states in dim2
- @arg γ: specific heat ratio
- @arg weights: quadrature weights for computing mean value
- @arg ll&lr: Langrange polynomials at left/right edge
- @arg t0=1.0: minimum limiting slope
"""
function positive_limiter(
    u::AbstractVector{T},
    weights,
    ll,
    lr,
    t0 = 1.0,
) where {T<:AbstractFloat}

    um = sum(u .* weights) / sum(weights)
    ub = [dot(u, ll), dot(u, lr)]

    ϵ = min(1e-13, um)
    θ = min(minimum(ub), minimum(u))

    t = min((um - ϵ) / (um - θ + 1e-8), 1.0)
    @assert 0 < t <= 1 "incorrect range of limiter parameter t"

    for i in axes(u, 1)
        u[i] = t * (u[i] - um) + um
    end

    return nothing

end

function positive_limiter(
    u::AbstractMatrix{T},
    γ,
    weights,
    ll,
    lr,
    t0 = 1.0,
) where {T<:AbstractFloat}

    # mean values
    u_mean = [sum(u[:, j] .* weights) for j in axes(u, 2)]
    t_mean = 1.0 / conserve_prim(u_mean, γ)[end]
    p_mean = 0.5 * u_mean[1] * t_mean

    # boundary values
    ρb = [dot(u[:, 1], ll), dot(u[:, 1], lr)]
    mb = [dot(u[:, 2], ll), dot(u[:, 2], lr)]
    eb = [dot(u[:, 3], ll), dot(u[:, 3], lr)]

    # density corrector
    ϵ = min(1e-13, u_mean[1], p_mean)
    ρ_min = min(minimum(ρb), minimum(u[:, 1])) # density minumum can emerge at both solution and flux points
    t1 = min((u_mean[1] - ϵ) / (u_mean[1] - ρ_min + 1e-8), 1.0)
    @assert 0 < t1 <= 1 "incorrect range of limiter parameter t"

    for i in axes(u, 1)
        u[i, 1] = t1 * (u[i, 1] - u_mean[1]) + u_mean[1]
    end

    # energy corrector
    tj = Float64[]
    for i = 1:2 # flux points
        prim = conserve_prim([ρb[i], mb[i], eb[i]], γ)

        if prim[end] < ϵ
            prob = NonlinearProblem{false}(
                tj_equation,
                1.0,
                ([ρb[i], mb[i], eb[i]], u_mean, γ, ϵ),
            )
            sol = solve(prob, NewtonRaphson(), tol = 1e-9)
            push!(tj, sol.u)
        end
    end
    for i in axes(u, 1) # solution points
        prim = conserve_prim(u[i, :], γ)

        if prim[end] < ϵ
            prob = NonlinearProblem{false}(tj_equation, 1.0, (u[i, :], u_mean, γ, ϵ))
            sol = solve(prob, NewtonRaphson(), tol = 1e-9)
            push!(tj, sol.u)
        end
    end

    if length(tj) > 0
        t2 = minimum(tj, t0)
        for j in axes(u, 2), i in axes(u, 1)
            u[i, j] = t2 * (u[i, j] - u_mean[j]) + u_mean[j]
        end
    end

    return nothing

end

function positive_limiter(
    u::AbstractArray{T,3},
    γ,
    weights,
    ll,
    lr,
    t0 = 1.0,
) where {T<:AbstractFloat}

    # mean values
    u_mean = [sum(u[:, :, j] .* weights) for j in axes(u, 2)]
    t_mean = 1.0 / conserve_prim(u_mean, γ)[end]
    p_mean = 0.5 * u_mean[1] * t_mean

    # boundary values
    ρb = zeros(4, length(ll))
    mxb = zeros(4, length(ll))
    myb = zeros(4, length(ll))
    eb = zeros(4, length(ll))
    for j in axes(ρb, 2)
        ρb[1, j] = dot(u[j, :, 1], ll)
        ρb[2, j] = dot(u[:, j, 1], lr)
        ρb[3, j] = dot(u[j, :, 1], lr)
        ρb[4, j] = dot(u[:, j, 1], ll)
        mxb[1, j] = dot(u[j, :, 2], ll)
        mxb[2, j] = dot(u[:, j, 2], lr)
        mxb[3, j] = dot(u[j, :, 2], lr)
        mxb[4, j] = dot(u[:, j, 2], ll)
        myb[1, j] = dot(u[j, :, 3], ll)
        myb[2, j] = dot(u[:, j, 3], lr)
        myb[3, j] = dot(u[j, :, 3], lr)
        myb[4, j] = dot(u[:, j, 3], ll)
        eb[1, j] = dot(u[j, :, 4], ll)
        eb[2, j] = dot(u[:, j, 4], lr)
        eb[3, j] = dot(u[j, :, 4], lr)
        eb[4, j] = dot(u[:, j, 4], ll)
    end

    # density corrector
    ϵ = min(1e-13, u_mean[1], p_mean)
    ρ_min = min(minimum(ρb), minimum(u[:, :, 1])) # density minumum can emerge at both solution and flux points
    t1 = min((u_mean[1] - ϵ) / (u_mean[1] - ρ_min + 1e-8), 1.0)
    @assert 0 < t1 <= 1 "incorrect range of limiter parameter t"

    for j in axes(u, 2), i in axes(u, 1)
        u[i, j, 1] = t1 * (u[i, j, 1] - u_mean[1]) + u_mean[1]
    end

    # energy corrector
    tj = Float64[]
    for j = 1:length(ll), i = 1:4
        prim = conserve_prim([ρb[i, j], mxb[i, j], myb[i, j], eb[i, j]], γ)

        if prim[end] < ϵ
            prob = NonlinearProblem{false}(
                tj_equation,
                1.0,
                ([ρb[i, j], mxb[i, j], myb[i, j], eb[i, j]], u_mean, γ, ϵ),
            )
            sol = solve(prob, NewtonRaphson(), tol = 1e-9)
            push!(tj, sol.u)
        end
    end
    for j in axes(u, 2), i in axes(u, 1) # solution points
        prim = conserve_prim(u[i, j, :], γ)

        if prim[end] < ϵ
            prob = NonlinearProblem{false}(tj_equation, 1.0, (u[i, j, :], u_mean, γ, ϵ))
            sol = solve(prob, NewtonRaphson(), tol = 1e-9)
            push!(tj, sol.u)
        end
    end

    if length(tj) > 0
        t2 = minimum(tj, t0)
        for k in axes(u, 3), j in axes(u, 2), i in axes(u, 1)
            u[i, j, k] = t2 * (u[i, j, k] - u_mean[k]) + u_mean[k]
        end
    end

    return nothing

end

function tj_equation(t, p)
    ũ, u_mean, γ, ϵ = p

    u_temp = [t * (ũ[i] - u_mean[i]) + u_mean[i] for i in eachindex(u_mean)]
    prim_temp = conserve_prim(u_temp, γ)

    return 0.5 * prim_temp[1] / prim_temp[end] - ϵ
end


text:
#
# sharedarrays.jl --
#
# Management of shared multi-dimensional arrays for the Julia interface to the
# C libraries of TAO, a Toolkit for Adaptive Optics.
#
#------------------------------------------------------------------------------
#
# This file is part of TAO software (https://git-cral.univ-lyon1.fr/tao)
# licensed under the MIT license.
#
# Copyright (C) 2018-2021, Éric Thiébaut.
#

propertynames(arr::SharedArray) =
    (:accesspoint,
     :counter,
     :shmid,
     :lock,
     :owner,
     :size,
     :timestamp1,
     :timestamp2,
     :timestamp3,
     :timestamp4,
     :type,
     )

getattribute(arr::SharedArray, ::Val{:counter}) =
    ccall((:tao_get_shared_array_counter, taolib), Int64,
          (Ptr{AbstractSharedObject},), arr)

setattribute!(arr::SharedArray, ::Val{:counter}, cnt::Integer) =
    ccall((:tao_set_shared_array_counter, taolib), Cvoid,
          (Ptr{AbstractSharedObject}, Int64), arr, cnt)

getattribute(arr::SharedArray, ::Val{:timestamp1}) = get_timestamp(arr, 1)
getattribute(arr::SharedArray, ::Val{:timestamp2}) = get_timestamp(arr, 2)
getattribute(arr::SharedArray, ::Val{:timestamp3}) = get_timestamp(arr, 3)
getattribute(arr::SharedArray, ::Val{:timestamp4}) = get_timestamp(arr, 4)

get_timestamp(arr::SharedArray, idx::Integer) = begin
    ref = Ref{HighResolutionTime}()
    ccall((:tao_get_shared_array_timestamp, taolib), Cvoid,
          (Ptr{AbstractSharedObject}, Cint, Ptr{HighResolutionTime}),
           arr, idx - 1, ref)
    return ref[]
end

setattribute!(arr::SharedArray, key::Val{:timestamp1}, arg::Union{Real,TimeVal}) =
    set_timestamp!(arr, 1, arg)

set_timestamp!(arr::SharedArray, idx::Integer, arg::Union{Real,TimeVal}) =
    set_timestamp!(arr, idx, HighResolutionTime(arg))

set_timestamp!(arr::SharedArray, idx::Integer, t::HighResolutionTime) =
    ccall((:tao_set_shared_array_timestamp, taolib), Cvoid,
          (Ptr{AbstractSharedObject}, Cint, Ptr{HighResolutionTime}),
           obj, idx - 1, Ref(t))

# Private accessors specific to shared arrays.
_get_arr(obj::SharedArray) =
    getfield(obj, :arr)
_set_arr!(obj::SharedArray{T,N}, val::Array{T,N}) where {T,N} =
    setfield!(obj, :arr, val)

# Make a `TaoBindings.SharedArray{T,N}` behaves like an array.  Note that, for
# performance reasons, reading/writing the array contents is done without any
# attempt to lock the object before.  Locking has to be done appropriately when
# such an object is used.
eltype(obj::SharedArray{T,N}) where {T,N} = T
length(obj::SharedArray) = length(_get_arr(obj))
ndims(obj::SharedArray{T,N}) where {T,N} = N
size(obj::SharedArray) = size(_get_arr(obj))
size(obj::SharedArray, d) = size(_get_arr(obj), d)
axes(obj::SharedArray) = axes(_get_arr(obj))
axes(obj::SharedArray, d) = axes(_get_arr(obj), d)
eachindex(obj::SharedArray) = eachindex(_get_arr(obj))
stride(obj::SharedArray, d) = stride(_get_arr(obj), d)
strides(obj::SharedArray) = strides(_get_arr(obj))
firstindex(obj::SharedArray) = 1
@inline firstindex(obj::SharedArray{T,N}, d) where {T,N} =
    ((d % UInt) - 1 < N ? 1 : error("dimension out of range"))
lastindex(obj::SharedArray) = length(_get_arr(obj))
lastindex(obj::SharedArray, d) = size(_get_arr(obj), d)

similar(obj::SharedArray) = similar(_get_arr(obj))
similar(obj::SharedArray, ::Type{T}) where {T} = similar(_get_arr(obj), T)

similar(obj::SharedArray{T}, dims::Integer...) where {T} =
    similar(obj, T, to_size(dims))
similar(obj::SharedArray{T}, dims::Tuple{Integer,Vararg{Integer}}) where {T} =
    similar(obj, T, to_size(dims))
similar(obj::SharedArray{T}, dims::Tuple{Int,Vararg{Int}}) where {T} =
    similar(_get_arr(obj), T, dims)

similar(obj::SharedArray, ::Type{T}, dims::Integer...) where {T} =
    similar(obj, T, to_size(dims))
similar(obj::SharedArray, ::Type{T}, dims::Tuple{Integer,Vararg{Integer}}) where {T} =
    similar(obj, T, to_size(dims))
similar(obj::SharedArray, ::Type{T}, dims::Tuple{Int,Vararg{Int}}) where {T} =
    similar(_get_arr(obj), T, dims)

reshape(obj::SharedArray, dims...) = reshape(_get_arr(obj), dims...)
copy(obj::SharedArray) = copy(_get_arr(obj))
deepcopy(obj::SharedArray) = deepcopy(_get_arr(obj))
fill!(obj::SharedArray, val) = fill!(_get_arr(obj), val)

@inline @propagate_inbounds Base.getindex(A::SharedArray, inds...) =
    getindex(_get_arr(A), inds...)
@inline @propagate_inbounds Base.setindex!(A::SharedArray, val, inds...) =
    (setindex!(_get_arr(A), val, inds...); return A)

IndexStyle(::Type{<:SharedArray}) = IndexLinear()

# Make a `TaoBindings.SharedArray{T,N}` iterable.
iterate(obj::SharedArray) = iterate(_get_arr(obj))
iterate(obj::SharedArray, state) = iterate(_get_arr(obj), state)

"""
    create(TaoBindings.SharedArray{T}, dims...; perms=0o600, owner=...) -> arr

creates a new shared TAO array with element type `T` and dimensions `dims` and
returns an instance attached to it.  Keyword `perms` can be used to grant
access permissions other than having read and write permissions for the creator
only.  Keyword `owner` can be used to specify the name of the owner of the
shared object (its length must be strictly less than
`TaoBindings.SHARED_OWNER_SIZE` and its default value is given by
`TaoBindings.default_owner()`).

    create(TaoBindings.SharedObject, type, size; perms=0o600, owner=...) -> obj

creates a new shared TAO object of given type and size (in bytes) and returns
an instance attached to it.  Keywords `perms` and `owner` have the same meaning
as above.

"""
create(::Type{SharedArray{T}}, dims::Integer...; kwds...) where {T} =
    create(SharedArray{T}, dims; kwds...)
create(::Type{SharedArray{T}}, dims::NTuple{N,Integer}; kwds...) where {T,N} =
    create(SharedArray{T,N}, dims; kwds...)
create(::Type{SharedArray{T,N}}, dims::Integer...; kwds...) where {T,N} =
    create(SharedArray{T,N}, dims; kwds...)
create(::Type{SharedArray{T,N}}, dims::NTuple{N,Integer}; kwds...) where {T,N} =
    create(SharedArray{T,N}, map(Int, dims); kwds...)
function create(::Type{SharedArray{T,N}},
                dims::NTuple{N,Int};
                owner::AbstractString = default_owner(),
                perms::Integer = 0o600) where {T,N}
    length(owner) < SHARED_OWNER_SIZE || error("owner name too long")
    eltype = shared_array_eltype(T)
    ptr = ccall((:tao_create_shared_array, taolib), Ptr{AbstractSharedObject},
                (Cstring, Cenum, Cint, Ptr{Clong}, Cuint),
                owner, eltype, N, Clong[dims...], perms)
    _check(ptr != C_NULL)
   return _wrap(SharedArray{T,N}, ptr, dims)
end

attach(::Type{SharedArray{T}}, shmid::Integer) where {T} =
    attach(SharedArray, shmid) :: SharedArray{T}

attach(::Type{SharedArray{T,N}}, shmid::Integer) where {T,N} =
    attach(SharedArray, shmid) :: SharedArray{T,N}

function attach(::Type{SharedArray}, shmid::Integer)
    ptr = ccall((:tao_attach_shared_array, taolib), Ptr{AbstractSharedObject},
                (ShmId,), shmid)
    _check(ptr != C_NULL)
    eltype = ccall((:tao_get_shared_array_eltype, taolib), Cenum,
                   (Ptr{AbstractSharedObject},), ptr)
    1 ≤ eltype ≤ length(SHARED_ARRAY_ELTYPES) ||
        _detach_and_throw(ptr, "Bad element type")
    N = Int(ccall((:tao_get_shared_array_ndims, taolib), Cint,
                  (Ptr{AbstractSharedObject},), ptr))
    1 ≤ N ≤ MAX_NDIMS ||
        _detach_and_throw(ptr, "Bad number of dimensions")
    dims = Vector{Int}(undef, N)
    for d in 1:N
        dims[d] = ccall((:tao_get_shared_array_dim, taolib), Clong,
                        (Ptr{AbstractSharedObject}, Cint), ptr, d)
        dims[d] ≥ 1 || _detach_and_throw(ptr, "Bad dimension ", d)
    end
    T = SHARED_ARRAY_ELTYPES[eltype]
    return _wrap(SharedArray{T,N}, ptr, (dims...,))
end

function _wrap(::Type{SharedArray{T,N}}, ptr::Ptr{AbstractSharedObject},
               dims::NTuple{N,Int}) where {T,N}
    data = ccall((:tao_get_shared_array_data, taolib), Ptr{T},
                 (Ptr{AbstractSharedObject},), ptr)
    data != C_NULL ||
        _detach_and_throw(ptr, "Bad shared array data address")
    arr = unsafe_wrap(Array, data, dims; own = false)
    obj = SharedArray{T,N}(ptr, arr, UNLOCKED, true)
    return finalizer(_finalize, obj)
end

@noinline _detach_and_throw(ptr::Ptr{AbstractSharedObject}, args...) =
    _detach_and_throw(ptr, string(args...))

function _detach_and_throw(ptr::Ptr{AbstractSharedObject}, msg::String)
    _call_detach(ptr)
    stack = get_error_stack()
    any_errors(stack) && discard_errors(stack)
    error(msg)
end

function detach(obj::SharedArray{T,N}) where {T,N}
    # Detaching a TAO shared array makes the associated Julia array invalid
    # so we replace it with an array of the correct type but with all
    # dimensions equal to zero.
    _set_arr!(obj, Array{T,N}(undef, ntuple(i -> 0, Val(N))))
    _detach(obj, true)
end


text:
# Euler's Totient function, φ(n) [sometimes called the phi function], is used to
# determine the number of positive numbers less than or equal to n which are
# relatively prime to n. For example, as 1, 2, 4, 5, 7, and 8, are all less than
# nine and relatively prime to nine, φ(9)=6.
#
# The number 1 is considered to be relatively prime to every positive number, so
# φ(1)=1.
#
# Interestingly, φ(87109)=79180, and it can be seen that 87109 is a permutation
# of 79180.
#
# Find the value of n, 1 < n < 10^7, for which φ(n) is a permutation of n and
# the ratio n/φ(n) produces a minimum.

using ProjectEulerSolutions

# Brute force approach to cycle through numbers calculating totients
function p070solution_bruteforce(n_max::Integer=100)::Integer
    min_ratio = 100.0
    nmin = 1
    n_start = Integer(floor(n_max * 0.8))
    for n in n_start:n_max
        digs = digits(n)
        tot = digits(totient(n))
        sort!(digs)  # Sort in place to save time / memory alloc
        sort!(tot)
        if digs == tot
            ratio = n / totient(n)
            if ratio < min_ratio
                nmin = n
                min_ratio = ratio
            end
        end
    end

    return nmin
end

# When φ(n) is very close to n, that's when we get the minimum values.  Thus,
# we want to consider numbers that have the fewest factors (1 - 1/f1)*(1 - 1/f2),
# will tend to give smaller ratios than 3 or 4 factors.  Additionally, we want
# the largest factors possible.  So we consider only numbers that have two prime
# factors, each as close to sqrt(10_000_000) as possible.
function p070solution_factors(n_max::Integer=100)::Integer
    root = sqrt(n_max)
    n_start = Integer(floor(root * 0.5))
    n_end = div(n_max, n_start)
    primes = sieve_eratosthenes(n_end, n_start)

    nmin = 1
    min_ratio = 100.0
    for i in 1:div(length(primes), 2)
        for j in i+1:length(primes)
            n = primes[i] * primes[j]
            if n > n_max
                break
            end
            tot = Integer(round(n * (1 - 1 / primes[i]) * (1 - 1 / primes[j])))
            tot_digs = digits(tot)
            n_digs = digits(n)
            sort!(tot_digs)  # Sort in place to save time / memory alloc
            sort!(n_digs)
            if n_digs == tot_digs
                ratio = n / tot
                if ratio < min_ratio
                    min_ratio = ratio
                    nmin = n
                end
            end
        end
    end

    return nmin
end

p070 = Problems.Problem(Dict("Brute force" => p070solution_bruteforce,
                             "Factors" => p070solution_factors))

Problems.benchmark(p070, 10_000_000)

max_stars_repo_name: gnujosh/julia-euler-project

max_issues_repo_name: gnujosh/julia-euler-project

max_forks_repo_name: gnujosh/julia-euler-project


text:
using FlightMechanics.Models

spl_stream = StickPedalsLeverStream(
    ConstantInput(0.5),
    vcat(DoubletInput(0.5, 1, 2), ConstantInput(0.25)),
    vcat(RampInput(0.5, 1, 2), ConstantInput(0.1)),
    ConstantInput(0.9)
    )

controls = get_controls(spl_stream, 0.)

@test isapprox(controls.stick_lon, 0.5)
@test isapprox(controls.stick_lat, 0.25)
@test isapprox(controls.pedals, 0.1)
@test isapprox(controls.thrust_lever, 0.9)


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

"""
    create_outpost(name, site_id)
    create_outpost(name, site_id, params::Dict{String,<:Any})

Creates an Outpost.

# Arguments
- `name`:
- `site_id`:

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"AvailabilityZone"`:
- `"AvailabilityZoneId"`:
- `"Description"`:
- `"Tags"`: The tags to apply to the Outpost.
"""
create_outpost(Name, SiteId; aws_config::AbstractAWSConfig=global_aws_config()) = outposts("POST", "/outposts", Dict{String, Any}("Name"=>Name, "SiteId"=>SiteId); aws_config=aws_config)
create_outpost(Name, SiteId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = outposts("POST", "/outposts", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Name"=>Name, "SiteId"=>SiteId), params)); aws_config=aws_config)

"""
    delete_outpost(outpost_id)
    delete_outpost(outpost_id, params::Dict{String,<:Any})

Deletes the Outpost.

# Arguments
- `outpost_id`:

"""
delete_outpost(OutpostId; aws_config::AbstractAWSConfig=global_aws_config()) = outposts("DELETE", "/outposts/$(OutpostId)"; aws_config=aws_config)
delete_outpost(OutpostId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = outposts("DELETE", "/outposts/$(OutpostId)", params; aws_config=aws_config)

"""
    delete_site(site_id)
    delete_site(site_id, params::Dict{String,<:Any})

Deletes the site.

# Arguments
- `site_id`:

"""
delete_site(SiteId; aws_config::AbstractAWSConfig=global_aws_config()) = outposts("DELETE", "/sites/$(SiteId)"; aws_config=aws_config)
delete_site(SiteId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = outposts("DELETE", "/sites/$(SiteId)", params; aws_config=aws_config)

"""
    get_outpost(outpost_id)
    get_outpost(outpost_id, params::Dict{String,<:Any})

Gets information about the specified Outpost.

# Arguments
- `outpost_id`:

"""
get_outpost(OutpostId; aws_config::AbstractAWSConfig=global_aws_config()) = outposts("GET", "/outposts/$(OutpostId)"; aws_config=aws_config)
get_outpost(OutpostId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = outposts("GET", "/outposts/$(OutpostId)", params; aws_config=aws_config)

"""
    get_outpost_instance_types(outpost_id)
    get_outpost_instance_types(outpost_id, params::Dict{String,<:Any})

Lists the instance types for the specified Outpost.

# Arguments
- `outpost_id`:

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"MaxResults"`:
- `"NextToken"`:
"""
get_outpost_instance_types(OutpostId; aws_config::AbstractAWSConfig=global_aws_config()) = outposts("GET", "/outposts/$(OutpostId)/instanceTypes"; aws_config=aws_config)
get_outpost_instance_types(OutpostId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = outposts("GET", "/outposts/$(OutpostId)/instanceTypes", params; aws_config=aws_config)

"""
    list_outposts()
    list_outposts(params::Dict{String,<:Any})

List the Outposts for your AWS account.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"MaxResults"`:
- `"NextToken"`:
"""
list_outposts(; aws_config::AbstractAWSConfig=global_aws_config()) = outposts("GET", "/outposts"; aws_config=aws_config)
list_outposts(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = outposts("GET", "/outposts", params; aws_config=aws_config)

"""
    list_sites()
    list_sites(params::Dict{String,<:Any})

Lists the sites for the specified AWS account.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"MaxResults"`:
- `"NextToken"`:
"""
list_sites(; aws_config::AbstractAWSConfig=global_aws_config()) = outposts("GET", "/sites"; aws_config=aws_config)
list_sites(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = outposts("GET", "/sites", params; aws_config=aws_config)

"""
    list_tags_for_resource(resource_arn)
    list_tags_for_resource(resource_arn, params::Dict{String,<:Any})

Lists the tags for the specified resource.

# Arguments
- `resource_arn`: The Amazon Resource Name (ARN) of the resource.

"""
list_tags_for_resource(ResourceArn; aws_config::AbstractAWSConfig=global_aws_config()) = outposts("GET", "/tags/$(ResourceArn)"; aws_config=aws_config)
list_tags_for_resource(ResourceArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = outposts("GET", "/tags/$(ResourceArn)", params; aws_config=aws_config)

"""
    tag_resource(resource_arn, tags)
    tag_resource(resource_arn, tags, params::Dict{String,<:Any})

Adds tags to the specified resource.

# Arguments
- `resource_arn`: The Amazon Resource Name (ARN) of the resource.
- `tags`: The tags to add to the resource.

"""
tag_resource(ResourceArn, Tags; aws_config::AbstractAWSConfig=global_aws_config()) = outposts("POST", "/tags/$(ResourceArn)", Dict{String, Any}("Tags"=>Tags); aws_config=aws_config)
tag_resource(ResourceArn, Tags, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = outposts("POST", "/tags/$(ResourceArn)", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Tags"=>Tags), params)); aws_config=aws_config)

"""
    untag_resource(resource_arn, tag_keys)
    untag_resource(resource_arn, tag_keys, params::Dict{String,<:Any})

Removes tags from the specified resource.

# Arguments
- `resource_arn`: The Amazon Resource Name (ARN) of the resource.
- `tag_keys`: The tag keys.

"""
untag_resource(ResourceArn, tagKeys; aws_config::AbstractAWSConfig=global_aws_config()) = outposts("DELETE", "/tags/$(ResourceArn)", Dict{String, Any}("tagKeys"=>tagKeys); aws_config=aws_config)
untag_resource(ResourceArn, tagKeys, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = outposts("DELETE", "/tags/$(ResourceArn)", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("tagKeys"=>tagKeys), params)); aws_config=aws_config)


text:
module OILMMs

using AbstractGPs
using ChainRulesCore
using FillArrays
using KernelFunctions
using LinearAlgebra
using Random

using AbstractGPs: AbstractGP, FiniteGP
using KernelFunctions: MOInput

include("util.jl")
include("oilmm.jl")
include("missing_data.jl")

export OILMM

end # module


text:
module Jennrich
using Manifolds, LinearAlgebra

export jennrich

"""
	jennrich(A, r :: Int)

Compute the rank r canonical polyadic decomposition of A using a pencil-based algorithm
"""
jennrich(A, r :: Int) = jennrich(A, ones(Int, r))

"""
	jennrich(A, L :: AbstractVector{Int})

Compute the (Lᵣ,Lᵣ,1)-BTD of A using a pencil-based algorithm
"""
function jennrich(𝔗 :: AbstractArray{<:Real, 3}, L :: AbstractVector{Int})
	n₁, n₂, n₃ = size(𝔗)
	@assert n₁ ≥ sum(L) && n₂ ≥ sum(L)

	𝔗Tuck = TuckerPoint(𝔗, (sum(L), sum(L), 2))
	𝔊     = 𝔗Tuck.hosvd.core

	evd   = eigen(𝔊[:,:,1] * 𝔊[:,:,2]^-1)
	makeReal!(evd)
	A :: Matrix{eltype(𝔗)} = 𝔗Tuck.hosvd.U[1] * real(evd.vectors)

	B⨀C   = (A \ reshape(𝔗, n₁, :))'
	B     = Matrix{eltype(A)}(undef, n₂, sum(L))
	C     = Matrix{eltype(A)}(undef, n₃, length(L))
	blkInd = cumsum(vcat(1, L))
	for i ∈ 1:length(L)
		# Bᵢ⨀Cᵢ is the concatenation of rank 1 matrices Bᵢ[:,j] ⊗ cᵢ
		# Compute the rank 1 SVD of these matrices (they all have cᵢ as a right singular vector)
		from, to = blkInd[i], blkInd[i+1] - 1
		Bᵢ⨀Cᵢ = B⨀C[:,from:to]
		rk1mtx = reshape(Bᵢ⨀Cᵢ * randn(L[i]), (n₂, n₃))
		C[:,i] = leftSingularVector(rk1mtx', maxiter=2) # right singular vector
		for j = 1:L[i]
			rk1mtx = reshape(Bᵢ⨀Cᵢ[:,j], (n₂, n₃))
			B[:,from-1+j] = rk1mtx * C[:,i]  # left singular vector * singular value
		end
	end
	A, B, C
end

# Compute the dominant left singular vector of A
# This only works well if the second singular value of A is significantly less than the first
function leftSingularVector(A; maxiter=1)
	σv = randn(size(A,2))
	u = normalize(A * σv)
	for i = 1:maxiter - 1
		mul!(σv, A', u)
		normalize!(mul!(u, A, σv))
	end
	u
end

function makeReal!(evd::Union{GeneralizedEigen, Eigen})
	λ, V = evd
	i = firstindex(λ)
	while i ≤ lastindex(λ)
		if imag(λ[i]) ≠ 0
			λ[i+1] = conj(λ[i+1])
			V[:,i] = real.(V[:,i])
			V[:,i+1] = imag.(V[:,i+1])
			i += 1
		end
		i += 1
	end
	evd
end

end # module


text:
# This file is a part of Julia. License is MIT: https://julialang.org/license

#########################
# limitation parameters #
#########################

const MAX_TYPEUNION_LEN = 3
const MAX_TYPE_DEPTH = 8
const MAX_INLINE_CONST_SIZE = 256
const TUPLE_COMPLEXITY_LIMIT_DEPTH = 3

#########################
# limitation heuristics #
#########################

limit_tuple_type(@nospecialize(t), params::Params) = limit_tuple_type_n(t, params.MAX_TUPLETYPE_LEN)

function limit_tuple_type_n(@nospecialize(t), lim::Int)
    if isa(t, UnionAll)
        return UnionAll(t.var, limit_tuple_type_n(t.body, lim))
    end
    p = t.parameters
    n = length(p)
    if n > lim
        tail = reduce(typejoin, Bottom, Any[p[lim:(n-1)]..., unwrapva(p[n])])
        return Tuple{p[1:(lim-1)]..., Vararg{tail}}
    end
    return t
end

# limit the complexity of type `t` to be simpler than the comparison type `compare`
# no new values may be introduced, so the parameter `source` encodes the set of all values already present
# the outermost tuple type is permitted to have up to `allowed_tuplelen` parameters
function limit_type_size(@nospecialize(t), @nospecialize(compare), @nospecialize(source), allowed_tuplelen::Int)
    source = svec(unwrap_unionall(compare), unwrap_unionall(source))
    source[1] === source[2] && (source = svec(source[1]))
    type_more_complex(t, compare, source, 1, TUPLE_COMPLEXITY_LIMIT_DEPTH, allowed_tuplelen) || return t
    r = _limit_type_size(t, compare, source, 1, allowed_tuplelen)
    @assert t <: r
    #@assert r === _limit_type_size(r, t, source) # this monotonicity constraint is slightly stronger than actually required,
      # since we only actually need to demonstrate that repeated application would reaches a fixed point,
      #not that it is already at the fixed point
    return r
end

# try to find `type` somewhere in `comparison` type
# at a minimum nesting depth of `mindepth`
function is_derived_type(@nospecialize(t), @nospecialize(c), mindepth::Int)
    if mindepth > 0
        mindepth -= 1
    end
    if t === c
        return mindepth == 0
    end
    if isa(c, TypeVar)
        # see if it is replacing a TypeVar upper bound with something simpler
        return is_derived_type(t, c.ub, mindepth)
    elseif isa(c, Union)
        # see if it is one of the elements of the union
        return is_derived_type(t, c.a, mindepth + 1) || is_derived_type(t, c.b, mindepth + 1)
    elseif isa(c, UnionAll)
        # see if it is derived from the body
        return is_derived_type(t, c.body, mindepth)
    elseif isa(c, DataType)
        if isa(t, DataType)
            # see if it is one of the supertypes of a parameter
            super = supertype(c)
            while super !== Any
                t === super && return true
                super = supertype(super)
            end
        end
        # see if it was extracted from a type parameter
        cP = c.parameters
        for p in cP
            is_derived_type(t, p, mindepth) && return true
        end
        if isconcretetype(c) && isbits(c)
            # see if it was extracted from a fieldtype
            # however, only look through types that can be inlined
            # to ensure monotonicity of derivation
            # since we know that for immutable, concrete, bits types,
            # the field types must have been constructed prior to the type,
            # it cannot have a reference cycle in the type graph
            cF = c.types
            for f in cF
                is_derived_type(t, f, mindepth) && return true
            end
        end
    end
    return false
end

function is_derived_type_from_any(@nospecialize(t), sources::SimpleVector, mindepth::Int)
    for s in sources
        is_derived_type(t, s, mindepth) && return true
    end
    return false
end

# type vs. comparison or which was derived from source
function _limit_type_size(@nospecialize(t), @nospecialize(c), sources::SimpleVector, depth::Int, allowed_tuplelen::Int)
    if t === c
        return t # quick egal test
    elseif t === Union{}
        return t # easy case
    elseif isa(t, DataType) && isempty(t.parameters)
        return t # fast path: unparameterized are always simple
    elseif isa(unwrap_unionall(t), DataType) && isa(c, Type) && c !== Union{} && c <: t
        return t # t is already wider than the comparison in the type lattice
    elseif is_derived_type_from_any(unwrap_unionall(t), sources, depth)
        return t # t isn't something new
    end
    if isa(t, TypeVar)
        if isa(c, TypeVar)
            if t.ub === c.ub && t.lb === c.lb
                return t
            end
        end
    elseif isa(t, Union)
        if isa(c, Union)
            a = _limit_type_size(t.a, c.a, sources, depth, allowed_tuplelen)
            b = _limit_type_size(t.b, c.b, sources, depth, allowed_tuplelen)
            return Union{a, b}
        end
    elseif isa(t, UnionAll)
        if isa(c, UnionAll)
            tv = t.var
            cv = c.var
            if tv.ub === cv.ub
                if tv.lb === cv.lb
                    return UnionAll(tv, _limit_type_size(t.body, c.body, sources, depth + 1, allowed_tuplelen))
                end
                ub = tv.ub
            else
                ub = _limit_type_size(tv.ub, cv.ub, sources, depth + 1, 0)
            end
            if tv.lb === cv.lb
                lb = tv.lb
            else
                # note: lower bounds need to be widened by making them lower
                lb = Bottom
            end
            v2 = TypeVar(tv.name, lb, ub)
            return UnionAll(v2, _limit_type_size(t{v2}, c{v2}, sources, depth + 1, allowed_tuplelen))
        end
        tbody = _limit_type_size(t.body, c, sources, depth + 1, allowed_tuplelen)
        tbody === t.body && return t
        return UnionAll(t.var, tbody)
    elseif isa(c, UnionAll)
        # peel off non-matching wrapper of comparison
        return _limit_type_size(t, c.body, sources, depth, allowed_tuplelen)
    elseif isa(t, DataType)
        if isa(c, DataType)
            tP = t.parameters
            cP = c.parameters
            if t.name === c.name && !isempty(cP)
                if isvarargtype(t)
                    VaT = _limit_type_size(tP[1], cP[1], sources, depth + 1, 0)
                    N = tP[2]
                    if isa(N, TypeVar) || N === cP[2]
                        return Vararg{VaT, N}
                    end
                    return Vararg{VaT}
                elseif t.name === Tuple.name
                    # for covariant datatypes (Tuple),
                    # apply type-size limit element-wise
                    ltP = length(tP)
                    lcP = length(cP)
                    np = min(ltP, max(lcP, allowed_tuplelen))
                    Q = Any[ tP[i] for i in 1:np ]
                    if ltP > np
                        # combine tp[np:end] into tP[np] using Vararg
                        Q[np] = tuple_tail_elem(Bottom, Any[ tP[i] for i in np:ltP ])
                    end
                    for i = 1:np
                        # now apply limit element-wise to Q
                        # padding out the comparison as needed to allowed_tuplelen elements
                        if i <= lcP
                            cPi = cP[i]
                        elseif isvarargtype(cP[lcP])
                            cPi = cP[lcP]
                        else
                            cPi = Any
                        end
                        Q[i] = _limit_type_size(Q[i], cPi, sources, depth + 1, 0)
                    end
                    return Tuple{Q...}
                end
            elseif isvarargtype(c)
                # Tuple{Vararg{T}} --> Tuple{T} is OK
                return _limit_type_size(t, cP[1], sources, depth, 0)
            end
        end
        if isType(t) # allow taking typeof as Type{...}, but ensure it doesn't start nesting
            tt = unwrap_unionall(t.parameters[1])
            if isa(tt, DataType) && !isType(tt)
                is_derived_type_from_any(tt, sources, depth) && return t
            end
        end
        if isvarargtype(t)
            # never replace Vararg with non-Vararg
            return Vararg
        end
        if allowed_tuplelen < 1 && t.name === Tuple.name
            return Any
        end
        widert = t.name.wrapper
        if !(t <: widert)
            # This can happen when a typevar has bounds too wide for its context, e.g.
            # `Complex{T} where T` is not a subtype of `Complex`. In that case widen even
            # faster to something safe to ensure the result is a supertype of the input.
            return Any
        end
        return widert
    end
    return Any
end

function type_more_complex(@nospecialize(t), @nospecialize(c), sources::SimpleVector, depth::Int, tupledepth::Int, allowed_tuplelen::Int)
    # detect cases where the comparison is trivial
    if t === c
        return false
    elseif t === Union{}
        return false # Bottom is as simple as they come
    elseif isa(t, DataType) && isempty(t.parameters)
        return false # fastpath: unparameterized types are always finite
    elseif tupledepth > 0 && isa(unwrap_unionall(t), DataType) && isa(c, Type) && c !== Union{} && c <: t
        return false # t is already wider than the comparison in the type lattice
    elseif tupledepth > 0 && is_derived_type_from_any(unwrap_unionall(t), sources, depth)
        return false # t isn't something new
    end
    # peel off wrappers
    if isa(c, UnionAll)
        # allow wrapping type with fewer UnionAlls than comparison if in a covariant context
        if !isa(t, UnionAll) && tupledepth == 0
            return true
        end
        t = unwrap_unionall(t)
        c = unwrap_unionall(c)
    end
    # rules for various comparison types
    if isa(c, TypeVar)
        tupledepth = 1 # allow replacing a TypeVar with a concrete value (since we know the UnionAll must be in covariant position)
        if isa(t, TypeVar)
            return !(t.lb === Union{} || t.lb === c.lb) || # simplify lb towards Union{}
                   type_more_complex(t.ub, c.ub, sources, depth + 1, tupledepth, 0)
        end
        c.lb === Union{} || return true
        return type_more_complex(t, c.ub, sources, depth, tupledepth, 0)
    elseif isa(c, Union)
        if isa(t, Union)
            return type_more_complex(t.a, c.a, sources, depth, tupledepth, allowed_tuplelen) ||
                   type_more_complex(t.b, c.b, sources, depth, tupledepth, allowed_tuplelen)
        end
        return type_more_complex(t, c.a, sources, depth, tupledepth, allowed_tuplelen) &&
               type_more_complex(t, c.b, sources, depth, tupledepth, allowed_tuplelen)
    elseif isa(t, Int) && isa(c, Int)
        return t !== 1 # alternatively, could use !(0 <= t < c)
    end
    # base case for data types
    if isa(t, DataType)
        tP = t.parameters
        if isa(c, DataType) && t.name === c.name
            cP = c.parameters
            length(cP) < length(tP) && return true
            ntail = length(cP) - length(tP) # assume parameters were dropped from the tuple head
            # allow creating variation within a nested tuple, but only so deep
            if t.name === Tuple.name && tupledepth > 0
                tupledepth -= 1
            elseif !isvarargtype(t)
                tupledepth = 0
            end
            isgenerator = (t.name.name === :Generator && t.name.module === _topmod(t.name.module))
            for i = 1:length(tP)
                tPi = tP[i]
                cPi = cP[i + ntail]
                if isgenerator
                    let tPi = unwrap_unionall(tPi),
                        cPi = unwrap_unionall(cPi)
                        if isa(tPi, DataType) && isa(cPi, DataType) &&
                                !tPi.abstract && !cPi.abstract &&
                                sym_isless(cPi.name.name, tPi.name.name)
                            # allow collect on (anonymous) Generators to nest, provided that their functions are appropriately ordered
                            # TODO: is there a better way?
                            continue
                        end
                    end
                end
                type_more_complex(tPi, cPi, sources, depth + 1, tupledepth, 0) && return true
            end
            return false
        elseif isvarargtype(c)
            return type_more_complex(t, unwrapva(c), sources, depth, tupledepth, 0)
        end
        if isType(t) # allow taking typeof any source type anywhere as Type{...}, as long as it isn't nesting Type{Type{...}}
            tt = unwrap_unionall(t.parameters[1])
            if isa(tt, DataType) && !isType(tt)
                is_derived_type_from_any(tt, sources, depth) || return true
                return false
            end
        end
    end
    return true
end

function type_too_complex(@nospecialize(t), d::Int)
    if d < 0
        return true
    elseif isa(t, Union)
        return type_too_complex(t.a, d - 1) || type_too_complex(t.b, d - 1)
    elseif isa(t, TypeVar)
        return type_too_complex(t.lb, d - 1) || type_too_complex(t.ub, d - 1)
    elseif isa(t, UnionAll)
        return type_too_complex(t.var, d) || type_too_complex(t.body, d)
    elseif isa(t, DataType)
        for x in (t.parameters)::SimpleVector
            if type_too_complex(x, d - 1)
                return true
            end
        end
    end
    return false
end

max_stars_repo_name: nreigl/julia

max_issues_repo_name: BenChung/Julia-BTI

max_forks_repo_name: BenChung/Julia-BTI


text:
struct Entry
    plottype::PlotFunc
    mappings::Arguments
    attributes::Dict{Symbol, Any}
end

Entry(plottype::PlotFunc=Any, mappings=arguments(); attributes...) =
    Entry(plottype, mappings, Dict{Symbol, Any}(attributes))

Entry(mappings::Arguments; attributes...) = Entry(Any, mappings; attributes...)

function separate!(entry::Entry)
    discrete, _ = separate!(entry.mappings)
    return discrete => entry
end

function recombine!(discrete, entry::Entry)
    return Entry(
        entry.plottype,
        recombine!(discrete, entry.mappings),
        entry.attributes
    )
end

struct Entries
    entries::Vector{Entry}
    scales::Arguments
    labels::Arguments
end

Entries() = Entries(Entry[], arguments(), arguments())

function compute_axes_grid(fig, e::Entries; axis=NamedTuple())

    rowcol = (:row, :col)

    layout_scale, scales... = map((:layout, rowcol...)) do sym
        return get(e.scales, sym, nothing)
    end

    grid_size = map(scales, (first, last)) do scale, f
        isnothing(scale) || return maximum(scale.plot)
        isnothing(layout_scale) || return maximum(f, layout_scale.plot)
        return 1
    end

    axes_grid = map(CartesianIndices(grid_size)) do c
        ax = Axis(fig[Tuple(c)...]; axis...)
        return AxisEntries(ax, Entry[], e.scales, e.labels)
    end

    for entry in e.entries
        rows, cols = map(rowcol, scales, (first, last)) do sym, scale, f
            v = get(entry.mappings, sym, nothing)
            layout_v = get(entry.mappings, :layout, nothing)
            # without layout info, plot on all axes
            # all values in `v` and `layout_v` are equal
            isnothing(v) || return rescale(v[1:1], scale)
            isnothing(layout_v) || return map(f, rescale(layout_v[1:1], layout_scale))
            return 1:f(grid_size)
        end
        for i in rows, j in cols
            ae = axes_grid[i, j]
            push!(ae.entries, entry)
        end
    end

    return axes_grid

end

function AbstractPlotting.plot(entries::Entries; axis=NamedTuple(), figure=NamedTuple())
    fig = Figure(; figure...)
    grid = plot!(fig, entries; axis)
    return FigureGrid(fig, grid)
end

function AbstractPlotting.plot!(fig, entries::Entries; axis=NamedTuple())
    axes_grid = compute_axes_grid(fig, entries; axis)
    foreach(plot!, axes_grid)
    return axes_grid
end

"""
    AxisEntries(axis::Union{Axis, Nothing}, entries::Vector{Entry}, labels, scales)

Define all ingredients to make plots on an axis.
Each scale can be either a `CategoricalScale` (for discrete collections), such as
`CategoricalScale(["a", "b"], ["red", "blue"])`, or a function,
such as `log10`. Other scales may be supported in the future.
"""
struct AxisEntries
    axis::Axis
    entries::Vector{Entry}
    scales::Arguments
    labels::Arguments
end

AbstractPlotting.Axis(ae::AxisEntries) = ae.axis
Entries(ae::AxisEntries) = Entries(ae.entries, ae.labels, ae.scales)

function prefix(i::Int, sym::Symbol)
    var = (:x, :y, :z)[i]
    return Symbol(var, sym)
end

function AbstractPlotting.plot!(ae::AxisEntries)
    axis, entries, labels, scales = ae.axis, ae.entries, ae.labels, ae.scales
    for entry in entries
        plottype, mappings, attributes = entry.plottype, entry.mappings, entry.attributes
        trace = map(unwrap∘rescale, mappings, scales)
        positional, named = trace.positional, trace.named
        merge!(named, attributes)
        for sym in [:col, :row, :layout]
            pop!(named, sym, nothing)
        end
        plot!(plottype, axis, positional...; named...)
    end
    # TODO: support log colorscale
    for i in 1:2
        label, scale = get(labels, i, nothing), get(scales, i, nothing)
        any(isnothing, (label, scale)) && continue
        axislabel, ticks, axisscale = prefix.(i, (:label, :ticks, :scale))
        if scale isa CategoricalScale
            u = map(string, scale.data)
            getproperty(axis, ticks)[] = (axes(u, 1), u)
        end
        getproperty(axis, axislabel)[] = string(label)
    end
    return axis
end

struct FigureGrid
    figure::Figure
    grid::Matrix{AxisEntries}
end

Base.show(io::IO, fg::FigureGrid) = show(io, fg.figure)
Base.show(io::IO, m::MIME, fg::FigureGrid) = show(io, m, fg.figure)
Base.show(io::IO, ::MIME"text/plain", fg::FigureGrid) = print(io, "FigureGrid()")

Base.showable(mime::MIME{M}, fg::FigureGrid) where {M} = showable(mime, fg.figure)

Base.display(fg::FigureGrid) = display(fg.figure)

function FileIO.save(filename::String, fg::FigureGrid; kwargs...)
    return FileIO.save(FileIO.query(filename), fg; kwargs...)
end

function FileIO.save(file::FileIO.Formatted, fg::FigureGrid; kwargs...)
    return FileIO.save(file, fg.figure; kwargs...)
end

to_tuple(fg) = (fg.figure, fg.grid)

Base.iterate(fg::FigureGrid) = iterate(to_tuple(fg))
Base.iterate(fg::FigureGrid, i) = iterate(to_tuple(fg), i)


text:
"""
GenX: An Configurable Capacity Expansion Model
Copyright (C) 2021,  Massachusetts Institute of Technology
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
A complete copy of the GNU General Public License v2 (GPLv2) is available
in LICENSE.txt.  Users uncompressing this from an archive may not have
received this license file.  If not, see <http://www.gnu.org/licenses/>.
"""

function write_power_balance(path::AbstractString, inputs::Dict, setup::Dict, EP::Model)
	dfGen = inputs["dfGen"]
	T = inputs["T"]     # Number of time steps (hours)
	Z = inputs["Z"]     # Number of zones
	SEG = inputs["SEG"] # Number of load curtailment segments
	STOR_ALL = inputs["STOR_ALL"]
	FLEX = inputs["FLEX"]
	## Power balance for each zone
	dfPowerBalance = Array{Any}
	rowoffset=3
	for z in 1:Z
	   	dfTemp1 = Array{Any}(nothing, T+rowoffset, 10)
	   	dfTemp1[1,1:size(dfTemp1,2)] = ["Generation", "Storage_Discharge", "Storage_Charge",
	           "Flexible_Demand_Defer", "Flexible_Demand_Stasify",
	           "Demand_Response", "Nonserved_Energy",
			   "Transmission_NetExport", "Transmission_Losses",
	           "Demand"]
	   	dfTemp1[2,1:size(dfTemp1,2)] = repeat([z],size(dfTemp1,2))
	   	for t in 1:T
	     	dfTemp1[t+rowoffset,1]= sum(value.(EP[:vP][dfGen[(dfGen[!,:THERM].==1) .&  (dfGen[!,:Zone].==z),:][!,:R_ID],t])) +
		 		sum(value.(EP[:vP][dfGen[(dfGen[!,:VRE].==1) .&  (dfGen[!,:Zone].==z),:][!,:R_ID],t])) +
				sum(value.(EP[:vP][dfGen[(dfGen[!,:MUST_RUN].==1) .&  (dfGen[!,:Zone].==z),:][!,:R_ID],t])) +
				sum(value.(EP[:vP][dfGen[(dfGen[!,:HYDRO].>=1) .&  (dfGen[!,:Zone].==z),:][!,:R_ID],t]))
	     	dfTemp1[t+rowoffset,2] = sum(value.(EP[:vP][dfGen[(dfGen[!,:STOR].>=1) .&  (dfGen[!,:Zone].==z),:][!,:R_ID],t]))
	     	dfTemp1[t+rowoffset,3] = 0
	     	if !isempty(intersect(dfGen[dfGen.Zone.==z,:R_ID],STOR_ALL))
	     	    dfTemp1[t+rowoffset,3] = -sum(value.(EP[:vCHARGE][y,t]) for y in intersect(dfGen[dfGen.Zone.==z,:R_ID],STOR_ALL))
	     	end
	     	dfTemp1[t+rowoffset,4] = 0
	     	if !isempty(intersect(dfGen[dfGen.Zone.==z,:R_ID],FLEX))
	     	    dfTemp1[t+rowoffset,4] = sum(value.(EP[:vCHARGE_FLEX][y,t]) for y in intersect(dfGen[dfGen.Zone.==z,:R_ID],FLEX))
	     	end
	     	dfTemp1[t+rowoffset,5] = -sum(value.(EP[:vP][dfGen[(dfGen[!,:FLEX].>=1) .&  (dfGen[!,:Zone].==z),:][!,:R_ID],t]))
	     	if SEG>1
	       		dfTemp1[t+rowoffset,6] = sum(value.(EP[:vNSE][2:SEG,t,z]))
	     	else
	       		dfTemp1[t+rowoffset,6]=0
	     	end
	     	dfTemp1[t+rowoffset,7] = value(EP[:vNSE][1,t,z])
	     	dfTemp1[t+rowoffset,8] = 0
	     	dfTemp1[t+rowoffset,9] = 0
		#=
	     	if setup["NetworkExpansion"] == 1
	     	    dfTemp1[t+rowoffset,8] = value(EP[:ePowerBalanceNetExportFlows][t,z])
	     	    dfTemp1[t+rowoffset,9] = -1/2 * value(EP[:eLosses_By_Zone][z,t])
	     	end
		=#
		if Z>=2
			dfTemp1[t+rowoffset,8] = value(EP[:ePowerBalanceNetExportFlows][t,z])
			dfTemp1[t+rowoffset,9] = -1/2 * value(EP[:eLosses_By_Zone][z,t])
		end
	     	dfTemp1[t+rowoffset,10] = -inputs["pD"][t,z]

			if setup["ParameterScale"] == 1
				dfTemp1[t+rowoffset,1] = dfTemp1[t+rowoffset,1] * ModelScalingFactor
				dfTemp1[t+rowoffset,2] = dfTemp1[t+rowoffset,2] * ModelScalingFactor
				dfTemp1[t+rowoffset,3] = dfTemp1[t+rowoffset,3] * ModelScalingFactor
				dfTemp1[t+rowoffset,4] = dfTemp1[t+rowoffset,4] * ModelScalingFactor
				dfTemp1[t+rowoffset,5] = dfTemp1[t+rowoffset,5] * ModelScalingFactor
				dfTemp1[t+rowoffset,6] = dfTemp1[t+rowoffset,6] * ModelScalingFactor
				dfTemp1[t+rowoffset,7] = dfTemp1[t+rowoffset,7] * ModelScalingFactor
				dfTemp1[t+rowoffset,8] = dfTemp1[t+rowoffset,8] * ModelScalingFactor
				dfTemp1[t+rowoffset,9] = dfTemp1[t+rowoffset,9] * ModelScalingFactor
				dfTemp1[t+rowoffset,10] = dfTemp1[t+rowoffset,10] * ModelScalingFactor
			end
	   	end
		if z==1
			dfPowerBalance =  hcat(vcat(["", "Zone", "AnnualSum"], ["t$t" for t in 1:T]), dfTemp1)
		else
		    dfPowerBalance = hcat(dfPowerBalance, dfTemp1)
		end
	end
	for c in 2:size(dfPowerBalance,2)
	   	dfPowerBalance[rowoffset,c]=sum(inputs["omega"].*dfPowerBalance[(rowoffset+1):size(dfPowerBalance,1),c])
	end
	dfPowerBalance = DataFrame(dfPowerBalance, :auto)
	CSV.write(joinpath(path, "power_balance.csv"), dfPowerBalance, writeheader=false)
end

max_stars_repo_name: Betristor/LTESOM

max_issues_repo_name: Betristor/LTESOM

max_forks_repo_name: Betristor/LTESOM


text:
import NumericExtensions.sumsq

################################################################################
#
#   METROPOLIS can take a full MolecularDynamicsTrial object, or the reduced
#   MDMetropolisTrial object, which is far more space-efficient, since the
#   fields of the latter are a subset of the former.
#
#   Otherwise works much like verlet!(r,n,m,δ), i.e. calculates values for steps
#   n through m on the MDTrial r.
#
#   The Metropolis algorithm itself works as follows:
#       1) Loop through particle positions, creating a series of proposed
#          random moves a distance δ from previous positions
#       2) calculate new particle energy at this position
#       3) calculate
#
################################################################################
function metropolis!( r::MDTrial, n::Int64, m::Int64, δpe::Float64 , δke::Float64)
    # Parameters
    N = r.numBodies
    l = r.L
    oneol = 1/l                             # Use this so much; set it now
    β = 1 / (r.Td)                          # T, E in units of ϵ, so kB cancels
    r.currentStep = n-1

    # Allocations
    A = Array(Float64, 3, N)                # all accepted new positions
    B = Array(Float64, 3, N)                # all accepted new velocities
    P = Array(Float64, 3, N)                # all proposed positions
    V = Array(Float64, 3, N)                # all proposed velocities

    p⃗ = Array(Float64, 3)                   # a proposed position
    o⃗ = Array(Float64, 3)                   # an old position
    v⃗ = Array(Float64, 3)                   # a proposed velocity
    Δp⃗ = Array(Float64, 3, N)               # dist btwn p⃗ and all Y's
    Δo⃗ = Array(Float64, 3, N)               # dist btwn o⃗ and all Y's

    pPE = 0.0                               # proposed PE for a particle
    oPE = 0.0                               # proposed PE for a particle
    pKE = 0.0                               # proposed KE for a particle
    ΔPE = 0.0                               # ΔPE resulting from a proposed step
    ΔKE = 0.0                               # ΔKE resulting from a proposed step

    α = 0.0                                 # prob of switching to higher E
    PEacc = 0.0                             # accepted PE changes per step
    KEacc = 0.0                             # accepted KE changes per step

    R2 = Array(Float64, 1, N)               # sq distances betwn Δp⃗ and Y's
    Rn2 = Array(Float64, 1, N)              # 1./R2
    Rn6 = Array(Float64, 1, N)              # Rn2^3

    # Calculations for each simulation step
    for i in r.currentStep:(m-1)
        PEacc = 0.0
        print("START Metropolis step ",r.currentStep+1,". ")
        A = r.y[:,:,i]
        B = r.v[:,:,i]
        P = A - (2.0rand(3,N) - 1.0)δpe
        V = B - (2.0rand(3,N) - 1.0)δke
        print("Running acc/rej... ")

        # Calculations for each particle
        for j in 1:N

            # POTENTIAL ENERGY ACCEPT/REJECT

            # Handle periodic boundaries, find shortest interparticle Δo⃗
            o⃗ = A[:,j]
            Δo⃗ = o⃗ .- A
            Δo⃗ *= oneol
            Δo⃗ += 0.5
            Δo⃗ = mod(Δo⃗,1)
            Δo⃗ -= 0.5
            Δo⃗ *= l

            # Find squared distances and compute energy
            R2 = sumsq(Δo⃗,1)
            R2[j] = 1                       # avoid blowing up with 1/0
            Rn2 = 1 ./ R2
            Rn2[j] = 0                      # avoid self-interaction
            Rn6 = Rn2 .* Rn2 .* Rn2

            # Find PE of the old position
            oPE = 4.0(sumsq(Rn6,2) - sum(Rn6))

             # Handle periodic boundaries, find shortest interparticle Δp⃗
            p⃗ = P[:,j]
            Δp⃗ = p⃗ .- A
            Δp⃗ *= oneol
            Δp⃗ += 0.5
            Δp⃗ = mod(Δp⃗,1)
            Δp⃗ -= 0.5
            Δp⃗ *= l

            # Find squared distances and compute energy
            R2 = sumsq(Δp⃗,1)
            R2[j] = 1                       # avoid blowing up with 1/0
            Rn2 = 1 ./ R2
            Rn2[j] = 0                      # avoid self-interaction
            Rn6 = Rn2 .* Rn2 .* Rn2

            # Find PE of the proposed position
            pPE = 4.0(sumsq(Rn6,2) - sum(Rn6))

            # Change in PE due to proposed move
            ΔPE = 2.0(pPE - oPE)

            # If the new state has lower energy, accept new position
            @assert length(ΔPE) == 1
            if ΔPE[1] < 0.0
                A[:,j] = p⃗                  # accept new position
                PEacc += 1
            else
                α = exp( -β*ΔPE[1] )
                if α > rand()
                    A[:,j] = p⃗              # accept new position
                    PEacc += 1
                end
            end

        end
        r.y[:,:,i+1] = A                    # accepted values become new r.y
        print("done with PEacc=",PEacc/N,". Find PE and virial... ")
        potentialenergy!(r, i+1)            # get pe, pet, and virial
        r.currentStep += 1
        println("done.")
    end
end

# Run for n more steps
function metropolis!(r::MDTrial, n::Int64, δpe::Float64, δke::Float64)
    start = r.currentStep + 1
    stop = min( r.currentStep + n, r.steps )
    metropolis!( r, start, stop, δpe, δke)
end

# Run till finished
function metropolis!(r::MDTrial, δpe::Float64, δke::Float64)
    start = r.currentStep + 1
    stop = r.steps
    metropolis!( r, start, stop, δpe, δke)
end

metropolis!(r::MDTrial, n::Int64, m::Int64, δ::Float64) = metropolis!(r, n, m, δ, δ)
metropolis!(r::MDTrial, n::Int64, δ::Float64) = metropolis!(r, n, δ, δ)
metropolis!(r::MDTrial, δ::Float64) = metropolis!(r, δ, δ)


text:
using Documenter, JuliaDB, IndexedTables, Dagger, TextParse, Glob

load_dir(x) = map(file -> joinpath("lib", x, file), readdir(joinpath(Base.source_dir(), "src", "lib", x)))

makedocs(
   modules = [JuliaDB, IndexedTables, NamedTuples],
   clean = false,
   format = [:html],#, :latex],
   sitename = "JuliaDB",
   pages = Any[
       "Home" => "index.md",
       "API Reference" => "api/index.md",
       "Data Structures" => "api/datastructures.md",
       "Selection" => "api/selection.md",
       "Aggregation" => "api/aggregation.md",
       "Joins" => "api/joins.md",
       "Reshaping" => "api/reshaping.md",
       "Loading and Saving" => "api/io.md",
       "Plotting" => "api/plotting.md",
       "OnlineStats Integration" => "manual/onlinestats.md",
       "Out-of-core functionality" => "manual/out-of-core.md",
       "Feature Extraction" => "manual/ml.md",
       "Tutorial" => "manual/tutorial.md",
   ],
   assets = ["assets/custom.css", "assets/custom.js"]
)

deploydocs(
    repo = "github.com/JuliaComputing/JuliaDB.jl.git",
    target = "build",
    julia = "0.6",
    osname = "linux",
    deps = nothing,
    make = nothing,
)


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

struct ExpressRouteCircuitConnectionsApi <: SwaggerApi
    client::Swagger.Client
end

"""

Creates or updates a Express Route Circuit Connection in the specified express route circuits.
Param: resourceGroupName::String (required)
Param: circuitName::String (required)
Param: peeringName::String (required)
Param: connectionName::String (required)
Param: expressRouteCircuitConnectionParameters::ExpressRouteCircuitConnection (required)
Param: api_version::String (required)
Param: subscriptionId::String (required)
Return: ExpressRouteCircuitConnection
"""
function _swaggerinternal_expressRouteCircuitConnectionsCreateOrUpdate(_api::ExpressRouteCircuitConnectionsApi, resourceGroupName::String, circuitName::String, peeringName::String, connectionName::String, expressRouteCircuitConnectionParameters, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "PUT", ExpressRouteCircuitConnection, "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}/connections/{connectionName}", ["azure_auth"], expressRouteCircuitConnectionParameters)
    Swagger.set_param(_ctx.path, "resourceGroupName", resourceGroupName)  # type String
    Swagger.set_param(_ctx.path, "circuitName", circuitName)  # type String
    Swagger.set_param(_ctx.path, "peeringName", peeringName)  # type String
    Swagger.set_param(_ctx.path, "connectionName", connectionName)  # type String
    Swagger.set_param(_ctx.path, "subscriptionId", subscriptionId)  # type String
    Swagger.set_param(_ctx.query, "api-version", api_version)  # type String
    Swagger.set_header_accept(_ctx, ["application/json"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json"] : [_mediaType])
    return _ctx
end

function expressRouteCircuitConnectionsCreateOrUpdate(_api::ExpressRouteCircuitConnectionsApi, resourceGroupName::String, circuitName::String, peeringName::String, connectionName::String, expressRouteCircuitConnectionParameters, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_expressRouteCircuitConnectionsCreateOrUpdate(_api, resourceGroupName, circuitName, peeringName, connectionName, expressRouteCircuitConnectionParameters, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function expressRouteCircuitConnectionsCreateOrUpdate(_api::ExpressRouteCircuitConnectionsApi, response_stream::Channel, resourceGroupName::String, circuitName::String, peeringName::String, connectionName::String, expressRouteCircuitConnectionParameters, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_expressRouteCircuitConnectionsCreateOrUpdate(_api, resourceGroupName, circuitName, peeringName, connectionName, expressRouteCircuitConnectionParameters, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

"""

Deletes the specified Express Route Circuit Connection from the specified express route circuit.
Param: resourceGroupName::String (required)
Param: circuitName::String (required)
Param: peeringName::String (required)
Param: connectionName::String (required)
Param: api_version::String (required)
Param: subscriptionId::String (required)
Return: Nothing
"""
function _swaggerinternal_expressRouteCircuitConnectionsDelete(_api::ExpressRouteCircuitConnectionsApi, resourceGroupName::String, circuitName::String, peeringName::String, connectionName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "DELETE", Nothing, "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}/connections/{connectionName}", ["azure_auth"])
    Swagger.set_param(_ctx.path, "resourceGroupName", resourceGroupName)  # type String
    Swagger.set_param(_ctx.path, "circuitName", circuitName)  # type String
    Swagger.set_param(_ctx.path, "peeringName", peeringName)  # type String
    Swagger.set_param(_ctx.path, "connectionName", connectionName)  # type String
    Swagger.set_param(_ctx.path, "subscriptionId", subscriptionId)  # type String
    Swagger.set_param(_ctx.query, "api-version", api_version)  # type String
    Swagger.set_header_accept(_ctx, ["application/json"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json"] : [_mediaType])
    return _ctx
end

function expressRouteCircuitConnectionsDelete(_api::ExpressRouteCircuitConnectionsApi, resourceGroupName::String, circuitName::String, peeringName::String, connectionName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_expressRouteCircuitConnectionsDelete(_api, resourceGroupName, circuitName, peeringName, connectionName, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function expressRouteCircuitConnectionsDelete(_api::ExpressRouteCircuitConnectionsApi, response_stream::Channel, resourceGroupName::String, circuitName::String, peeringName::String, connectionName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_expressRouteCircuitConnectionsDelete(_api, resourceGroupName, circuitName, peeringName, connectionName, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

"""

Gets the specified Express Route Circuit Connection from the specified express route circuit.
Param: resourceGroupName::String (required)
Param: circuitName::String (required)
Param: peeringName::String (required)
Param: connectionName::String (required)
Param: api_version::String (required)
Param: subscriptionId::String (required)
Return: ExpressRouteCircuitConnection
"""
function _swaggerinternal_expressRouteCircuitConnectionsGet(_api::ExpressRouteCircuitConnectionsApi, resourceGroupName::String, circuitName::String, peeringName::String, connectionName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "GET", ExpressRouteCircuitConnection, "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}/connections/{connectionName}", ["azure_auth"])
    Swagger.set_param(_ctx.path, "resourceGroupName", resourceGroupName)  # type String
    Swagger.set_param(_ctx.path, "circuitName", circuitName)  # type String
    Swagger.set_param(_ctx.path, "peeringName", peeringName)  # type String
    Swagger.set_param(_ctx.path, "connectionName", connectionName)  # type String
    Swagger.set_param(_ctx.path, "subscriptionId", subscriptionId)  # type String
    Swagger.set_param(_ctx.query, "api-version", api_version)  # type String
    Swagger.set_header_accept(_ctx, ["application/json"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json"] : [_mediaType])
    return _ctx
end

function expressRouteCircuitConnectionsGet(_api::ExpressRouteCircuitConnectionsApi, resourceGroupName::String, circuitName::String, peeringName::String, connectionName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_expressRouteCircuitConnectionsGet(_api, resourceGroupName, circuitName, peeringName, connectionName, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function expressRouteCircuitConnectionsGet(_api::ExpressRouteCircuitConnectionsApi, response_stream::Channel, resourceGroupName::String, circuitName::String, peeringName::String, connectionName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_expressRouteCircuitConnectionsGet(_api, resourceGroupName, circuitName, peeringName, connectionName, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

"""

Gets all global reach connections associated with a private peering in an express route circuit.
Param: resourceGroupName::String (required)
Param: circuitName::String (required)
Param: peeringName::String (required)
Param: api_version::String (required)
Param: subscriptionId::String (required)
Return: ExpressRouteCircuitConnectionListResult
"""
function _swaggerinternal_expressRouteCircuitConnectionsList(_api::ExpressRouteCircuitConnectionsApi, resourceGroupName::String, circuitName::String, peeringName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "GET", ExpressRouteCircuitConnectionListResult, "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}/connections", ["azure_auth"])
    Swagger.set_param(_ctx.path, "resourceGroupName", resourceGroupName)  # type String
    Swagger.set_param(_ctx.path, "circuitName", circuitName)  # type String
    Swagger.set_param(_ctx.path, "peeringName", peeringName)  # type String
    Swagger.set_param(_ctx.path, "subscriptionId", subscriptionId)  # type String
    Swagger.set_param(_ctx.query, "api-version", api_version)  # type String
    Swagger.set_header_accept(_ctx, ["application/json"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json"] : [_mediaType])
    return _ctx
end

function expressRouteCircuitConnectionsList(_api::ExpressRouteCircuitConnectionsApi, resourceGroupName::String, circuitName::String, peeringName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_expressRouteCircuitConnectionsList(_api, resourceGroupName, circuitName, peeringName, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function expressRouteCircuitConnectionsList(_api::ExpressRouteCircuitConnectionsApi, response_stream::Channel, resourceGroupName::String, circuitName::String, peeringName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_expressRouteCircuitConnectionsList(_api, resourceGroupName, circuitName, peeringName, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

export expressRouteCircuitConnectionsCreateOrUpdate, expressRouteCircuitConnectionsDelete, expressRouteCircuitConnectionsGet, expressRouteCircuitConnectionsList


text:
# ---
# title: 481. Magical String
# id: problem481
# author: Tian Jun
# date: 2020-10-31
# difficulty: Medium
# categories:
# link: <https://leetcode.com/problems/magical-string/description/>
# hidden: true
# ---
#
# A magical string **S** consists of only '1' and '2' and obeys the following
# rules:
#
# The string **S** is magical because concatenating the number of contiguous
# occurrences of characters '1' and '2' generates the string **S** itself.
#
# The first few elements of string **S** is the following: **S** =
# "1221121221221121122……"
#
# If we group the consecutive '1's and '2's in **S** , it will be:
#
# 1 22 11 2 1 22 1 22 11 2 11 22 ......
#
# and the occurrences of '1's or '2's in each group are:
#
# 1 2 2 1 1 2 1 2 2 1 2 2 ......
#
# You can see that the occurrence sequence above is the **S** itself.
#
# Given an integer N as input, return the number of '1's in the first N number
# in the magical string **S**.
#
# **Note:** N will not exceed 100,000.
#
# **Example 1:**
#
#
#
#     Input: 6
#     Output: 3
#     Explanation: The first 6 elements of magical string S is "12211" and it contains three 1's, so return 3.
#
#
#
## @lc code=start
using LeetCode

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


text:
export Parzen

"""
    struct Parzen <: Score{Float64}

A parzen score.
"""
struct Parzen <: Score{Float64}
    means :: Vector{Float64}
    sd :: Float64
end

@impl begin
    struct ParzenGetScore end
    function get_score(sf::Parzen, i::Float64)::AbstractFloat
        t = 0.0
        for m in sf.means
            t += normal_density(i, m, sf.sd)
        end
        return t / length(sf.means)
    end
end