text:
@userplot AndrewsPlot

"""
    andrewsplot(args...; kw...)
Shows each row of an array (or table) as a line. The `x` argument specifies a
grouping variable. This is a way to visualize structure in high-dimensional data.
https://en.wikipedia.org/wiki/Andrews_plot
#Examples
```julia
using RDatasets, StatsPlots
iris = dataset("datasets", "iris")
@df iris andrewsplot(:Species, cols(1:4))
```
"""
andrewsplot

@recipe function f(h::AndrewsPlot)
    if length(h.args) == 2  # specify x if not given
        x, y = h.args
    else
        y = h.args[1]
        x = ones(size(y,1))
    end

    seriestype := :andrews

    # series in a user recipe will have different colors
    for g in unique(x)
        @series begin
            label := "$g"
            range(-π, stop = π, length = 200), Surface(y[g .== x,:]) #surface needed, or the array will be split into columns
        end
    end
    nothing
end

# the series recipe
@recipe function f(::Type{Val{:andrews}}, x, y, z)
    y = y.surf
    rows,cols = size(y)
    seriestype := :path

    # these series are the lines, will keep the same colors
    for j in 1:rows
        @series begin
            primary := false
            ys     = zeros(length(x))
            terms = [isodd(i) ? cos((i÷2).*ti) : sin((i÷2).*ti) for i = 2:cols, ti=x]
            for ti = eachindex(x)
                ys[ti] = y[j,1]/sqrt(2) + sum(y[j,i].*terms[i-1,ti] for i = 2:cols)
            end

            x := x
            y := ys
            ()
        end
    end

    x := []
    y := []
    ()
end


text:
#_____________________________________________________________________
#                            Alice's code
#
using Statistics, ReusePatterns

abstract type AbstractPolygon end

@quasiabstract mutable struct Polygon <: AbstractPolygon
    x::Vector{Float64}
    y::Vector{Float64}
end

# Retrieve the number of vertices, and their X and Y coordinates
vertices(p::Polygon) = length(p.x)
coords_x(p::Polygon) = p.x
coords_y(p::Polygon) = p.y

# Move, scale and rotate a polygon
function move!(p::Polygon, dx::Real, dy::Real)
    p.x .+= dx
    p.y .+= dy
end

function scale!(p::Polygon, scale::Real)
    m = mean(p.x); p.x = (p.x .- m) .* scale .+ m
    m = mean(p.y); p.y = (p.y .- m) .* scale .+ m
end

function rotate!(p::Polygon, angle_deg::Real)
    θ = float(angle_deg) * pi / 180
    R = [cos(θ) -sin(θ); sin(θ) cos(θ)]
    x = p.x .- mean(p.x)
    y = p.y .- mean(p.y)
    (x, y) = R * [x, y]
    p.x = x .+ mean(p.x)
    p.y = y .+ mean(p.y)
end

#_____________________________________________________________________
#                             Bob's code
#

@quasiabstract mutable struct RegularPolygon <: Polygon

    radius::Float64
end

function RegularPolygon(n::Integer, radius::Real)
    @assert n >= 3
    θ = range(0, stop=2pi-(2pi/n), length=n)
    c = radius .* exp.(im .* θ)
    return RegularPolygon(real(c), imag(c), radius)
end

# Compute length of a side and the polygon area
side(p::RegularPolygon) = 2 * p.radius * sin(pi / vertices(p))
area(p::RegularPolygon) = side(p)^2 * vertices(p) / 4 / tan(pi / vertices(p))

function scale!(p::RegularPolygon, scale::Real)
    invoke(scale!, Tuple{supertype(RegularPolygon), typeof(scale)}, p, scale) # call "super" method
    p.radius *= scale        # update internal state
end

# Attach a label to a polygon
mutable struct Named{T} <: AbstractPolygon
    polygon::T
    name::String
end
Named{T}(name, args...; kw...) where T = Named{T}(T(args...; kw...), name)
name(p::Named) = p.name

# Forward methods from `Named` to `Polygon`
@forward (Named, :polygon) RegularPolygon

ext: jl


text:
mutable struct CircuitData{S<:Real, T<:CircuitParams} <: AbstractData
    nPoint::Int
    frequency::Vector{S}
    params::Vector{T}
    CircuitData(frequency::AbstractVector{S}, params::Vector{T}) where
        {S<:Real, T<:CircuitParams} =
        (length(frequency) == length(params))?
        new{S,T}(length(frequency), collect(frequency), params):
        error("CircuitData Error: Number of frequency points and datapoints don't match.")
end

check_frequency_identical(d1::CircuitData, d2::CircuitData, d3::CircuitData...) =
    begin
        data = [d1, d2, d3...]
        freqs = [d.frequency for d in data]
        # foldl doesn't seem to work reliably here
        # foldl(==, freqs)
        all(n -> (freqs[1] == freqs[n]), 1:length(freqs))
    end

"""
    ndatapoints(d::CircuitData{S, T}) where {S<:Real, T<:CircuitParams}
The number of datapoints for a given `CircuitData`.
"""
ndatapoints(d::CircuitData{S, T}) where {S<:Real, T<:CircuitParams} =
    length(d.frequency)

function show(io::IO, D::CircuitData{S, T}) where {S<:Real, T<:CircuitParams}
    write(io, "CircuitData{$S, $T}, ")
    write(io, "# datapoints = $(D.nPoint)\n")
end

# getindex methods for CircuitData
for p in (:Impedance, :Admittance)
    @eval getindex(D::CircuitData{S, $p{T}}, I::Int) where {S<:Real, T<:Real} =
        D.params[I].data
    @eval getindex(D::CircuitData{S, $p{T}}, I::Range) where {S<:Real, T<:Real} =
        [D.params[n].data for n in I]
    @eval getindex(D::CircuitData{S, $p{T}}, I::Vector) where {S<:Real, T<:Real} =
        [D.params[n] for n in I]
    @eval getindex(D::CircuitData{S, $p{T}}, I::Vector{Bool}) where {S<:Real,
        T<:Real} = (length(D.params) == length(I))?
        [D.params[n].data for n in Base.LogicalIndex(I)]:
        error("Length of the mask different from lenghth of the array attemped to access")
    @eval getindex(D::CircuitData{S, $p{T}}, ::Colon) where {S<:Real, T<:Real} =
        getindex(D, 1:length(D.params))
end


text:
### Reproduce Figure 2c from Draine (2011)

using DustyHII
using Plots

# Define the fixed model parameters for that panel
γ = 10.0
β = 3.0
T4=0.94
hnui = 18.0 # eV

# The model grid used for the lines.
grid = (
    a=(τ=0.21, Qn=1),
    b=(τ=0.45, Qn=1e1),
    c=(τ=0.96, Qn=1e2),
    d=(τ=2.07, Qn=1e3),
    e=(τ=4.46, Qn=1e4),
    f=(τ=9.60, Qn=1e5),
    e=(τ=20.7, Qn=1e6),
    f=(τ=44.6, Qn=1e7))

keys = grid.keys()

# Go through and calculate the models
#
# Since the solver expects u0 as an initial value and the
# model grid gives τ and Q_0 n_rms, we here need to convert the Qn
# value to u0. For this we need the n_rms value which however is a
# value calculated by the model. The way to tackle this is to create
# a table of n_rms vs u0 values.
#

for k in keys

m = DustyHII.draine2011model


text:
# Tests for module InterestRates

using Base.Test
using BusinessDays
using InterestRates

bd = BusinessDays
ir = InterestRates

vert_x = [11, 15, 19, 23]
vert_y = [0.10, 0.15, 0.20, 0.19]

dt_curve = Date(2015,08,03)

# Error testing
@test_throws ErrorException ir.IRCurve("", ir.Actual365(), ir.ExponentialCompounding(),
	ir.Linear(), dt_curve, [1, 2, 6, 5], [.1, .1, .1, .1])

@test_throws ErrorException ir.IRCurve("", ir.Actual365(), ir.ExponentialCompounding(),
	ir.Linear(), dt_curve, [1, 2, 3, 4], [.1, .1, .1])

@test_throws ErrorException ir.IRCurve("", ir.Actual365(), ir.ExponentialCompounding(),
	ir.Linear(), dt_curve, Array(Int64,0) , [.1, .1, .1])

@test_throws ErrorException ir.IRCurve("", ir.Actual365(), ir.ExponentialCompounding(),
	ir.Linear(), dt_curve, Array(Int64,1) , Array(Float64,0))

@test_throws ErrorException ir.IRCurve("", ir.Actual365(), ir.ExponentialCompounding(),
	ir.Linear(), dt_curve, Array(Int64,0) , Array(Float64,0))

bd.initcache(bd.Brazil())

curve_b252_ec_lin = ir.IRCurve("dummy-linear", ir.BDays252(bd.Brazil()),
	ir.ExponentialCompounding(), ir.Linear(), dt_curve,
	vert_x, vert_y)

@test_throws ErrorException zero_rate(curve_b252_ec_lin, dt_curve - Dates.Day(10))

@test ir.curve_get_name(curve_b252_ec_lin) == "dummy-linear"
@test ir.curve_get_date(curve_b252_ec_lin) == dt_curve

maturity_2_days = advancebdays(bd.Brazil(), dt_curve, vert_x[1] + 2)
yrs = (vert_x[1] + 2) / 252.0
zero_rate_2_days = 0.125
disc_2_days = 1.0 / ( (1.0 + zero_rate_2_days)^yrs)
@test_approx_eq zero_rate_2_days zero_rate(curve_b252_ec_lin, maturity_2_days) # Linear interpolation
@test_approx_eq disc_2_days discountfactor(curve_b252_ec_lin, maturity_2_days)
@test_approx_eq zero_rate(curve_b252_ec_lin, advancebdays(bd.Brazil(), dt_curve, 11)) 0.10
@test_throws ErrorException zero_rate(curve_b252_ec_lin, advancebdays(bd.Brazil(), dt_curve, -4)) # maturity before curve date
@test_approx_eq zero_rate(curve_b252_ec_lin, advancebdays(bd.Brazil(), dt_curve, 11-4)) 0.05 # extrapolate before first vertice
@test_approx_eq zero_rate(curve_b252_ec_lin, advancebdays(bd.Brazil(), dt_curve, 23+4)) 0.18 # extrapolate after last vertice

dt_maturity = dt_curve+Dates.Day(30)
@test_approx_eq ERF_to_rate(curve_b252_ec_lin, ERF(curve_b252_ec_lin, dt_maturity), ir.yearfraction(curve_b252_ec_lin, dt_maturity)) zero_rate(curve_b252_ec_lin, dt_maturity)

curve_ac360_cont_ff = ir.IRCurve("dummy-cont-flatforward", ir.Actual360(),
	ir.ContinuousCompounding(), ir.FlatForward(), dt_curve,
	vert_x, vert_y)

@test_approx_eq zero_rate(curve_ac360_cont_ff, dt_curve + Dates.Day(11)) 0.1
@test_approx_eq zero_rate(curve_ac360_cont_ff, dt_curve + Dates.Day(15)) 0.15
@test_approx_eq zero_rate(curve_ac360_cont_ff, dt_curve + Dates.Day(19)) 0.20
@test_approx_eq zero_rate(curve_ac360_cont_ff, dt_curve + Dates.Day(23)) 0.19
@test zero_rate(curve_ac360_cont_ff, dt_curve + Dates.Day(16)) > 0.15
@test zero_rate(curve_ac360_cont_ff, dt_curve + Dates.Day(17)) < 0.20
@test_approx_eq forward_rate(curve_ac360_cont_ff, dt_curve + Dates.Day(11), dt_curve + Dates.Day(15)) 0.2875 # forward_rate calculation on vertices
@test_approx_eq forward_rate(curve_ac360_cont_ff, dt_curve + Dates.Day(11), dt_curve + Dates.Day(13)) 0.2875 # forward_rate calculation on interpolated maturity
@test_approx_eq ERF(curve_ac360_cont_ff, dt_curve + Dates.Day(13)) 1.00466361875533 # ffwd interp on ERF

dt_maturity = dt_curve+Dates.Day(30)
@test_approx_eq ERF_to_rate(curve_ac360_cont_ff, ERF(curve_ac360_cont_ff, dt_maturity), ir.yearfraction(curve_ac360_cont_ff, dt_maturity)) zero_rate(curve_ac360_cont_ff, dt_maturity)
@test_approx_eq zero_rate(curve_ac360_cont_ff, dt_curve + Dates.Day(13)) 0.128846153846152 # ffwd interp as zero_rate
@test_approx_eq ERF(curve_ac360_cont_ff, dt_curve + Dates.Day(19), dt_curve + Dates.Day(23)) 1.00158458746737
@test_approx_eq forward_rate(curve_ac360_cont_ff, dt_curve + Dates.Day(19), dt_curve + Dates.Day(23)) 0.1425000000000040
@test_approx_eq zero_rate(curve_ac360_cont_ff, dt_curve + Dates.Day(30)) 0.1789166666666680 # ffwd extrap after last vertice
@test_approx_eq forward_rate(curve_ac360_cont_ff, dt_curve + Dates.Day(19), dt_curve + Dates.Day(23)) forward_rate(curve_ac360_cont_ff, dt_curve + Dates.Day(50), dt_curve + Dates.Day(51))
@test_approx_eq forward_rate(curve_ac360_cont_ff, dt_curve + Dates.Day(19), dt_curve + Dates.Day(23)) forward_rate(curve_ac360_cont_ff, dt_curve + Dates.Day(50), dt_curve + Dates.Day(100))

@test_approx_eq forward_rate(curve_ac360_cont_ff, dt_curve + Dates.Day(11), dt_curve + Dates.Day(15)) 0.2875
@test_approx_eq zero_rate(curve_ac360_cont_ff, dt_curve + Dates.Day(9)) 0.05833333333333 # ffwd extrap before first vertice

@test discountfactor(curve_ac360_cont_ff, dt_curve) == 1
@test isnan(ERF_to_rate(curve_ac360_cont_ff, 1.0, 0.0))

# Null curve tests
n_curve = ir.NullIRCurve()
@test n_curve == ir.NullIRCurve() # Should be singleton
@test ERF(n_curve, Date(2000,1,1)) == 1.0
@test ER(n_curve, Date(2000,1,1)) == 0.0
@test discountfactor(n_curve, Date(2000,1,1)) == 1.0
@test ir.curve_get_name(n_curve) == "NullCurve"
@test isnullcurve(n_curve) == true
@test isnullcurve(curve_ac360_cont_ff) == false
@test forward_rate(n_curve, Date(2000,1,1), Date(2000,1,2)) == 0.0
@test zero_rate(n_curve, Date(2000,1,1)) == 0.0
@test zero_rate(n_curve, [Date(2000,1,1), Date(2000,1,2)]) == [ 0.0, 0.0 ]

# Tests for vector functions
dt_curve = Date(2015, 08, 07)
curve_ac365_simple_linear = ir.IRCurve("dummy-simple-linear", ir.Actual365(),
	ir.SimpleCompounding(), ir.Linear(), dt_curve,
	vert_x, vert_y)
mat_vec = [ Date(2015,08,17), Date(2015,08,18), Date(2015,08,19), Date(2015,08,20), Date(2015,08,21), Date(2015,08,22)]
@test_approx_eq zero_rate(curve_ac365_simple_linear, mat_vec) [0.0875,0.1,0.1125,0.1250,0.1375,0.15]
@test_approx_eq ERF(curve_ac365_simple_linear, mat_vec) [1.00239726027397, 1.00301369863014, 1.00369863013699, 1.00445205479452, 1.00527397260274, 1.00616438356164]
@test_approx_eq discountfactor(curve_ac365_simple_linear, mat_vec) [0.997608472839084, 0.996995356459984, 0.996314999317592, 0.995567678145244, 0.994753696259454, 0.993873383253914]

dt_maturity = dt_curve+Dates.Day(30)
@test_approx_eq ERF_to_rate(curve_ac365_simple_linear, ERF(curve_ac365_simple_linear, dt_maturity), ir.yearfraction(curve_ac365_simple_linear, dt_maturity)) zero_rate(curve_ac365_simple_linear, dt_maturity)

comp = ir.CompositeInterpolation(ir.StepFunction(), ir.Linear(), ir.StepFunction())
curve_ac365_simple_comp = ir.IRCurve("dummy-simple-linear", ir.Actual365(),
	ir.SimpleCompounding(), comp, dt_curve,
	vert_x, vert_y)
@test_approx_eq zero_rate(curve_ac365_simple_comp, mat_vec) [0.1,0.1,0.1125,0.1250,0.1375,0.15]
@test_approx_eq zero_rate(curve_ac365_simple_comp, Date(2100,2,2)) 0.19

curve_step = ir.IRCurve("step-curve", ir.Actual365(),
	ir.SimpleCompounding(), ir.StepFunction(), dt_curve,
	vert_x, vert_y)
mat_vec = [ Date(2015,08,08), Date(2015,08,12), Date(2015,08,17), Date(2015,08,18), Date(2015,08,19),
	Date(2015,08,21), Date(2015,08,22), Date(2015,08,23), Date(2015,08,25), Date(2015,08,26),
	Date(2015,08,27), Date(2015,08,29), Date(2015,08,30), Date(2015,08,31), Date(2015,09,26)]

@test_approx_eq zero_rate(curve_step, mat_vec) [0.10, 0.10, 0.10, 0.10, 0.10, 0.10, 0.15, 0.15, 0.15, 0.20, 0.20, 0.20, 0.19, 0.19, 0.19]

dt_maturity = dt_curve+Dates.Day(30)
@test_approx_eq ERF_to_rate(curve_step, ERF(curve_step, dt_maturity), ir.yearfraction(curve_step, dt_maturity)) zero_rate(curve_step, dt_maturity)

# Nelson Siegel
dt_curve = Date(2015, 08, 11)
curve_NS = ir.IRCurve("dummy-continuous-nelsonsiegel", ir.Actual360(),
	ir.ContinuousCompounding(), ir.NelsonSiegel(), dt_curve,
	[0.1, 0.2, 0.3, 0.5])

mat_vec = [Date(2015,8,12), Date(2016,8,12)]
@test_approx_eq zero_rate(curve_NS, mat_vec) [0.300069315921728, 0.311522078457982]
@test_approx_eq discountfactor(curve_NS, mat_vec) [0.999166821408637, 0.727908844513432]

dt_maturity = dt_curve+Dates.Day(30)
@test_approx_eq ERF_to_rate(curve_NS, ERF(curve_NS, dt_maturity), ir.yearfraction(curve_NS, dt_maturity)) zero_rate(curve_NS, dt_maturity)

# Svensson
dt_curve = Date(2015, 08, 11)
curve_sven = ir.IRCurve("dummy-continuous-svensson", ir.Actual360(),
	ir.ContinuousCompounding(), ir.Svensson(), dt_curve,
	[0.1, 0.2, 0.3, 0.4, 0.5, 0.8])

mat_vec = [Date(2015,8,12), Date(2016,8,12)]
@test_approx_eq zero_rate(curve_sven, mat_vec) [0.300513102478340, 0.408050168725566]
@test_approx_eq discountfactor(curve_sven, mat_vec) [0.999165589696054, 0.659690510410030]

dt_maturity = dt_curve+Dates.Day(30)
@test_approx_eq ERF_to_rate(curve_NS, ERF(curve_NS, dt_maturity), ir.yearfraction(curve_NS, dt_maturity)) zero_rate(curve_NS, dt_maturity)

# Splines

vert_x = [11, 15, 19, 23, 25]
vert_y = [0.10, 0.12, 0.20, 0.22, 0.2]

sp = ir.splinefit([1, 2, 3, 4], [1.0, 2.0, 3.0, 4.0])
ir.splineint(sp, [5, 6])
sp = ir.splinefit([1.0, 2.0, 3.0, 4.0], [1.0, 2.0, 3.0, 4.0])
ir.splineint(sp, [1.0, 1.5])

sp = ir.splinefit(vert_x, vert_y)
y = ir.splineint(sp, convert(Vector{Int}, 1:30))
@test_approx_eq y[vert_x] vert_y

y_benchmark = [0.09756098, 0.09780488, 0.09804878, 0.09829268, 0.09853659, 0.09878049, 0.09902439, 0.09926829, 0.09951220, 0.09975610, 0.10000000, 0.10054116, 0.10286585,
0.10875762, 0.12000000, 0.13753049, 0.15890244, 0.18082317, 0.20000000, 0.21371189, 0.22152439, 0.22357470, 0.22000000, 0.21137195, 0.20000000, 0.18817073,
0.17634146, 0.16451220, 0.15268293, 0.14085366]

@test_approx_eq_eps y y_benchmark 5e-9

curve_spline_rates = ir.IRCurve("dummy-SplineOnRates", ir.Actual360(),
	ir.ContinuousCompounding(), ir.CubicSplineOnRates(), dt_curve,
	vert_x, vert_y)

@test_approx_eq zero_rate(curve_spline_rates, dt_curve + Dates.Day(11)) 0.1
@test_approx_eq zero_rate(curve_spline_rates, [dt_curve+Dates.Day(11), dt_curve+Dates.Day(15)]) vert_y[1:2]

dt_maturity = dt_curve+Dates.Day(30)
@test_approx_eq ERF_to_rate(curve_spline_rates, ERF(curve_spline_rates, dt_maturity), ir.yearfraction(curve_spline_rates, dt_maturity)) zero_rate(curve_spline_rates, dt_maturity)

mat_vec = convert(Vector{Dates.Day}, convert(Vector{Int}, 1:30)) + dt_curve
@test_approx_eq zero_rate(curve_spline_rates, mat_vec) y

curve_spline_discount = ir.IRCurve("dummy-SplineOnDiscountFactors", ir.Actual360(),
	ir.ContinuousCompounding(), ir.CubicSplineOnDiscountFactors(), dt_curve,
	vert_x, vert_y)

@test_approx_eq zero_rate(curve_spline_discount, dt_curve + Dates.Day(11)) 0.1
@test_approx_eq zero_rate(curve_spline_discount, [dt_curve+Dates.Day(11), dt_curve+Dates.Day(15)]) vert_y[1:2]

@test ir.advancedays(ir.BDays252(bd.Brazil()), Date(2015,9,1), [0, 1, 3, 4, 5]) == [Date(2015,9,1),Date(2015,9,2),Date(2015,9,4),Date(2015,9,8),Date(2015,9,9)]
@test ir.advancedays(ir.Actual360(), Date(2015,9,1), [0, 1, 3, 4, 5]) == [Date(2015,9,1),Date(2015,9,2),Date(2015,9,4),Date(2015,9,5),Date(2015,9,6)]
@test ir.advancedays(ir.Actual365(), Date(2015,9,1), [0, 1, 3, 4, 5]) == [Date(2015,9,1),Date(2015,9,2),Date(2015,9,4),Date(2015,9,5),Date(2015,9,6)]

param = 10
ir.curve_set_dict_parameter!(curve_spline_discount, :custom_parameter, param)
@test ir.curve_get_dict_parameter(curve_spline_discount, :custom_parameter) == param

include("usage.jl")
include("perftests.jl")


text:
struct Assays
    count::NamedArray
    norm_count::NamedArray
    scaled_count::NamedArray
    feature_data::DataFrame
    var_features::Array{String,1}
    name::String
end

struct Reductions
    name::String
    cell_coordinates::DataFrame
    feature_coordinates::DataFrame
    key::String
    standard_deviation::Array{Float32,1}
    assay_used::String
    misc::AbstractArray
end

struct Pissaro
    assays::Dict{String, Assays}
    reductions::Dict{String, Reductions}
    cell_data::DataFrame
    default_assay::String
    default_ident::String
end

function Base.show(io::IO, m::Pissaro)
    println("A PissaroObject with:")
    println(length(m.assays), " assays")
    println(nrow(m.cell_data), " cells")
    println("active assay: ", m.default_assay, " with ", size(m.assays[m.default_assay].count)[1], " features")
end

function Base.show(io::IO, m::Assays)
    print("assay ", m.name)
end

function GetCount(X::Pissaro; assay::String = X.default_assay, named::Bool = true)
    if named
        GetAssay(X, assay = assay).count
    else
        GetAssay(X, assay = assay).count.array
    end
end

function GetNormCount(X::Pissaro; assay::String = X.default_assay, named::Bool = true)
    if named
        GetAssay(X, assay = assay).norm_count
    else
        GetAssay(X, assay = assay).norm_count.array
    end
end

function GetScaledCount(X::Pissaro; assay::String = X.default_assay, named::Bool = true)
    if named
        GetAssay(X, assay = assay).scaled_count
    else
        GetAssay(X, assay = assay).scaled_count.array
    end
end

function GetFeatureData(X::Pissaro; assay::String = X.default_assay)
    GetAssay(X, assay = assay).feature_data
end

function GetAssay(X::Pissaro; assay::String = X.default_assay)
    in(assay, keys(X.assays)) ? X.assays[assay] : error(assay, " assay not present in PissaroObject")
end

function GetVariableFeatures(X::Pissaro; assay::String = X.default_assay)
    GetAssay(X, assay = assay).var_features
end

max_stars_repo_name: Cortalak/Pissaro

max_issues_repo_name: Cortalak/Pissaro

max_forks_repo_name: Cortalak/Pissaro


text:
# This file is a part of SimilaritySearch.jl
# License is Apache 2.0: https://www.apache.org/licenses/LICENSE-2.0.txt

export Sss, LaesaTournament #, KvpTournament

function Sss(dist::Function, db::Array{T,1}, alpha::Float64; shuf=false) where T
    pivots = [db[refID] for refID in select_sss(dist, db, alpha, shuf=shuf)]
    fit(Laesa, dist, db, pivots)
end

function LaesaTournament(dist::Function, db::Array{T,1}, numrefs::Int, tournamentsize::Int=3) where T
    pivots = [db[refID] for refID in select_tournament(dist, db, numrefs, tournamentsize)]
    fit(Laesa, dist, db, pivots)
end

# function KvpTournament(db::Array{T,1}, dist::Function, k::Int, numrefs::Int, tournamentsize::Int=0) where T
#     #pivots = [db[refID] for refID in select_tournament(db, numrefs, tournamentsize, dist)]
#     pivots = select_tournament(db, dist, numrefs, tournamentsize)
#     Kvp(db, dist, k, pivots)
# end


text:
using DiffEqPhysics
using StochasticDiffEq

T = 120.0 # °K
T0 = 90.0 # °K
kb = 8.3144598e-3 # kJ/(K*mol)
ϵ = T * kb
σ = 0.34 # nm
ρ = 1374/1.6747# Da/nm^3
m = 39.95# Da
N = 216
L = (m*N/ρ)^(1/3)#10.229σ
R = 0.5*L
v_dev = sqrt(kb * T / m)
bodies = generate_bodies_in_cell_nodes(N, m, v_dev, L)

τ = 0.5e-3 # ps or 1e-12 s
t1 = 0.0
t2 = 2000τ

parameters = LennardJonesParameters(ϵ, σ, R)
lj_system = PotentialNBodySystem(bodies, Dict(:lennard_jones => parameters));
thermostat = AndersenThermostat(90, 0.01/τ)
#thermostat = BerendsenThermostat(90, 2000τ)
#thermostat = LangevinThermostat(90, 0.00)
#thermostat = NoseHooverThermostat(T0, 200τ)
pbc = CubicPeriodicBoundaryConditions(L)
simulation = NBodySimulation(lj_system, (t1, t2), pbc, thermostat, kb);
result = @time run_simulation(simulation, VelocityVerlet(), dt=τ)
#result = @time run_simulation_sde(simulation, ISSEM(symplectic=true,theta=0.5))

t = t1:τ:result.solution.t[end-1]
temper = temperature.(result, t)

using Plots
pl=plot(t, temper, ylim=[0,200], xlabel="t, ps", ylabel = "T, °K", label="Temperature, °K", linewidth=2)
plot!(pl, t, T0*ones(length(t)), label = "90 °K", linewidth=2)
plot!(pl, title="Andersen thermostat at dt*v=$(thermostat.ν*τ) ")
#plot!(pl, title="Berendsen thermostat at tau=$(thermostat.τ) ps")
#plot!(pl, title="Nose-Hoover thermostat at tau=$(thermostat.τ) ps")

time_now = Dates.format(now(), "yyyy_mm_dd_HH_MM_SS")
Nactual = length(bodies)
timesteps = round(length(result.solution.t))

@time save_to_pdb(result, "D:/liquid argon simulation $Nactual molecules and $timesteps steps $time_now.pdb" )

#using JLD
#save("d:/nosehoover thermostat for water liquid argon $T0 and $(thermostat.τ) _$time_now.jld", "t",t, "temper", temper, "T0", T0, "τ", thermostat.τ)


text:
function commandEcho(ed::Editor, args::String)
    setStatusMessage(ed, args)
end

addCommand(:echo, commandEcho,
           help="echo <msg>: set the status message to <msg>")


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

"""
    cancel_journal_kinesis_stream(name, stream_id)
    cancel_journal_kinesis_stream(name, stream_id, params::Dict{String,<:Any})

Ends a given Amazon QLDB journal stream. Before a stream can be canceled, its current
status must be ACTIVE. You can't restart a stream after you cancel it. Canceled QLDB stream
resources are subject to a 7-day retention period, so they are automatically deleted after
this limit expires.

# Arguments
- `name`: The name of the ledger.
- `stream_id`: The UUID (represented in Base62-encoded text) of the QLDB journal stream to
  be canceled.

"""
cancel_journal_kinesis_stream(name, streamId; aws_config::AbstractAWSConfig=global_aws_config()) = qldb("DELETE", "/ledgers/$(name)/journal-kinesis-streams/$(streamId)"; aws_config=aws_config)
cancel_journal_kinesis_stream(name, streamId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = qldb("DELETE", "/ledgers/$(name)/journal-kinesis-streams/$(streamId)", params; aws_config=aws_config)

"""
    create_ledger(name, permissions_mode)
    create_ledger(name, permissions_mode, params::Dict{String,<:Any})

Creates a new ledger in your AWS account in the current Region.

# Arguments
- `name`: The name of the ledger that you want to create. The name must be unique among all
  of your ledgers in the current AWS Region. Naming constraints for ledger names are defined
  in Quotas in Amazon QLDB in the Amazon QLDB Developer Guide.
- `permissions_mode`: The permissions mode to assign to the ledger that you want to create.
  This parameter can have one of the following values:    ALLOW_ALL: A legacy permissions
  mode that enables access control with API-level granularity for ledgers. This mode allows
  users who have the SendCommand API permission for this ledger to run all PartiQL commands
  (hence, ALLOW_ALL) on any tables in the specified ledger. This mode disregards any
  table-level or command-level IAM permissions policies that you create for the ledger.
  STANDARD: (Recommended) A permissions mode that enables access control with finer
  granularity for ledgers, tables, and PartiQL commands. By default, this mode denies all
  user requests to run any PartiQL commands on any tables in this ledger. To allow PartiQL
  commands to run, you must create IAM permissions policies for specific table resources and
  PartiQL actions, in addition to the SendCommand API permission for the ledger. For
  information, see Getting started with the standard permissions mode in the Amazon QLDB
  Developer Guide.    We strongly recommend using the STANDARD permissions mode to maximize
  the security of your ledger data.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"DeletionProtection"`: The flag that prevents a ledger from being deleted by any user.
  If not provided on ledger creation, this feature is enabled (true) by default. If deletion
  protection is enabled, you must first disable it before you can delete the ledger. You can
  disable it by calling the UpdateLedger operation to set the flag to false.
- `"Tags"`: The key-value pairs to add as tags to the ledger that you want to create. Tag
  keys are case sensitive. Tag values are case sensitive and can be null.
"""
create_ledger(Name, PermissionsMode; aws_config::AbstractAWSConfig=global_aws_config()) = qldb("POST", "/ledgers", Dict{String, Any}("Name"=>Name, "PermissionsMode"=>PermissionsMode); aws_config=aws_config)
create_ledger(Name, PermissionsMode, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = qldb("POST", "/ledgers", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Name"=>Name, "PermissionsMode"=>PermissionsMode), params)); aws_config=aws_config)

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

Deletes a ledger and all of its contents. This action is irreversible. If deletion
protection is enabled, you must first disable it before you can delete the ledger. You can
disable it by calling the UpdateLedger operation to set the flag to false.

# Arguments
- `name`: The name of the ledger that you want to delete.

"""
delete_ledger(name; aws_config::AbstractAWSConfig=global_aws_config()) = qldb("DELETE", "/ledgers/$(name)"; aws_config=aws_config)
delete_ledger(name, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = qldb("DELETE", "/ledgers/$(name)", params; aws_config=aws_config)

"""
    describe_journal_kinesis_stream(name, stream_id)
    describe_journal_kinesis_stream(name, stream_id, params::Dict{String,<:Any})

Returns detailed information about a given Amazon QLDB journal stream. The output includes
the Amazon Resource Name (ARN), stream name, current status, creation time, and the
parameters of the original stream creation request. This action does not return any expired
journal streams. For more information, see Expiration for terminal streams in the Amazon
QLDB Developer Guide.

# Arguments
- `name`: The name of the ledger.
- `stream_id`: The UUID (represented in Base62-encoded text) of the QLDB journal stream to
  describe.

"""
describe_journal_kinesis_stream(name, streamId; aws_config::AbstractAWSConfig=global_aws_config()) = qldb("GET", "/ledgers/$(name)/journal-kinesis-streams/$(streamId)"; aws_config=aws_config)
describe_journal_kinesis_stream(name, streamId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = qldb("GET", "/ledgers/$(name)/journal-kinesis-streams/$(streamId)", params; aws_config=aws_config)

"""
    describe_journal_s3_export(export_id, name)
    describe_journal_s3_export(export_id, name, params::Dict{String,<:Any})

Returns information about a journal export job, including the ledger name, export ID,
creation time, current status, and the parameters of the original export creation request.
This action does not return any expired export jobs. For more information, see Export job
expiration in the Amazon QLDB Developer Guide. If the export job with the given ExportId
doesn't exist, then throws ResourceNotFoundException. If the ledger with the given Name
doesn't exist, then throws ResourceNotFoundException.

# Arguments
- `export_id`: The UUID (represented in Base62-encoded text) of the journal export job to
  describe.
- `name`: The name of the ledger.

"""
describe_journal_s3_export(exportId, name; aws_config::AbstractAWSConfig=global_aws_config()) = qldb("GET", "/ledgers/$(name)/journal-s3-exports/$(exportId)"; aws_config=aws_config)
describe_journal_s3_export(exportId, name, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = qldb("GET", "/ledgers/$(name)/journal-s3-exports/$(exportId)", params; aws_config=aws_config)

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

Returns information about a ledger, including its state and when it was created.

# Arguments
- `name`: The name of the ledger that you want to describe.

"""
describe_ledger(name; aws_config::AbstractAWSConfig=global_aws_config()) = qldb("GET", "/ledgers/$(name)"; aws_config=aws_config)
describe_ledger(name, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = qldb("GET", "/ledgers/$(name)", params; aws_config=aws_config)

"""
    export_journal_to_s3(exclusive_end_time, inclusive_start_time, role_arn, s3_export_configuration, name)
    export_journal_to_s3(exclusive_end_time, inclusive_start_time, role_arn, s3_export_configuration, name, params::Dict{String,<:Any})

Exports journal contents within a date and time range from a ledger into a specified Amazon
Simple Storage Service (Amazon S3) bucket. The data is written as files in Amazon Ion
format. If the ledger with the given Name doesn't exist, then throws
ResourceNotFoundException. If the ledger with the given Name is in CREATING status, then
throws ResourcePreconditionNotMetException. You can initiate up to two concurrent journal
export requests for each ledger. Beyond this limit, journal export requests throw
LimitExceededException.

# Arguments
- `exclusive_end_time`: The exclusive end date and time for the range of journal contents
  to export. The ExclusiveEndTime must be in ISO 8601 date and time format and in Universal
  Coordinated Time (UTC). For example: 2019-06-13T21:36:34Z. The ExclusiveEndTime must be
  less than or equal to the current UTC date and time.
- `inclusive_start_time`: The inclusive start date and time for the range of journal
  contents to export. The InclusiveStartTime must be in ISO 8601 date and time format and in
  Universal Coordinated Time (UTC). For example: 2019-06-13T21:36:34Z. The InclusiveStartTime
  must be before ExclusiveEndTime. If you provide an InclusiveStartTime that is before the
  ledger's CreationDateTime, Amazon QLDB defaults it to the ledger's CreationDateTime.
- `role_arn`: The Amazon Resource Name (ARN) of the IAM role that grants QLDB permissions
  for a journal export job to do the following:   Write objects into your Amazon Simple
  Storage Service (Amazon S3) bucket.   (Optional) Use your customer master key (CMK) in AWS
  Key Management Service (AWS KMS) for server-side encryption of your exported data.
- `s3_export_configuration`: The configuration settings of the Amazon S3 bucket destination
  for your export request.
- `name`: The name of the ledger.

"""
export_journal_to_s3(ExclusiveEndTime, InclusiveStartTime, RoleArn, S3ExportConfiguration, name; aws_config::AbstractAWSConfig=global_aws_config()) = qldb("POST", "/ledgers/$(name)/journal-s3-exports", Dict{String, Any}("ExclusiveEndTime"=>ExclusiveEndTime, "InclusiveStartTime"=>InclusiveStartTime, "RoleArn"=>RoleArn, "S3ExportConfiguration"=>S3ExportConfiguration); aws_config=aws_config)
export_journal_to_s3(ExclusiveEndTime, InclusiveStartTime, RoleArn, S3ExportConfiguration, name, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = qldb("POST", "/ledgers/$(name)/journal-s3-exports", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ExclusiveEndTime"=>ExclusiveEndTime, "InclusiveStartTime"=>InclusiveStartTime, "RoleArn"=>RoleArn, "S3ExportConfiguration"=>S3ExportConfiguration), params)); aws_config=aws_config)

"""
    get_block(block_address, name)
    get_block(block_address, name, params::Dict{String,<:Any})

Returns a block object at a specified address in a journal. Also returns a proof of the
specified block for verification if DigestTipAddress is provided. For information about the
data contents in a block, see Journal contents in the Amazon QLDB Developer Guide. If the
specified ledger doesn't exist or is in DELETING status, then throws
ResourceNotFoundException. If the specified ledger is in CREATING status, then throws
ResourcePreconditionNotMetException. If no block exists with the specified address, then
throws InvalidParameterException.

# Arguments
- `block_address`: The location of the block that you want to request. An address is an
  Amazon Ion structure that has two fields: strandId and sequenceNo. For example:
  {strandId:\"BlFTjlSXze9BIh1KOszcE3\",sequenceNo:14}.
- `name`: The name of the ledger.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"DigestTipAddress"`: The latest block location covered by the digest for which to
  request a proof. An address is an Amazon Ion structure that has two fields: strandId and
  sequenceNo. For example: {strandId:\"BlFTjlSXze9BIh1KOszcE3\",sequenceNo:49}.
"""
get_block(BlockAddress, name; aws_config::AbstractAWSConfig=global_aws_config()) = qldb("POST", "/ledgers/$(name)/block", Dict{String, Any}("BlockAddress"=>BlockAddress); aws_config=aws_config)
get_block(BlockAddress, name, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = qldb("POST", "/ledgers/$(name)/block", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("BlockAddress"=>BlockAddress), params)); aws_config=aws_config)

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

Returns the digest of a ledger at the latest committed block in the journal. The response
includes a 256-bit hash value and a block address.

# Arguments
- `name`: The name of the ledger.

"""
get_digest(name; aws_config::AbstractAWSConfig=global_aws_config()) = qldb("POST", "/ledgers/$(name)/digest"; aws_config=aws_config)
get_digest(name, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = qldb("POST", "/ledgers/$(name)/digest", params; aws_config=aws_config)

"""
    get_revision(block_address, document_id, name)
    get_revision(block_address, document_id, name, params::Dict{String,<:Any})

Returns a revision data object for a specified document ID and block address. Also returns
a proof of the specified revision for verification if DigestTipAddress is provided.

# Arguments
- `block_address`: The block location of the document revision to be verified. An address
  is an Amazon Ion structure that has two fields: strandId and sequenceNo. For example:
  {strandId:\"BlFTjlSXze9BIh1KOszcE3\",sequenceNo:14}.
- `document_id`: The UUID (represented in Base62-encoded text) of the document to be
  verified.
- `name`: The name of the ledger.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"DigestTipAddress"`: The latest block location covered by the digest for which to
  request a proof. An address is an Amazon Ion structure that has two fields: strandId and
  sequenceNo. For example: {strandId:\"BlFTjlSXze9BIh1KOszcE3\",sequenceNo:49}.
"""
get_revision(BlockAddress, DocumentId, name; aws_config::AbstractAWSConfig=global_aws_config()) = qldb("POST", "/ledgers/$(name)/revision", Dict{String, Any}("BlockAddress"=>BlockAddress, "DocumentId"=>DocumentId); aws_config=aws_config)
get_revision(BlockAddress, DocumentId, name, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = qldb("POST", "/ledgers/$(name)/revision", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("BlockAddress"=>BlockAddress, "DocumentId"=>DocumentId), params)); aws_config=aws_config)

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

Returns an array of all Amazon QLDB journal stream descriptors for a given ledger. The
output of each stream descriptor includes the same details that are returned by
DescribeJournalKinesisStream. This action does not return any expired journal streams. For
more information, see Expiration for terminal streams in the Amazon QLDB Developer Guide.
This action returns a maximum of MaxResults items. It is paginated so that you can retrieve
all the items by calling ListJournalKinesisStreamsForLedger multiple times.

# Arguments
- `name`: The name of the ledger.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"max_results"`: The maximum number of results to return in a single
  ListJournalKinesisStreamsForLedger request. (The actual number of results returned might be
  fewer.)
- `"next_token"`: A pagination token, indicating that you want to retrieve the next page of
  results. If you received a value for NextToken in the response from a previous
  ListJournalKinesisStreamsForLedger call, you should use that value as input here.
"""
list_journal_kinesis_streams_for_ledger(name; aws_config::AbstractAWSConfig=global_aws_config()) = qldb("GET", "/ledgers/$(name)/journal-kinesis-streams"; aws_config=aws_config)
list_journal_kinesis_streams_for_ledger(name, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = qldb("GET", "/ledgers/$(name)/journal-kinesis-streams", params; aws_config=aws_config)

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

Returns an array of journal export job descriptions for all ledgers that are associated
with the current AWS account and Region. This action returns a maximum of MaxResults items,
and is paginated so that you can retrieve all the items by calling ListJournalS3Exports
multiple times. This action does not return any expired export jobs. For more information,
see Export job expiration in the Amazon QLDB Developer Guide.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"max_results"`: The maximum number of results to return in a single ListJournalS3Exports
  request. (The actual number of results returned might be fewer.)
- `"next_token"`: A pagination token, indicating that you want to retrieve the next page of
  results. If you received a value for NextToken in the response from a previous
  ListJournalS3Exports call, then you should use that value as input here.
"""
list_journal_s3_exports(; aws_config::AbstractAWSConfig=global_aws_config()) = qldb("GET", "/journal-s3-exports"; aws_config=aws_config)
list_journal_s3_exports(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = qldb("GET", "/journal-s3-exports", params; aws_config=aws_config)

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

Returns an array of journal export job descriptions for a specified ledger. This action
returns a maximum of MaxResults items, and is paginated so that you can retrieve all the
items by calling ListJournalS3ExportsForLedger multiple times. This action does not return
any expired export jobs. For more information, see Export job expiration in the Amazon QLDB
Developer Guide.

# Arguments
- `name`: The name of the ledger.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"max_results"`: The maximum number of results to return in a single
  ListJournalS3ExportsForLedger request. (The actual number of results returned might be
  fewer.)
- `"next_token"`: A pagination token, indicating that you want to retrieve the next page of
  results. If you received a value for NextToken in the response from a previous
  ListJournalS3ExportsForLedger call, then you should use that value as input here.
"""
list_journal_s3_exports_for_ledger(name; aws_config::AbstractAWSConfig=global_aws_config()) = qldb("GET", "/ledgers/$(name)/journal-s3-exports"; aws_config=aws_config)
list_journal_s3_exports_for_ledger(name, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = qldb("GET", "/ledgers/$(name)/journal-s3-exports", params; aws_config=aws_config)

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

Returns an array of ledger summaries that are associated with the current AWS account and
Region. This action returns a maximum of 100 items and is paginated so that you can
retrieve all the items by calling ListLedgers multiple times.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"max_results"`: The maximum number of results to return in a single ListLedgers request.
  (The actual number of results returned might be fewer.)
- `"next_token"`: A pagination token, indicating that you want to retrieve the next page of
  results. If you received a value for NextToken in the response from a previous ListLedgers
  call, then you should use that value as input here.
"""
list_ledgers(; aws_config::AbstractAWSConfig=global_aws_config()) = qldb("GET", "/ledgers"; aws_config=aws_config)
list_ledgers(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = qldb("GET", "/ledgers", params; aws_config=aws_config)

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

Returns all tags for a specified Amazon QLDB resource.

# Arguments
- `resource_arn`: The Amazon Resource Name (ARN) for which to list the tags. For example:
  arn:aws:qldb:us-east-1:123456789012:ledger/exampleLedger

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

"""
    stream_journal_to_kinesis(inclusive_start_time, kinesis_configuration, role_arn, stream_name, name)
    stream_journal_to_kinesis(inclusive_start_time, kinesis_configuration, role_arn, stream_name, name, params::Dict{String,<:Any})

Creates a journal stream for a given Amazon QLDB ledger. The stream captures every document
revision that is committed to the ledger's journal and delivers the data to a specified
Amazon Kinesis Data Streams resource.

# Arguments
- `inclusive_start_time`: The inclusive start date and time from which to start streaming
  journal data. This parameter must be in ISO 8601 date and time format and in Universal
  Coordinated Time (UTC). For example: 2019-06-13T21:36:34Z. The InclusiveStartTime cannot be
  in the future and must be before ExclusiveEndTime. If you provide an InclusiveStartTime
  that is before the ledger's CreationDateTime, QLDB effectively defaults it to the ledger's
  CreationDateTime.
- `kinesis_configuration`: The configuration settings of the Kinesis Data Streams
  destination for your stream request.
- `role_arn`: The Amazon Resource Name (ARN) of the IAM role that grants QLDB permissions
  for a journal stream to write data records to a Kinesis Data Streams resource.
- `stream_name`: The name that you want to assign to the QLDB journal stream. User-defined
  names can help identify and indicate the purpose of a stream. Your stream name must be
  unique among other active streams for a given ledger. Stream names have the same naming
  constraints as ledger names, as defined in Quotas in Amazon QLDB in the Amazon QLDB
  Developer Guide.
- `name`: The name of the ledger.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"ExclusiveEndTime"`: The exclusive date and time that specifies when the stream ends. If
  you don't define this parameter, the stream runs indefinitely until you cancel it. The
  ExclusiveEndTime must be in ISO 8601 date and time format and in Universal Coordinated Time
  (UTC). For example: 2019-06-13T21:36:34Z.
- `"Tags"`: The key-value pairs to add as tags to the stream that you want to create. Tag
  keys are case sensitive. Tag values are case sensitive and can be null.
"""
stream_journal_to_kinesis(InclusiveStartTime, KinesisConfiguration, RoleArn, StreamName, name; aws_config::AbstractAWSConfig=global_aws_config()) = qldb("POST", "/ledgers/$(name)/journal-kinesis-streams", Dict{String, Any}("InclusiveStartTime"=>InclusiveStartTime, "KinesisConfiguration"=>KinesisConfiguration, "RoleArn"=>RoleArn, "StreamName"=>StreamName); aws_config=aws_config)
stream_journal_to_kinesis(InclusiveStartTime, KinesisConfiguration, RoleArn, StreamName, name, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = qldb("POST", "/ledgers/$(name)/journal-kinesis-streams", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("InclusiveStartTime"=>InclusiveStartTime, "KinesisConfiguration"=>KinesisConfiguration, "RoleArn"=>RoleArn, "StreamName"=>StreamName), params)); aws_config=aws_config)

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

Adds one or more tags to a specified Amazon QLDB resource. A resource can have up to 50
tags. If you try to create more than 50 tags for a resource, your request fails and returns
an error.

# Arguments
- `tags`: The key-value pairs to add as tags to the specified QLDB resource. Tag keys are
  case sensitive. If you specify a key that already exists for the resource, your request
  fails and returns an error. Tag values are case sensitive and can be null.
- `resource_arn`: The Amazon Resource Name (ARN) to which you want to add the tags. For
  example:  arn:aws:qldb:us-east-1:123456789012:ledger/exampleLedger

"""
tag_resource(Tags, resourceArn; aws_config::AbstractAWSConfig=global_aws_config()) = qldb("POST", "/tags/$(resourceArn)", Dict{String, Any}("Tags"=>Tags); aws_config=aws_config)
tag_resource(Tags, resourceArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = qldb("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 one or more tags from a specified Amazon QLDB resource. You can specify up to 50
tag keys to remove.

# Arguments
- `resource_arn`: The Amazon Resource Name (ARN) from which to remove the tags. For
  example:  arn:aws:qldb:us-east-1:123456789012:ledger/exampleLedger
- `tag_keys`: The list of tag keys to remove.

"""
untag_resource(resourceArn, tagKeys; aws_config::AbstractAWSConfig=global_aws_config()) = qldb("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()) = qldb("DELETE", "/tags/$(resourceArn)", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("tagKeys"=>tagKeys), params)); aws_config=aws_config)

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

Updates properties on a ledger.

# Arguments
- `name`: The name of the ledger.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"DeletionProtection"`: The flag that prevents a ledger from being deleted by any user.
  If not provided on ledger creation, this feature is enabled (true) by default. If deletion
  protection is enabled, you must first disable it before you can delete the ledger. You can
  disable it by calling the UpdateLedger operation to set the flag to false.
"""
update_ledger(name; aws_config::AbstractAWSConfig=global_aws_config()) = qldb("PATCH", "/ledgers/$(name)"; aws_config=aws_config)
update_ledger(name, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = qldb("PATCH", "/ledgers/$(name)", params; aws_config=aws_config)

"""
    update_ledger_permissions_mode(permissions_mode, name)
    update_ledger_permissions_mode(permissions_mode, name, params::Dict{String,<:Any})

Updates the permissions mode of a ledger.  Before you switch to the STANDARD permissions
mode, you must first create all required IAM policies and table tags to avoid disruption to
your users. To learn more, see Migrating to the standard permissions mode in the Amazon
QLDB Developer Guide.

# Arguments
- `permissions_mode`: The permissions mode to assign to the ledger. This parameter can have
  one of the following values:    ALLOW_ALL: A legacy permissions mode that enables access
  control with API-level granularity for ledgers. This mode allows users who have the
  SendCommand API permission for this ledger to run all PartiQL commands (hence, ALLOW_ALL)
  on any tables in the specified ledger. This mode disregards any table-level or
  command-level IAM permissions policies that you create for the ledger.    STANDARD:
  (Recommended) A permissions mode that enables access control with finer granularity for
  ledgers, tables, and PartiQL commands. By default, this mode denies all user requests to
  run any PartiQL commands on any tables in this ledger. To allow PartiQL commands to run,
  you must create IAM permissions policies for specific table resources and PartiQL actions,
  in addition to the SendCommand API permission for the ledger. For information, see Getting
  started with the standard permissions mode in the Amazon QLDB Developer Guide.    We
  strongly recommend using the STANDARD permissions mode to maximize the security of your
  ledger data.
- `name`: The name of the ledger.

"""
update_ledger_permissions_mode(PermissionsMode, name; aws_config::AbstractAWSConfig=global_aws_config()) = qldb("PATCH", "/ledgers/$(name)/permissions-mode", Dict{String, Any}("PermissionsMode"=>PermissionsMode); aws_config=aws_config)
update_ledger_permissions_mode(PermissionsMode, name, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = qldb("PATCH", "/ledgers/$(name)/permissions-mode", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("PermissionsMode"=>PermissionsMode), params)); aws_config=aws_config)


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

"""
    AbstractInterpreter

An abstract base class that allows multiple dispatch to determine the method of
executing Julia code.  The native Julia LLVM pipeline is enabled by using the
`NativeInterpreter` concrete instantiation of this abstract class, others can be
swapped in as long as they follow the AbstractInterpreter API.

All AbstractInterpreters are expected to provide at least the following methods:

- InferenceParams(interp) - return an `InferenceParams` instance
- OptimizationParams(interp) - return an `OptimizationParams` instance
- get_world_counter(interp) - return the world age for this interpreter
- get_inference_cache(interp) - return the runtime inference cache
"""
abstract type AbstractInterpreter; end

"""
    InferenceResult

A type that represents the result of running type inference on a chunk of code.
"""
mutable struct InferenceResult
    linfo::MethodInstance
    argtypes::Vector{Any}
    overridden_by_const::BitVector
    result # ::Type, or InferenceState if WIP
    src #::Union{CodeInfo, OptimizationState, Nothing} # if inferred copy is available
    function InferenceResult(linfo::MethodInstance, given_argtypes = nothing)
        argtypes, overridden_by_const = matching_cache_argtypes(linfo, given_argtypes)
        return new(linfo, argtypes, overridden_by_const, Any, nothing)
    end
end

"""
    OptimizationParams

Parameters that control optimizer operation.
"""
struct OptimizationParams
    inlining::Bool              # whether inlining is enabled
    inline_cost_threshold::Int  # number of CPU cycles beyond which it's not worth inlining
    inline_nonleaf_penalty::Int # penalty for dynamic dispatch
    inline_tupleret_bonus::Int  # extra willingness for non-isbits tuple return types
    inline_error_path_cost::Int # cost of (un-optimized) calls in blocks that throw

    # Duplicating for now because optimizer inlining requires it.
    # Keno assures me this will be removed in the near future
    MAX_METHODS::Int
    MAX_TUPLE_SPLAT::Int
    MAX_UNION_SPLITTING::Int

    function OptimizationParams(;
            inlining::Bool = inlining_enabled(),
            inline_cost_threshold::Int = 100,
            inline_nonleaf_penalty::Int = 1000,
            inline_tupleret_bonus::Int = 400,
            inline_error_path_cost::Int = 20,
            max_methods::Int = 3,
            tuple_splat::Int = 32,
            union_splitting::Int = 4,
        )
        return new(
            inlining,
            inline_cost_threshold,
            inline_nonleaf_penalty,
            inline_tupleret_bonus,
            inline_error_path_cost,
            max_methods,
            tuple_splat,
            union_splitting,
        )
    end
end

"""
    InferenceParams

Parameters that control type inference operation.
"""
struct InferenceParams
    ipo_constant_propagation::Bool
    aggressive_constant_propagation::Bool

    # don't consider more than N methods. this trades off between
    # compiler performance and generated code performance.
    # typically, considering many methods means spending lots of time
    # obtaining poor type information.
    # It is important for N to be >= the number of methods in the error()
    # function, so we can still know that error() is always Bottom.
    MAX_METHODS::Int
    # the maximum number of union-tuples to swap / expand
    # before computing the set of matching methods
    MAX_UNION_SPLITTING::Int
    # the maximum number of union-tuples to swap / expand
    # when inferring a call to _apply
    MAX_APPLY_UNION_ENUM::Int

    # parameters limiting large (tuple) types
    TUPLE_COMPLEXITY_LIMIT_DEPTH::Int

    # when attempting to inlining _apply, abort the optimization if the tuple
    # contains more than this many elements
    MAX_TUPLE_SPLAT::Int

    function InferenceParams(;
            ipo_constant_propagation::Bool = true,
            aggressive_constant_propagation::Bool = false,
            max_methods::Int = 3,
            union_splitting::Int = 4,
            apply_union_enum::Int = 8,
            tupletype_depth::Int = 3,
            tuple_splat::Int = 32,
        )
        return new(
            ipo_constant_propagation,
            aggressive_constant_propagation,
            max_methods,
            union_splitting,
            apply_union_enum,
            tupletype_depth,
            tuple_splat,
        )
    end
end

"""
    NativeInterpreter

This represents Julia's native type inference algorithm and codegen backend.
It contains many parameters used by the compilation pipeline.
"""
struct NativeInterpreter <: AbstractInterpreter
    # Cache of inference results for this particular interpreter
    cache::Vector{InferenceResult}
    # The world age we're working inside of
    world::UInt

    # Parameters for inference and optimization
    inf_params::InferenceParams
    opt_params::OptimizationParams

    function NativeInterpreter(world::UInt = get_world_counter();
                               inf_params = InferenceParams(),
                               opt_params = OptimizationParams(),
                               )
        # Sometimes the caller is lazy and passes typemax(UInt).
        # we cap it to the current world age
        if world == typemax(UInt)
            world = get_world_counter()
        end

        # If they didn't pass typemax(UInt) but passed something more subtly
        # incorrect, fail out loudly.
        @assert world <= get_world_counter()

        return new(
            # Initially empty cache
            Vector{InferenceResult}(),

            # world age counter
            world,

            # parameters for inference and optimization
            inf_params,
            opt_params,
        )
    end
end

# Quickly and easily satisfy the AbstractInterpreter API contract
InferenceParams(ni::NativeInterpreter) = ni.inf_params
OptimizationParams(ni::NativeInterpreter) = ni.opt_params
get_world_counter(ni::NativeInterpreter) = ni.world
get_inference_cache(ni::NativeInterpreter) = ni.cache

code_cache(ni::NativeInterpreter) = WorldView(GLOBAL_CI_CACHE, ni.world)

"""
    lock_mi_inference(ni::NativeInterpreter, mi::MethodInstance)

Hint that `mi` is in inference to help accelerate bootstrapping. This helps limit the amount of wasted work we might do when inference is working on initially inferring itself by letting us detect when inference is already in progress and not running a second copy on it. This creates a data-race, but the entry point into this code from C (jl_type_infer) already includes detection and restriction on recursion, so it is hopefully mostly a benign problem (since it should really only happen during the first phase of bootstrapping that we encounter this flag).
"""
lock_mi_inference(ni::NativeInterpreter, mi::MethodInstance) = (mi.inInference = true; nothing)

"""
    See lock_mi_inference
"""
unlock_mi_inference(ni::NativeInterpreter, mi::MethodInstance) = (mi.inInference = false; nothing)

"""
Emit an analysis remark during inference for the current line (`sv.pc`). These annotations are ignored
by the native interpreter, but can be used by external tooling to annotate
inference results.
"""
add_remark!(ni::NativeInterpreter, sv, s) = nothing

may_optimize(ni::NativeInterpreter) = true
may_compress(ni::NativeInterpreter) = true
may_discard_trees(ni::NativeInterpreter) = true

max_stars_repo_name: caleb-allen/julialang

max_issues_repo_name: guptakmohit/julia

max_forks_repo_name: guptakmohit/julia