text:
function f(x)
    if x < 8
        return 0
    end
    ans = (x ÷ 3) - 2
    return ans + f((x ÷ 3) - 2)
end

a = [140170,75120,75645,134664,124948,137630,146662,116881,120030,94332,50473,59361,128237,84894,51368,128802,57275,129235,113481,66378,55842,90548,107696,53603,130458,80306,120820,131313,100303,59224,123369,140584,60642,68184,103101,82278,51968,51048,98139,60498,127082,71197,109478,71286,84840,141305,51800,72352,93147,73549,122739,62363,58453,59000,63564,63424,51053,120826,123337,130824,59053,77983,68977,67126,96051,53024,145647,139343,113236,59396,146174,148622,83384,86938,100673,80757,107675,147417,124538,136463,104609,149559,136037,54997,139674,101638,65739,70029,143847,122035,66256,78087,105045,108867,99630,127173,139021,139759,134171,104869]
println(sum(f.(a)))

max_stars_repo_path: Day 1/Day 1 Part 2.jl

max_issues_repo_path: Day 1/Day 1 Part 2.jl

max_forks_repo_path: Day 1/Day 1 Part 2.jl


text:
isinstalled(pkg) = try
    isa(Pkg.installed(pkg), VersionNumber)
  catch
    return false
end

ext: jl


text:
using JSON
using Random

"""
    importCorpus(path::String)

Returns a string containing the whole file in one line.
"""
function importCorpus(path::String)

    full_text = ""

    open(path, "r") do file

        line = 0

        print("\nReading file: <")

        while !eof(file)

            s = readline(file)
            line += 1

            full_text *= s[1:end]

            if line % 10000 == 0
                print("=")
                break
            end # if

        end # while

        print(">\n")

    end # do

    full_text = uppercase(full_text)

    # Split that really long bit of text.
    return [
        full_text[count*500:(count+1)*500]
        for count = 1:(round(Int, length(full_text) / 500 - length(full_text) % 500)-1)
    ]

end # function

"""
    importTraining(schema::String, text::String)

`schema`: A string containing the path to the schema file\n
`text`: A string containing the path to the text file
"""
function importTraining(schema::String, text::String)

    println("Importing JSON dict from: ", schema)
    training_data = JSON.parsefile(schema)

    println("Importing Corpus from: ", text)
    split_text = importCorpus(text)

    training_data["Supervised"]["decrypts"] = split_text

    #== CREATE THE TRAINING DATA ==#

    # Import ciphers
    println("MAKE SURE THAT ALL CIPHERS ARE LOADED MODULES. [if using Allforhumans, this won't be a problem]")

    ciphers = 4
    alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    encrypt_format = ("encrypts" => [], "steps" => [], "text_id" => [])

    # Single layer

    for cipher in 1:ciphers

        _encrypts = []
        push!(encrypt_format, training_data["Supervised"]["encrypts"])
        append!(cipher, training_data["Supervised"]["encrypts"][end]["steps"]) # 1 = AtBash, 2 = ROT13 etc.

        for text in 1:length(training_data["Supervised"]["decrypts"])

            if cipher == 1 # AtBash
                if rand(1:6) == 6
                    append!(atbash(training_data["Supervised"]["decrypts"][text], alphabet), _encrypts)
                    append!(text, training_data["Supervised"]["encrypts"][end]["text_id"])
                end # if
            end # if

        end # for

        append!(_encrypts, training_data["Supervised"]["encrypts"][end]["encrypts"])

    end # for

    # Two layers

    # Three layers

    return training_data

end # function

importTraining(
    "AI\\Texts\\smaller_schema.json",
    "AI\\Texts\\download\\download\\LOB_COCOA\\lob.txt",
)

max_stars_repo_name: Squalm/Cipher-Tools

max_issues_repo_name: Squalm/Cipher-Tools

max_forks_repo_name: Squalm/Cipher-Tools


text:
using Gnuplot
function vline_at(x; color="black", lw = 2)
    "set arrow from $(x), graph 0 to $(x), graph 1 nohead lc rgb '$(color)' lw $(lw)"
end
@gp [3,3] [0,5] "w impulse notit lc 'red'" # vertical line from 0 to 5 at x=3
@gp :- xrange =(0,4) yrange=(-1,6)
# full vertical line at x = 2
@gp :- vline_at(2; lw = 3)
@gp :- vline_at(1; color = "orange")
save(term ="pngcairo size 600,400", output ="vlines.png")

max_stars_repo_name: lazarusA/gnuplot-examples

max_issues_repo_name: lazarusA/gnuplot-examples

max_forks_repo_name: lazarusA/gnuplot-examples


text:
# 2021-11-07T14:01:01
if Base.VERSION >= v"1.4.2" && ccall(:jl_generating_output, Cint, ()) == 1
  var"#precompile#int"(f, args...) = f(args...)
  var"#precompile"(f, args...) =
    Base.precompile(Tuple{typeof(var"#precompile#int"), f, args...})

  # Core
  # total time: 0.0

  # Base.MainInclude
  # total time: 0.0

  # Base.Sort
  # total time: 0.014884936

  var"#precompile"(typeof(sortperm),Vector{Symbol})   # time: 0.007626647
  let fbody = try __lookup_kwbody__(which(sortperm, (Vector{Symbol},))) catch missing end
        if !ismissing(fbody)
            var"#precompile"(fbody, Base.Sort.QuickSortAlg,Function,Function,Nothing,Base.Order.ForwardOrdering,typeof(sortperm),Vector{Symbol})
        end
    end   # time: 0.007258289

  # Base.Iterators
  # total time: 0.013343715999999999

  var"#precompile"(typeof(iterate),Base.Iterators.Zip{Tuple{Vector{Symbol}, Vector{Expr}}})   # time: 0.005042564
  var"#precompile"(typeof(iterate),Base.Iterators.Drop{Vector{Pair{Symbol, DataType}}})   # time: 0.003272639
  var"#precompile"(typeof(iterate),Base.Iterators.Zip{Tuple{Vector{Symbol}, Vector{Expr}}},Tuple{Int64, Int64})   # time: 0.00317269
  var"#precompile"(typeof(zip),Vector{Symbol},Vararg{Any, N} where N)   # time: 0.001855823

  # Base.Broadcast
  # total time: 0.032511912

  var"#precompile"(typeof(copy),Base.Broadcast.Broadcasted{Base.Broadcast.Style{Tuple}, Nothing, typeof(in), Tuple{NTuple{4, Symbol}, Tuple{Tuple{Symbol, Symbol, Symbol}}}})   # time: 0.025055496
  var"#precompile"(typeof(copy),Base.Broadcast.Broadcasted{Base.Broadcast.Style{Tuple}, Nothing, typeof(getindex), Tuple{Tuple{NamedTuple{(:a, :b, :c), Tuple{Nothing, Int64, Float64}}}, Tuple{Symbol, Symbol}}})   # time: 0.006404012
  var"#precompile"(Type{Base.Broadcast.Broadcasted{Base.Broadcast.Style{Tuple}, Axes, F, Args} where {Axes, F, Args<:Tuple}},typeof(in),Tuple{NTuple{4, Symbol}, Tuple{Tuple{Symbol, Symbol, Symbol}}})   # time: 0.001052404

  # Base
  # total time: 0.373312223

  var"#precompile"(Type{Base.IteratorSize},Base.Iterators.Zip{Tuple{Vector{Symbol}, Vector{Expr}}})   # time: 0.028020676
  var"#precompile"(Type{Base.IteratorSize},Base.Iterators.Zip{Tuple{Vector{Symbol}, Vector{Symbol}}})   # time: 0.025203701
  var"#precompile"(Type{Base.IteratorSize},Base.Iterators.Zip{Tuple{Vector{Symbol}, Vector{Any}}})   # time: 0.01814107
  var"#precompile"(typeof(getindex),Vector{Symbol},Vector{Int64})   # time: 0.01510981
  var"#precompile"(typeof(==),Vector{Pair{Symbol, Union{Nothing, Int64}}},Vector{Pair{Symbol, Union{Nothing, Int64}}})   # time: 0.012717317
  var"#precompile"(typeof(Base.copymutable),Vector{Pair{Symbol, DataType}})   # time: 0.012320287
  var"#precompile"(Type{Pair},Symbol,Float64)   # time: 0.010663889
  var"#precompile"(typeof(Base.vect),Pair{Symbol, Nothing},Vararg{Any, N} where N)   # time: 0.009562518
  var"#precompile"(typeof(Base.setindex_widen_up_to),Vector{Expr},Symbol,Int64)   # time: 0.008246483
  var"#precompile"(typeof(foldl),Function,Tuple{Bool, Bool, Bool})   # time: 0.007966861
  var"#precompile"(typeof(foldl),Function,NTuple{4, Bool})   # time: 0.006025352
  let fbody = try __lookup_kwbody__(which(mapfoldl, (Function,Function,NTuple{4, Bool},))) catch missing end
        if !ismissing(fbody)
            var"#precompile"(fbody, Base._InitialValue,typeof(mapfoldl),Function,Function,NTuple{4, Bool})
        end
    end   # time: 0.005161738
  var"#precompile"(typeof(getindex),Vector{DataType},Vector{Int64})   # time: 0.004795045
  var"#precompile"(typeof(Base.setindex_widen_up_to),Vector{Symbol},Expr,Int64)   # time: 0.004716734
  let fbody = try __lookup_kwbody__(which(mapfoldl, (Function,Function,Tuple{Bool, Bool, Bool},))) catch missing end
        if !ismissing(fbody)
            var"#precompile"(fbody, Base._InitialValue,typeof(mapfoldl),Function,Function,Tuple{Bool, Bool, Bool})
        end
    end   # time: 0.004602275
  var"#precompile"(typeof(collect),Base.Generator{Vector{Symbol}, Type{QuoteNode}})   # time: 0.004223247
  var"#precompile"(typeof(copyto!),Vector{Pair{Symbol, Union{Nothing, Int64}}},Tuple{Pair{Symbol, Nothing}, Pair{Symbol, Int64}})   # time: 0.003908387
  var"#precompile"(typeof(Base.setindex_widen_up_to),Vector{Expr},Expr,Int64)   # time: 0.003778313
  var"#precompile"(typeof(repr),Type)   # time: 0.003444675
  var"#precompile"(typeof(string),String,Tuple{Symbol, Symbol})   # time: 0.003264028
  var"#precompile"(typeof(Base.mapfoldl_impl),typeof(identity),typeof(&),Base._InitialValue,NTuple{4, Bool})   # time: 0.002810136
  var"#precompile"(typeof(Base.promote_typeof),Pair{Symbol, Nothing},Pair{Symbol, Int64})   # time: 0.002365867
  var"#precompile"(typeof(Base.push_widen),Vector{Pair{Symbol, DataType}},Any)   # time: 0.002126327
  var"#precompile"(typeof(==),Tuple{Symbol, Symbol},Tuple{Symbol, Symbol})   # time: 0.00204966
  var"#precompile"(Type{Base.IteratorSize},Base.Iterators.Enumerate{Core.SimpleVector})   # time: 0.001976853
  var"#precompile"(typeof(Base._array_for),Type{Expr},Base.Iterators.Zip{Tuple{Vector{Symbol}, Vector{Any}}},Base.HasShape{1})   # time: 0.001738193
  var"#precompile"(typeof(push!),Vector{Pair{Symbol, DataType}},Pair{Symbol, DataType})   # time: 0.001541832
  var"#precompile"(typeof(Base.setindex_widen_up_to),Vector{Symbol},Symbol,Int64)   # time: 0.001493033
  var"#precompile"(Type{Pair},Symbol,Type)   # time: 0.001342879
  var"#precompile"(typeof(==),Tuple{Int64, Float64},Tuple{Int64, Float64})   # time: 0.001154466
  var"#precompile"(typeof(Base._array_for),Type{Expr},Base.Iterators.Zip{Tuple{Vector{Symbol}, Vector{Symbol}}},Base.HasShape{1})   # time: 0.001013987

  # ArgumentModes.Impl
  # total time: 0.740025636

  var"#precompile"(typeof(~),Mode[==, :a => Int64],Mode[==, :a])   # time: 0.20711419
  var"#precompile"(typeof(which(ArgumentModes.Impl._Mode_instance_g,(Any,Any,)).generator.gen),Any,Any,Any)   # time: 0.15569615
  var"#precompile"(typeof(show),IOBuffer,Type{Mode[==, :a => Float64, :b => String, :c, :d => Int64]})   # time: 0.03318364
  var"#precompile"(typeof(checkmode),Mode[==, :a, :b => Int64, :c => Float64],typeof(==),Symbol,Symbol)   # time: 0.027065475
  var"#precompile"(typeof(checkmode),Mode[==, :a, :b => Int64, :c => Float64],typeof(|),Symbol,Symbol)   # time: 0.023050297
  var"#precompile"(typeof(checkmode),Mode[==, :a, :b => Int64, :c => Float64],Symbol,Symbol,Symbol)   # time: 0.021079471
  var"#precompile"(typeof(checkmode),Mode[==, :a, :b => Int64, :c => Float64],typeof(!),Symbol,Symbol,Symbol)   # time: 0.020862447
  var"#precompile"(typeof(~),Mode[==, :a],Mode[==, :b])   # time: 0.017923424
  var"#precompile"(typeof(checkmode),Function,Mode[==, :a, :b => Int64, :c => Float64],typeof(==),Symbol,Symbol,Vararg{Symbol, N} where N)   # time: 0.016142227
  var"#precompile"(typeof(which(ArgumentModes.Impl._extract_symbols_from_args_g,(Any,)).generator.gen),Any,Any)   # time: 0.013818592
  var"#precompile"(typeof(checkmode),Mode[==, :a, :b => Int64, :c => Float64],typeof(==),Symbol,Symbol,Symbol,Vararg{Symbol, N} where N)   # time: 0.013255158
  var"#precompile"(typeof(checkmode),Mode[==, :a, :b => Int64, :c => Float64],typeof(|),Symbol,Symbol,Symbol)   # time: 0.011424678
  var"#precompile"(Type{Pair},Mode[==, :m2],String)   # time: 0.009898064
  var"#precompile"(typeof(which(ArgumentModes.Impl._getindex_g,(Any,Any,Any,)).generator.gen),Any,Any,Any,Any)   # time: 0.009702764
  var"#precompile"(typeof(getindex),Mode[==, :a, :b => Int64],Symbol,Symbol)   # time: 0.009164862
  var"#precompile"(typeof(~),Mode[==, :m1 => Int64],Mode[==, :m2 => Int64])   # time: 0.00815442
  var"#precompile"(typeof(~),Mode[==, :m1],Mode[==, :m2 => String])   # time: 0.007593852
  var"#precompile"(typeof(checkmode),Mode[==, :a, :b => Int64, :c => Float64],typeof(!),Symbol,Symbol)   # time: 0.006211011
  var"#precompile"(Type{Pair},Mode[==, :m2],Int64)   # time: 0.005805799
  isdefined(ArgumentModes.Impl, Symbol("#f#19")) && var"#precompile"(getfield(ArgumentModes.Impl, Symbol("#f#19")),Pair{Symbol, DataType})   # time: 0.003805427
  var"#precompile"(typeof(ArgumentModes.Impl._Mode_instance_g),Val{(:a, :b, :c, :d)},Tuple{Pair{Symbol, Float64}, Pair{Symbol, String}, Symbol, Pair{Symbol, Int64}})   # time: 0.002551479
  var"#precompile"(typeof(getindex),Type{Mode},Symbol,Pair{Symbol, DataType},Pair{Symbol, Union})   # time: 0.001971067
  var"#precompile"(typeof(ArgumentModes.Impl._extract_symbols_from_args_g),Tuple{Pair{Symbol, Float64}, Pair{Symbol, String}, Symbol, Pair{Symbol, Int64}})   # time: 0.001938178
  var"#precompile"(typeof(show),IOBuffer,Type{Mode})   # time: 0.001661923
  var"#precompile"(typeof(show),IOBuffer,Type{Mode[:a => Int64, :b => Float64, :c, :d => String]})   # time: 0.001531112
  var"#precompile"(Type{Mode},Pair{Symbol, Nothing})   # time: 0.001299248
  var"#precompile"(typeof(pairs),Mode[==, :a, :b => Int64])   # time: 0.001058294

end


text:
using Sockets, MbedTLS, HTTP

capath = "/var/folders/0s/p7ggmk2s339dq2xbnzf1wm3r0000gn/T/tmpEwcTmO"
certpath = "/var/folders/0s/p7ggmk2s339dq2xbnzf1wm3r0000gn/T/tmpY3ZlRI"
keypath = "/var/folders/0s/p7ggmk2s339dq2xbnzf1wm3r0000gn/T/tmpa7fT14"
conf = MbedTLS.SSLConfig(certpath, keypath)

MbedTLS.config_defaults!(conf)
MbedTLS.authmode!(conf, MbedTLS.MBEDTLS_SSL_VERIFY_REQUIRED)
# MbedTLS.rng!(conf, rng)

# function show_debug(level, filename, number, msg)
#     @show level, filename, number, msg
# end
#
# MbedTLS.dbg!(conf, show_debug)

cacert = MbedTLS.crt_parse_file(capath)
println("capath: ", cacert)
MbedTLS.ca_chain!(conf, cacert)
#
# MbedTLS.setup!(ctx, conf)
# MbedTLS.set_bio!(ctx, sock)
#
# MbedTLS.handshake(ctx)
resp = HTTP.request("GET", "https://localhost:49642/api/v1/pods"; sslconfig=conf)
@show resp
# write(ctx, "GET /api/v1/pods HTTP/1.1\r\nHost: localhost\r\n\r\n")
# buf = String(read(ctx, 1000))
# println(buf)

max_stars_repo_name: pbarker/kubemeta

max_issues_repo_name: pbarker/kubemeta

max_forks_repo_name: pbarker/kubemeta


text:
const TriToeplitz{T} = Tridiagonal{T,Fill{T,1,Tuple{OneToInf{Int}}}}
const ConstRowMatrix{T} = ApplyMatrix{T,typeof(*),<:Tuple{<:AbstractVector,<:AbstractFill{<:Any,2,Tuple{OneTo{Int},OneToInf{Int}}}}}
const PertConstRowMatrix{T} = Hcat{T,<:Tuple{Array{T},<:ConstRowMatrix{T}}}
const InfToeplitz{T} = BandedMatrix{T,<:ConstRowMatrix{T},OneToInf{Int}}
const PertToeplitz{T} = BandedMatrix{T,<:PertConstRowMatrix{T},OneToInf{Int}}

const SymTriPertToeplitz{T} = SymTridiagonal{T,Vcat{T,1,Tuple{Vector{T},Fill{T,1,Tuple{OneToInf{Int}}}}}}
const TriPertToeplitz{T} = Tridiagonal{T,Vcat{T,1,Tuple{Vector{T},Fill{T,1,Tuple{OneToInf{Int}}}}}}
const AdjTriPertToeplitz{T} = Adjoint{T,Tridiagonal{T,Vcat{T,1,Tuple{Vector{T},Fill{T,1,Tuple{OneToInf{Int}}}}}}}
const InfBandedMatrix{T,V<:AbstractMatrix{T}} = BandedMatrix{T,V,OneToInf{Int}}

_prepad(p, a) = Vcat(Zeros(max(p,0)), a)
_prepad(p, a::Zeros{T,1}) where T = Zeros{T}(length(a)+p)
_prepad(p, a::Ones{T,1}) where T = Ones{T}(length(a)+p)
_prepad(p, a::AbstractFill{T,1}) where T = Fill{T}(getindex_value(a), length(a)+p)

function BandedMatrix{T}(kv::Tuple{Vararg{Pair{<:Integer,<:AbstractVector}}},
                         ::NTuple{2,Infinity},
                         (l,u)::NTuple{2,Integer}) where T
    ks = getproperty.(kv, :first)
    l,u = -minimum(ks),maximum(ks)
    rws = Vcat(permutedims.(_prepad.(ks,getproperty.(kv, :second)))...)
    c = zeros(T, l+u+1, length(ks))
    for (k,j) in zip(u .- ks .+ 1,1:length(ks))
        c[k,j] = one(T)
    end
    _BandedMatrix(ApplyArray(*,c,rws), ∞, l, u)
end

# Construct InfToeplitz
function BandedMatrix{T}(kv::Tuple{Vararg{Pair{<:Integer,<:Fill{<:Any,1,Tuple{OneToInf{Int}}}}}},
                         mn::NTuple{2,Infinity},
                         lu::NTuple{2,Integer}) where T
    m,n = mn
    @assert isinf(n)
    l,u = lu
    t = zeros(T, u+l+1)
    for (k,v) in kv
        p = length(v)
        t[u-k+1] = v.value
    end

    return _BandedMatrix(t * Ones{T}(1,∞), m, l, u)
end

function BandedMatrix{T}(kv::Tuple{Vararg{Pair{<:Integer,<:Vcat{<:Any,1,<:Tuple{<:AbstractVector,Fill{<:Any,1,Tuple{OneToInf{Int}}}}}}}},
                         mn::NTuple{2,Infinity},
                         lu::NTuple{2,Integer}) where T
    m,n = mn
    @assert isinf(n)
    l,u = lu
    M = mapreduce(x -> length(x.second.args[1]) + max(0,x.first), max, kv) # number of data rows
    data = zeros(T, u+l+1, M)
    t = zeros(T, u+l+1)
    for (k,v) in kv
        a,b = v.args
        p = length(a)
        t[u-k+1] = b.value
        if k ≤ 0
            data[u-k+1,1:p] = a
            data[u-k+1,p+1:end] .= b.value
        else
            data[u-k+1,k+1:k+p] = a
            data[u-k+1,k+p+1:end] .= b.value
        end
    end

    return _BandedMatrix(Hcat(data, t * Ones{T}(1,∞)), m, l, u)
end

function BandedMatrix(Ac::Adjoint{T,<:InfToeplitz}) where T
    A = parent(Ac)
    l,u = bandwidths(A)
    a = A.data.args[1]
    _BandedMatrix(reverse(conj(a)) * Ones{T}(1,∞), ∞, u, l)
end

function BandedMatrix(Ac::Transpose{T,<:InfToeplitz}) where T
    A = parent(Ac)
    l,u = bandwidths(A)
    a = A.data.args[1]
    _BandedMatrix(reverse(a) * Ones{T}(1,∞), ∞, u, l)
end

function BandedMatrix(Ac::Adjoint{T,<:PertToeplitz}) where T
    A = parent(Ac)
    l,u = bandwidths(A)
    a,b = A.data.args
    Ac_fd = BandedMatrix(_BandedMatrix(Hcat(a, b[:,1:l+1]), size(a,2)+l, l, u)')
    _BandedMatrix(Hcat(Ac_fd.data, reverse(conj(b.args[1])) * Ones{T}(1,∞)), ∞, u, l)
end

function BandedMatrix(Ac::Transpose{T,<:PertToeplitz}) where T
    A = parent(Ac)
    l,u = bandwidths(A)
    a,b = A.data.args
    Ac_fd = BandedMatrix(transpose(_BandedMatrix(Hcat(a, b[:,1:l+1]), size(a,2)+l, l, u)))
    _BandedMatrix(Hcat(Ac_fd.data, reverse(b.args[1]) * Ones{T}(1,∞)), ∞, u, l)
end

for op in (:-, :+)
    @eval begin
        function $op(A::SymTriPertToeplitz{T}, λ::UniformScaling) where T
            TV = promote_type(T,eltype(λ))
            dv = Vcat(convert.(AbstractVector{TV}, A.dv.args)...)
            ev = Vcat(convert.(AbstractVector{TV}, A.ev.args)...)
            SymTridiagonal(broadcast($op, dv, Ref(λ.λ)), ev)
        end
        function $op(λ::UniformScaling, A::SymTriPertToeplitz{V}) where V
            TV = promote_type(eltype(λ),V)
            SymTridiagonal(convert(AbstractVector{TV}, broadcast($op, Ref(λ.λ), A.dv)),
                           convert(AbstractVector{TV}, broadcast($op, A.ev)))
        end
        function $op(A::SymTridiagonal{T,<:AbstractFill}, λ::UniformScaling) where T
            TV = promote_type(T,eltype(λ))
            SymTridiagonal(convert(AbstractVector{TV}, broadcast($op, A.dv, Ref(λ.λ))),
                           convert(AbstractVector{TV}, A.ev))
        end

        function $op(A::TriPertToeplitz{T}, λ::UniformScaling) where T
            TV = promote_type(T,eltype(λ))
            Tridiagonal(Vcat(convert.(AbstractVector{TV}, A.dl.args)...),
                        Vcat(convert.(AbstractVector{TV}, broadcast($op, A.d, λ.λ).args)...),
                        Vcat(convert.(AbstractVector{TV}, A.du.args)...))
        end
        function $op(λ::UniformScaling, A::TriPertToeplitz{V}) where V
            TV = promote_type(eltype(λ),V)
            Tridiagonal(Vcat(convert.(AbstractVector{TV}, broadcast($op, A.dl.args))...),
                        Vcat(convert.(AbstractVector{TV}, broadcast($op, λ.λ, A.d).args)...),
                        Vcat(convert.(AbstractVector{TV}, broadcast($op, A.du.args))...))
        end
        function $op(adjA::AdjTriPertToeplitz{T}, λ::UniformScaling) where T
            A = parent(adjA)
            TV = promote_type(T,eltype(λ))
            Tridiagonal(Vcat(convert.(AbstractVector{TV}, A.du.args)...),
                        Vcat(convert.(AbstractVector{TV}, broadcast($op, A.d, λ.λ).args)...),
                        Vcat(convert.(AbstractVector{TV}, A.dl.args)...))
        end
        function $op(λ::UniformScaling, adjA::AdjTriPertToeplitz{V}) where V
            A = parent(adjA)
            TV = promote_type(eltype(λ),V)
            Tridiagonal(Vcat(convert.(AbstractVector{TV}, broadcast($op, A.du.args))...),
                        Vcat(convert.(AbstractVector{TV}, broadcast($op, λ.λ, A.d).args)...),
                        Vcat(convert.(AbstractVector{TV}, broadcast($op, A.dl.args))...))
        end

        function $op(λ::UniformScaling, A::InfToeplitz{V}) where V
            l,u = bandwidths(A)
            TV = promote_type(eltype(λ),V)
            a = convert(AbstractVector{TV}, $op.(A.data.args[1]))
            a[u+1] += λ.λ
            _BandedMatrix(a*Ones{TV}(1,∞), ∞, l, u)
        end

        function $op(A::InfToeplitz{T}, λ::UniformScaling) where T
            l,u = bandwidths(A)
            TV = promote_type(T,eltype(λ))
            a = TV[Zeros{TV}(max(-u,0)); A.data.args[1]; Zeros{TV}(max(-l,0))]
            a[max(0,u)+1] = $op(a[max(u,0)+1], λ.λ)
            _BandedMatrix(a*Ones{TV}(1,∞), ∞, max(l,0), max(u,0))
        end

        function $op(λ::UniformScaling, A::PertToeplitz{V}) where V
            l,u = bandwidths(A)
            TV = promote_type(eltype(λ),V)
            a, t = convert.(AbstractVector{TV}, A.data.args)
            b = $op.(t.args[1])
            a[u+1,:] += λ.λ
            b[u+1] += λ.λ
            _BandedMatrix(Hcat(a, b*Ones{TV}(1,∞)), ∞, l, u)
        end

        function $op(A::PertToeplitz{T}, λ::UniformScaling) where T
            l,u = bandwidths(A)
            TV = promote_type(T,eltype(λ))
            ã, t = A.data.args
            a = AbstractArray{TV}(ã)
            b = AbstractVector{TV}(t.args[1])
            a[u+1,:] .= $op.(a[u+1,:],λ.λ)
            b[u+1] = $op(b[u+1], λ.λ)
            _BandedMatrix(Hcat(a, b*Ones{TV}(1,∞)), ∞, l, u)
        end
    end
end

####
# Conversions to BandedMatrix
####

function BandedMatrix(A::PertToeplitz{T}, (l,u)::Tuple{Int,Int}) where T
    @assert A.u == u # Not implemented
    a, b = A.data.args
    t = b.args[1] # topelitz part
    t_pad = vcat(t,Zeros(l-A.l))
    data = Hcat([vcat(a,Zeros{T}(l-A.l,size(a,2))) repeat(t_pad,1,l)], t_pad * Ones{T}(1,∞))
    _BandedMatrix(data, ∞, l, u)
end

function BandedMatrix(A::SymTriPertToeplitz{T}, (l,u)::Tuple{Int,Int}) where T
    a,a∞ = A.dv.args
    b,b∞ = A.ev.args
    n = max(length(a), length(b)+1) + 1
    data = zeros(T, l+u+1, n)
    data[u,2:length(b)+1] .= b
    data[u,length(b)+2:end] .= b∞.value
    data[u+1,1:length(a)] .= a
    data[u+1,length(a)+1:end] .= a∞.value
    data[u+2,1:length(b)] .= b
    data[u+2,length(b)+1:end] .= b∞.value
    _BandedMatrix(Hcat(data, [Zeros{T}(u-1); b∞.value; a∞.value; b∞.value; Zeros{T}(l-1)] * Ones{T}(1,∞)), ∞, l, u)
end

function BandedMatrix(A::SymTridiagonal{T,Fill{T,1,Tuple{OneToInf{Int}}}}, (l,u)::Tuple{Int,Int}) where T
    a∞ = A.dv
    b∞ = A.ev
    n = 2
    data = zeros(T, l+u+1, n)
    data[u,2:end] .= b∞.value
    data[u+1,1:end] .= a∞.value
    data[u+2,1:end] .= b∞.value
    _BandedMatrix(Hcat(data, [Zeros{T}(u-1); b∞.value; a∞.value; b∞.value; Zeros{T}(l-1)] * Ones{T}(1,∞)), ∞, l, u)
end

function BandedMatrix(A::TriPertToeplitz{T}, (l,u)::Tuple{Int,Int}) where T
    a,a∞ = A.d.args
    b,b∞ = A.du.args
    c,c∞ = A.dl.args
    n = max(length(a), length(b)+1, length(c)-1) + 1
    data = zeros(T, l+u+1, n)
    data[u,2:length(b)+1] .= b
    data[u,length(b)+2:end] .= b∞.value
    data[u+1,1:length(a)] .= a
    data[u+1,length(a)+1:end] .= a∞.value
    data[u+2,1:length(c)] .= c
    data[u+2,length(c)+1:end] .= c∞.value
    _BandedMatrix(Hcat(data, [Zeros{T}(u-1); b∞.value; a∞.value; c∞.value; Zeros{T}(l-1)] * Ones{T}(1,∞)), ∞, l, u)
end

function BandedMatrix(A::Tridiagonal{T,Fill{T,1,Tuple{OneToInf{Int}}}}, (l,u)::Tuple{Int,Int}) where T
    a∞ = A.d
    b∞ = A.du
    c∞ = A.dl
    n = 2
    data = zeros(T, l+u+1, n)
    data[u,2:end] .= b∞.value
    data[u+1,1:end] .= a∞.value
    data[u+2,1:end] .= c∞.value
    _BandedMatrix(Hcat(data, [Zeros{T}(u-1); b∞.value; a∞.value; c∞.value; Zeros{T}(l-1)] * Ones{T}(1,∞)), ∞, l, u)
end

function InfToeplitz(A::Tridiagonal{T,Fill{T,1,Tuple{OneToInf{Int}}}}, (l,u)::Tuple{Int,Int}) where T
    a∞ = A.d
    b∞ = A.du
    c∞ = A.dl
    _BandedMatrix([Zeros{T}(u-1); b∞.value; a∞.value; c∞.value; Zeros{T}(l-1)] * Ones{T}(1,∞), ∞, l, u)
end

InfToeplitz(A::Tridiagonal{T,Fill{T,1,Tuple{OneToInf{Int}}}}) where T = InfToeplitz(A, bandwidths(A))

####
# Toeplitz layout
####

_pertdata(A::ConstRowMatrix{T}) where T = Array{T}(undef,size(A,1),0)
_pertdata(A::Hcat{T,<:Tuple{Vector{T},<:ConstRowMatrix{T}}}) where T = 1
_pertdata(A::PertConstRowMatrix) = A.args[1]
function _pertdata(A::SubArray)
    P = parent(A)
    kr,jr = parentindices(A)
    dat = _pertdata(P)
    dat[kr,jr ∩ axes(dat,2)]
end

_constrows(A::ConstRowMatrix) = A.args[1]*getindex_value(A.args[2])
_constrows(A::PertConstRowMatrix) = _constrows(A.args[2])
_constrows(A::SubArray) = _constrows(parent(A))[parentindices(A)[1]]

ConstRowMatrix(A::AbstractMatrix{T}) where T = ApplyMatrix(*, A[:,1], Ones{T}(1,size(A,2)))
PertConstRowMatrix(A::AbstractMatrix{T}) where T =
    Hcat(_pertdata(A), ApplyMatrix(*, _constrows(A), Ones{T}(1,size(A,2))))

struct ConstRows <: MemoryLayout end
struct PertConstRows <: MemoryLayout end
MemoryLayout(::Type{<:ConstRowMatrix}) = ConstRows()
MemoryLayout(::Type{<:PertConstRowMatrix}) = PertConstRows()
bandedcolumns(::ConstRows) = BandedToeplitzLayout()
bandedcolumns(::PertConstRows) = PertToeplitzLayout()
sublayout(::ConstRows, inds...) = sublayout(ApplyLayout{typeof(*)}(), inds...)
sublayout(::PertConstRows, inds...) = sublayout(ApplyLayout{typeof(hcat)}(), inds...)
for Typ in (:ConstRows, :PertConstRows)
    @eval begin
        sublayout(::$Typ, ::Type{<:Tuple{Any,AbstractInfUnitRange{Int}}}) = $Typ() # no way to lose const rows
        applybroadcaststyle(::Type{<:AbstractMatrix}, ::$Typ) = LazyArrayStyle{2}()
        applylayout(::Type, ::$Typ, _...) = LazyLayout()
    end
end

const BandedToeplitzLayout = BandedColumns{ConstRows}
const PertToeplitzLayout = BandedColumns{PertConstRows}

_BandedMatrix(::BandedToeplitzLayout, A::AbstractMatrix) =
    _BandedMatrix(ConstRowMatrix(bandeddata(A)), size(A,1), bandwidths(A)...)
_BandedMatrix(::PertToeplitzLayout, A::AbstractMatrix) =
    _BandedMatrix(PertConstRowMatrix(bandeddata(A)), size(A,1), bandwidths(A)...)

# for Lay in (:BandedToeplitzLayout, :PertToeplitzLayout)
#     @eval begin
#         sublayout(::$Lay, ::Type{<:Tuple{AbstractInfUnitRange{Int},AbstractInfUnitRange{Int}}}) = $Lay()
#         sublayout(::$Lay, ::Type{<:Tuple{Slice,AbstractInfUnitRange{Int}}}) = $Lay()
#         sublayout(::$Lay, ::Type{<:Tuple{AbstractInfUnitRange{Int},Slice}}) = $Lay()
#         sublayout(::$Lay, ::Type{<:Tuple{Slice,Slice}}) = $Lay()

#         sub_materialize(::$Lay, V) = BandedMatrix(V)
#     end
# end

##
# UniformScaling
##

for op in (:+, :-), Typ in (:(BandedMatrix{<:Any,<:Any,OneToInf{Int}}),
                            :(Adjoint{<:Any,<:BandedMatrix{<:Any,<:Any,OneToInf{Int}}}),
                            :(Transpose{<:Any,<:BandedMatrix{<:Any,<:Any,OneToInf{Int}}}))
    @eval begin
        $op(A::$Typ, λ::UniformScaling) = $op(A, Diagonal(Fill(λ.λ,∞)))
        $op(λ::UniformScaling, A::$Typ) = $op(Diagonal(Fill(λ.λ,∞)), A)
    end
end

_default_banded_broadcast(bc::Broadcasted, ::Tuple{<:OneToInf,<:Any}) = copy(Broadcasted{LazyArrayStyle{2}}(bc.f, bc.args))


text:
include("damping.jl")

include("rho.jl")

include("lm_result.jl")
include("lm.jl")

include("lm_bc_result.jl")
include("lm_bc.jl")


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

mutable struct Usage <: SwaggerModel
    unit::Any # spec type: Union{ Nothing, String } # spec name: unit
    currentValue::Any # spec type: Union{ Nothing, Int32 } # spec name: currentValue
    limit::Any # spec type: Union{ Nothing, Int32 } # spec name: limit
    name::Any # spec type: Union{ Nothing, UsageName } # spec name: name

    function Usage(;unit=nothing, currentValue=nothing, limit=nothing, name=nothing)
        o = new()
        validate_property(Usage, Symbol("unit"), unit)
        setfield!(o, Symbol("unit"), unit)
        validate_property(Usage, Symbol("currentValue"), currentValue)
        setfield!(o, Symbol("currentValue"), currentValue)
        validate_property(Usage, Symbol("limit"), limit)
        setfield!(o, Symbol("limit"), limit)
        validate_property(Usage, Symbol("name"), name)
        setfield!(o, Symbol("name"), name)
        o
    end
end # type Usage

const _property_map_Usage = Dict{Symbol,Symbol}(Symbol("unit")=>Symbol("unit"), Symbol("currentValue")=>Symbol("currentValue"), Symbol("limit")=>Symbol("limit"), Symbol("name")=>Symbol("name"))
const _property_types_Usage = Dict{Symbol,String}(Symbol("unit")=>"String", Symbol("currentValue")=>"Int32", Symbol("limit")=>"Int32", Symbol("name")=>"UsageName")
Base.propertynames(::Type{ Usage }) = collect(keys(_property_map_Usage))
Swagger.property_type(::Type{ Usage }, name::Symbol) = Union{Nothing,eval(Meta.parse(_property_types_Usage[name]))}
Swagger.field_name(::Type{ Usage }, property_name::Symbol) =  _property_map_Usage[property_name]

const _allowed_Usage_unit = ["Count", "Bytes", "Seconds", "Percent", "CountsPerSecond", "BytesPerSecond"]

function check_required(o::Usage)
    true
end

function validate_property(::Type{ Usage }, name::Symbol, val)
    if name === Symbol("unit")
        Swagger.validate_param(name, "Usage", :enum, val, _allowed_Usage_unit)
    end
end


text:
# SPD-License-Identifier: MIT

using ArgParse
using JLD2
using MarkovModels
using Random

function loadlexicon(path)
    retval = Dict()
    open(path, "r") do f
        for line in eachline(f)
            tokens = split(line)
            word, pronun = tokens[1], tokens[2:end]
            pronuns = push!(get(retval, word, []), pronun)
            retval[word] = pronuns
        end
    end
    retval
end

function rand_addsil(sentence, silsym, between_silprob, edge_silprob)
    retval = rand() < edge_silprob ? [silsym] : []
    for word in sentence[1:end-1]
        push!(retval, word)
        if rand() < between_silprob
            push!(retval, silsym)
        end
    end
    push!(retval, sentence[end])
    if rand() < edge_silprob
        push!(retval, silsym)
    end
    retval
end

function main(args)
    oovsym = args["oov-sym"]
    silsym = args["sil-sym"]
    between_silprob = args["between-silprob"]
    edge_silprob = args["edge-silprob"]
    lexicon = loadlexicon(args["lexicon"])
    n = args["ngram-order"]
    hmms = load(args["hmms"])

    ###################################################################
    # Estimate the n-gram count without pruning

    @info "Estimating $(n)-gram phonotactic language model."

    counts = Dict()
    for line in eachline(stdin)
        tokens = split(line)
        tokens = rand_addsil(tokens, silsym, between_silprob, edge_silprob)
        seq = []
        for token in tokens
            if token ∈ keys(lexicon)
                push!(seq, lexicon[token][1])
            else
                push!(seq, lexicon[oovsym][1])
            end
        end

        # Append nothing to mark the end of sentence.
        seq = vcat(seq..., [nothing])

        for i in 1:length(seq)
            src = tuple(seq[max(1, i-n+1):i-1]...)
            dest = if n > 1
                tuple(seq[max(1, i-n+2):i]...)
            else
                tuple(seq[i])
            end
            counts[(src, dest)] = get(counts, (src, dest), 0) + 1
        end
    end

    ###################################################################
    # Build an FSM from the counts

    @info "Representing the language model as a FSM."

    SF = LogSemifield{Float32}
    fsm = VectorFSM{SF}()

    # Get the init and final weights
    iws = Dict()
    fws = Dict()
    for ((src, dest), count) in counts
        if isempty(src) iws[dest] = SF(log(count)) end
        if isnothing(dest[end]) fws[src] = SF(log(count)) end
    end

    # Create the states.
    smap = Dict()
    for ((src, dest), count) in counts
        if ! isnothing(dest[end]) && dest ∉ keys(smap)
            initweight = get(iws, dest, zero(SF))
            finalweight = get(fws, dest, zero(SF))

            # This will be nonzero only in the unigram case.
            finalweight += get(fws, tuple(), zero(SF))

            smap[dest] = addstate!(fsm, dest; initweight, finalweight)
        end
    end

    # Create the arcs.
    for ((src, dest), count) in counts
        # Not an initial / final pseudo-arc.
        if ! isnothing(src) && ! isnothing(dest[end])
            if src == tuple() && n == 1
                # special case for unigram probabilty:
                # we use the same weight for each possible src states
                for s in values(smap)
                    addarc!(fsm, s, smap[dest], SF(log(count)))
                end
            elseif src ≠ tuple()
                addarc!(fsm, smap[src], smap[dest], SF(log(count)))
            end
        end
    end

    fsm = fsm

    ###################################################################
    # Compile and save

    @info "Composing the language model with units' HMM."

    # The previously built FSM combines the grammar and the lexicon.
    GL = fsm |> renormalize
    H = hmms["units"]
    GLH = HierarchicalFSM(GL, H)

    @info "Compiling."

    # Compile the expanded FSM into a matrix format.
    mfsm = MatrixFSM(GLH, hmms["pdfid_mapping"], t -> (t[end-1], t[end]))

    save(args["denfsm"], Dict("fsm" => mfsm))
end

function parse_commandline()
    s = ArgParseSettings()
    @add_arg_table s begin
        "--oov-sym"
            default = "<UNK>"
            help = "fallback for out of vocabulary words"
        "--sil-sym"
            default = "<SIL>"
            help = "silence word symbol"
        "--edge-silprob"
            default = 0.8
            arg_type = Float64
            help = "probability of having a silence at the edge of the utterance"
        "--between-silprob"
            default = 0.1
            arg_type = Float64
            help = "probability of having a silence between two words"
        "--ngram-order"
            default = 3
            arg_type = Int
            help = "ngram order of the language model"
        "hmms"
            required = true
            help = "HMM FSMs in JLD2 format"
        "lexicon"
            required = true
            help = "lexicon text file"
        "denfsm"
            required = true
            help = "output denominator fsm in JLD2 format"
    end
    s.description = """
    Build a denominator graph based on a phonetic language model.
    This script read the text from its standard input.
    """
    parse_args(s)
end

args = parse_commandline()
main(args)

max_stars_repo_name: MartinKocour/SpeechLab

max_issues_repo_name: MartinKocour/SpeechLab

max_forks_repo_name: MartinKocour/SpeechLab


text:
lines = open("bitmasks.txt") do f
    readlines(f)
end

memory = zeros(Int64, 100000)
zeromask = nothing
onemask = nothing
for l in lines
    global memory, zeromask, onemask
    if startswith(l, "mask = ")
        mask = match(r"[10X]+", l).match
        onemask = parse(Int, replace(mask, "X" => "0"); base = 2)
        zeromask = parse(Int, replace(mask, "X" => "1"); base = 2)
    else
        addr, val = parse.(Int, match(r"mem\[(\d+)\] = (\d+)", l).captures)
        memory[addr] = val & zeromask | onemask
    end
end

println(sum(memory))

memory = Dict{Int64, Int64}()
onemask = nothing
xmask = nothing
for l in lines
    global memory, xmask, onemask
    if startswith(l, "mask = ")
        mask = match(r"[10X]+", l).match
        onemask = parse(Int, replace(mask, "X" => "0"); base = 2)
        xmask = findall(x -> x == 'X', mask)
    else
        addr, val = parse.(Int, match(r"mem\[(\d+)\] = (\d+)", l).captures)
        res = collect(bitstring(addr | onemask)[end-35:end])
        for i in 0:(2^length(xmask)-1)
            floating = bitstring(i)[end-(length(xmask)-1):end]
            float = collect(res)
            for i in 1:length(xmask)
                float[xmask[i]] = floating[i]
            end
            memory[parse(Int, join(float); base = 2)] = val
        end
    end
end

println(sum(values(memory)))


text:
"""
# module TestDoolittle

# Examples

```jldoctest
julia>
```
"""
module TestDoolittle

using Test

using APMAE4001.LUFactorization.Doolittle

@testset "Set 1" begin
     A = [1  1  0  0  0  0
          1  2  1  0  0  0
          0  1  2  1  0  0
          0  0  1  2  1  0
          0  0  0  1  2  1
          0  0  0  0  1  2]
     L, U = doolittle_lu(A)
     @test L == [1.0  0.0  0.0  0.0  0.0  0.0
                 1.0  1.0  0.0  0.0  0.0  0.0
                 0.0  1.0  1.0  0.0  0.0  0.0
                 0.0  0.0  1.0  1.0  0.0  0.0
                 0.0  0.0  0.0  1.0  1.0  0.0
                 0.0  0.0  0.0  0.0  1.0  1.0]
     @test U == [1.0  1.0  0.0  0.0  0.0  0.0
                 0.0  1.0  1.0  0.0  0.0  0.0
                 0.0  0.0  1.0  1.0  0.0  0.0
                 0.0  0.0  0.0  1.0  1.0  0.0
                 0.0  0.0  0.0  0.0  1.0  1.0
                 0.0  0.0  0.0  0.0  0.0  1.0]
end

@testset "Example from notes" begin
     A = [1  1   0
          2  5   1
          1  4  -1]
     b = [1, 1, 2]
     L, U = doolittle_lu(A)
     @test L == [1.0  0.0  0.0
                 2.0  1.0  0.0
                 1.0  1.0  1.0]
     @test U == [1.0  1.0   0.0
                 0.0  3.0   1.0
                 0.0  0.0  -2.0]
     solutions = polysolve(A, b)
     @test solutions == A \ b
end

end


text:
function _precompile_()
    ccall(:jl_generating_output, Cint, ()) == 1 || return nothing
    Base.precompile(Tuple{typeof(deepcopy_internal),Tuple{Symbol, Symbol, Symbol},IdDict{Any, Any}})   # time: 0.0203449
    Base.precompile(Tuple{typeof(deepcopy_internal),Tuple{Int64},IdDict{Any, Any}})   # time: 0.0182394
    Base.precompile(Tuple{typeof(deepcopy_internal),Tuple{Int64, Int64, Int64},IdDict{Any, Any}})   # time: 0.0170211
    Base.precompile(Tuple{typeof(deepcopy_internal),Tuple{Symbol},IdDict{Any, Any}})   # time: 0.0164719
    Base.precompile(Tuple{typeof(symdiff),Vector{String},Vector{String}})   # time: 0.0073157
    Base.precompile(Tuple{typeof(_shrink),Function,Vector{String},Tuple{Vector{String}}})   # time: 0.0035465
    Base.precompile(Tuple{typeof(deepcopy_internal),Vector{Int32},IdDict{Any, Any}})   # time: 0.0031766
    Base.precompile(Tuple{typeof(copyto!),Matrix{Float64},Int64,Vector{Float64},Int64,Int64})   # time: 0.0019458
    Base.precompile(Tuple{typeof(setindex_widen_up_to),Vector{DataType},Any,Int64})   # time: 0.001777
    Base.precompile(Tuple{typeof(fieldcount),Type{Tuple{String, String, String}}})   # time: 0.0013452
    Base.precompile(Tuple{typeof(vectorfilter),Function,Vector{String}})   # time: 0.0012713
end


text:
export nest, unnest

using DataFrames

function nest(df::AbstractDataFrame, by, out)
    function _subdf_as_vec(sdf)
        [sdf[!, Not(by)]]
    end
    res = combine(groupby(df, by), _subdf_as_vec)

    rename!(res, names(res)[end]=>out)

    res
end

function unnest(df, val)
    tmp = [crossjoin(df[i:i, Not(val)], sdf) for (i, sdf) in enumerate(df[!, val])]
    reduce(vcat,  tmp)
end

max_stars_repo_name: xiaodaigh/DataConvenience

max_issues_repo_name: xiaodaigh/DataConvenience

max_forks_repo_name: xiaodaigh/DataConvenience


text:
using Oceananigans.Architectures
using Oceananigans.Architectures: device_event
using Oceananigans.BoundaryConditions
using Oceananigans.TurbulenceClosures: calculate_diffusivities!
using Oceananigans.ImmersedBoundaries: mask_immersed_field!
using Oceananigans.Models.NonhydrostaticModels: update_hydrostatic_pressure!

import Oceananigans.TimeSteppers: update_state!

compute_auxiliary_fields!(auxiliary_fields) = Tuple(compute!(a) for a in auxiliary_fields)

"""
    update_state!(model::HydrostaticFreeSurfaceModel)

Update peripheral aspects of the model (auxiliary fields, halo regions, diffusivities,
hydrostatic pressure) to the current model state.
"""
update_state!(model::HydrostaticFreeSurfaceModel) = update_state!(model, model.grid)

function update_state!(model::HydrostaticFreeSurfaceModel, grid)

    # Mask immersed fields
    masking_events = Tuple(mask_immersed_field!(field) for field in merge(model.auxiliary_fields, prognostic_fields(model)))

    wait(device(model.architecture), MultiEvent(masking_events))

    # Fill halos for velocities and tracers. On the CubedSphere, the halo filling for velocity fields is wrong.
    fill_halo_regions!(prognostic_fields(model), model.architecture, model.clock, fields(model))

    # This _refills_ the halos for horizontal velocity fields when grid::ConformalCubedSphereGrid
    # For every other type of grid, fill_horizontal_velocity_halos! does nothing.
    fill_horizontal_velocity_halos!(model.velocities.u, model.velocities.v, model.architecture)

    compute_w_from_continuity!(model)

    fill_halo_regions!(model.velocities.w, model.architecture, model.clock, fields(model))

    compute_auxiliary_fields!(model.auxiliary_fields)

    # Calculate diffusivities
    calculate_diffusivities!(model.diffusivity_fields, model.closure, model)
    fill_halo_regions!(model.diffusivity_fields, model.architecture, model.clock, fields(model))

    # Calculate hydrostatic pressure
    pressure_calculation = launch!(model.architecture, model.grid, :xy, update_hydrostatic_pressure!,
                                   model.pressure.pHY′, model.grid, model.buoyancy, model.tracers,
                                   dependencies=device_event(model.architecture))

    # Fill halo regions for pressure
    wait(device(model.architecture), pressure_calculation)

    fill_halo_regions!(model.pressure.pHY′, model.architecture)

    return nothing
end


text:
struct ProtectedException <: Exception
    msg::String
end

abstract type Permission end
struct Read <: Permission end
struct Write <: Permission end

struct Protected{T}
    data::T
    perms::NamedTuple
end

function Base.getproperty(protected::Protected, field::Symbol)
    return getfieldperm(
        getfield(protected, :data),
        field,
        get(getfield(protected, :perms), field, nothing),
    )
end

function Base.setproperty!(protected::Protected, field::Symbol, x)
    return setfieldperm!(
        getfield(protected, :data),
        field,
        x,
        get(getfield(protected, :perms), field, nothing),
    )
end

function Base.getindex(protected::Protected, idx)
    return getindexperm(
        getfield(protected, :data),
        idx,
        get(getfield(protected, :perms), idx, nothing),
    )
end

function Base.setindex!(protected::Protected, x, idx)
    return setindexperm!(
        getfield(protected, :data),
        x,
        idx,
        get(getfield(protected, :perms), idx, nothing),
    )
end

Base.haskey(d::Protected, key) = haskey(getfield(d, :data), key)

getindexperm(data::D, idx, perm::Nothing) where D =
    throw(ProtectedException("Read access to $D[$idx] disallowed."))
getindexperm(data, idx, perm::Union{Read, Write}) = getindex(data, idx)
getindexperm(data, idx, perm::NamedTuple) = protect(getindex(data, idx), perm)

setindexperm!(data::D, idx, x, perm::Union{Read, Nothing, NamedTuple}) where D =
    throw(ProtectedException("Write access to $D[$idx] disallowed."))
setindexperm!(data, x, idx, perm::Write) = setindex!(data, x, idx)

getfieldperm(data::D, field, perm::Nothing) where D =
    throw(ProtectedException("Read access to $(D).$(string(field)) disallowed."))
getfieldperm(data, field, perm::Union{Read, Write}) = getproperty(data, field)
getfieldperm(data, field, perm::NamedTuple) = protect(getproperty(data, field), perm)

setfieldperm!(data::D, field, x, perm::Union{Read, Nothing, NamedTuple}) where D =
    throw(ProtectedException("Write access to $(D).$(string(field)) disallowed."))
setfieldperm!(data, field, x, perm::Write) = setproperty!(data, field, x)

Base.fieldnames(protected::Protected) = fieldnames(typeof(getfield(protected, :data)))

protect(x, perms) = Protected(x, perms)

struct PropDict{V}
    d::Dict
    function PropDict(d::Dict{K, V}) where {K, V}
        return new{V}(d)
    end
end

Base.getproperty(d::PropDict, field::Symbol) = getfield(d, :d)[field]
Base.setproperty!(d::PropDict, field::Symbol, val) = (getfield(d, :d)[field] = val;)
Base.propertynames(d::PropDict) = Tuple(keys(getfield(d, :d)))

Base.haskey(d::PropDict, key) = haskey(getfield(d, :d), key)

PropDict(args...) = PropDict(Dict{Symbol, Any}(args...))


text:
using AlgebraPDF
using Test

@testset "Plotting utils" begin
    @test scaletobinneddata(10, (0,1),10) ≈ 1.0
    @test scaletobinneddata(10, range(0,1,length=11)) ≈ 1.0
    @test scaletobinneddata(range(0,1,length=11)) ≈ 0.1
end


text:
function AdapterPropagator(arg0::Propagator)
    return AdapterPropagator((Propagator,), arg0)
end

function add_effect(obj::AdapterPropagator, arg0::AdapterPropagator_DifferentialEffect)
    return jcall(obj, "addEffect", void, (AdapterPropagator_DifferentialEffect,), arg0)
end

function get_effects(obj::AdapterPropagator)
    return jcall(obj, "getEffects", List, ())
end

function get_initial_state(obj::AdapterPropagator)
    return jcall(obj, "getInitialState", SpacecraftState, ())
end

function get_propagator(obj::AdapterPropagator)
    return jcall(obj, "getPropagator", Propagator, ())
end

function reset_initial_state(obj::AdapterPropagator, arg0::SpacecraftState)
    return jcall(obj, "resetInitialState", void, (SpacecraftState,), arg0)
end


text:
"""
Kinetic energy: 1/2 sum_n f_n ∫ |∇ψn|^2.
"""
struct Kinetic end
(K::Kinetic)(basis) = TermKinetic(basis)

struct TermKinetic <: Term
    basis::PlaneWaveBasis
    kinetic_energies::Vector{Vector} # kinetic energy 1/2|G+k|^2 for every kpoint
end
function TermKinetic(basis::PlaneWaveBasis)
    kinetic_energies = [[sum(abs2, basis.model.recip_lattice * (G + kpt.coordinate)) / 2
                         for G in G_vectors(kpt)]
                        for kpt in basis.kpoints]
    TermKinetic(basis, kinetic_energies)
end

function ene_ops(term::TermKinetic, ψ, occ; kwargs...)
    basis = term.basis
    T = eltype(basis)

    ops = [FourierMultiplication(basis, kpoint, term.kinetic_energies[ik])
           for (ik, kpoint) in enumerate(basis.kpoints)]
    ψ === nothing && return (E=T(Inf), ops=ops)

    E = zero(T)
    for (ik, k) in enumerate(basis.kpoints)
        for iband = 1:size(ψ[1], 2)
            ψnk = @views ψ[ik][:, iband]
            E += (basis.kweights[ik] * occ[ik][iband]
                  * real(dot(ψnk, term.kinetic_energies[ik] .* ψnk)))
        end
    end

    (E=E, ops=ops)
end


text:
using ShortStrings
using Test, Random

r = randstring.(1:15)
@test all(ShortString15.(r) .== r)
a = ShortString15.(r)
@test fsort(a) |> issorted

r = randstring.(1:7)
@test all(ShortString7.(r) .== r)
a = ShortString7.(r)
@test fsort(a) |> issorted

r = randstring.(1:3)
@test all(ShortString{UInt32}.(r) .== r)
a = ShortString{UInt32}.(r)
@test fsort(a) |> issorted

@test all(ShortString3.(r) .== r)
a = ShortString3.(r)
@test fsort(a) |> issorted

@test collect(ShortString3("abc")) == ['a', 'b', 'c']

@test ss15"Short String!!!" === ShortString15("Short String!!!")
@test ss7"ShrtStr" === ShortString7("ShrtStr")
@test ss3"ss3" === ShortString3("ss3")

@test_throws ErrorException ShortString{UInt128}("Short String!!!!")
@test_throws ErrorException ShortString15("Short String!!!!")
@test_throws ErrorException ss15"Short String!!!!"

@test_throws ErrorException ShortString{UInt64}("ShortStr")
@test_throws ErrorException ShortString7("ShortStr")
@test_throws ErrorException ss7"ShortStr"

@test_throws ErrorException ShortString{UInt32}("Short")
@test_throws ErrorException ShortString3("Short")
@test_throws ErrorException ss3"Short"


text:
using NonLinearReactionAdvectionDiffusionWithFrontData;

@testset "Различные вспомогательные функции                " begin

    N = 20;
    X = [i/N for i in 0:N];
    Y = u_init.(X);

    @testset "Initial condition" begin

        @test length(u_init.(X)) == N+1
        @test_broken isapprox(u_init(X[1]), -8, rtol=0.001)
        @test isapprox(u_init(X[end]), 4, rtol=0.001)
    end

    @testset "`strip_borderPoints`" begin
        B = copy(Y)
        B = NonLinearReactionAdvectionDiffusionWithFrontData.strip_borderPoints(B, N)
        @test length(B) == N-1
        @test B == Y[2:N]
        @test_throws AssertionError NonLinearReactionAdvectionDiffusionWithFrontData.strip_borderPoints(B, N)
    end

end

@testset "Формирование сетки                               " begin

    using NonLinearReactionAdvectionDiffusionWithFrontData: shishkin_mesh;

    e = 0.02;
    a, b = 0, 1;
    xtp = 0.3;
    N = 50;
    X = shishkin_mesh(a, b, xtp, e, N);

    @test sort(X) == X
    @test unique(X) == X
    @test length(X) == N + N + 2N + 1

    # Проверка упорядоченности a, x_tp, b
    @test_throws ArgumentError shishkin_mesh(b, a, 0.5, 0.1, N)
    @test_throws ArgumentError shishkin_mesh(a, b, 1.5, 0.1, N)
    @test_throws ArgumentError shishkin_mesh(a, b, -10, 0.1, N)

end


text:
module DynamicHMCModels

using Reexport

@reexport using CSV, LinearAlgebra
@reexport using ForwardDiff
@reexport using DynamicHMC, LogDensityProblems, TransformVariables
@reexport using StatsFuns, Distributions, Random, MCMCChains
@reexport using Parameters, CSV, DataFrames, StatsPlots

include("chains.jl")
include("nptochain.jl")

export
  create_a3d,
  insert_chain!,
  nptochain,
  create_mcmcchains

end # module


text:
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
# Description
# ==============================================================================
#
#   Tests related to the text backend.
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

@testset "Rational numbers" verbose = true begin
    @testset "Default" begin
        result = pretty_number(String, 1986//1987)
        expected = "¹⁹⁸⁶/₁₉₈₇"
        @test result == expected

        result = pretty_number(String, 1234567890//1)
        expected = "¹²³⁴⁵⁶⁷⁸⁹⁰/₁"
        @test result == expected

        result = pretty_number(String, 1//1234567890)
        expected = "¹/₁₂₃₄₅₆₇₈₉₀"
        @test result == expected

        result = pretty_number(String, -1986//1987)
        expected = "- ¹⁹⁸⁶/₁₉₈₇"
        @test result == expected

        result = pretty_number(String, -1234567890//1)
        expected = "- ¹²³⁴⁵⁶⁷⁸⁹⁰/₁"
        @test result == expected

        result = pretty_number(String, -1//1234567890)
        expected = "- ¹/₁₂₃₄₅₆₇₈₉₀"
        @test result == expected
    end

    @testset "Compact" begin
        result = pretty_number(String, 1986//1987; compact = false)
        expected = """
        1986
        ————
        1987"""
        @test result == expected

        result = pretty_number(String, -1986//1987; compact = false)
        expected = """
          1986
        - ————
          1987"""
        @test result == expected
    end
end

@testset "Irrational numbers" verbose = true begin
    @testset "Default" begin
        result = pretty_number(String, π)
        @test result == "π"

        result = pretty_number(String, ℯ)
        @test result == "ℯ"
    end
end

@testset "Numbers" verbose = true begin
    @testset "Default" begin
        result = pretty_number(String, 1.1986e6)
        expected = "1.1986 × 10⁶"
        @test result == expected

        result = pretty_number(String, 0)
        expected = "0"
        @test result == expected

        result = pretty_number(String, 1e0)
        expected = "1"
        @test result == expected

        result = pretty_number(String, 1e0; always_print_base = true)
        expected = "1 × 10⁰"
        @test result == expected

        result = pretty_number(String, 1e1)
        expected = "1 × 10¹"
        @test result == expected

        result = pretty_number(String, 1e2)
        expected = "1 × 10²"
        @test result == expected

        result = pretty_number(String, 1e3)
        expected = "1 × 10³"
        @test result == expected

        result = pretty_number(String, 1e4)
        expected = "1 × 10⁴"
        @test result == expected

        result = pretty_number(String, 1e5)
        expected = "1 × 10⁵"
        @test result == expected

        result = pretty_number(String, 1e6)
        expected = "1 × 10⁶"
        @test result == expected

        result = pretty_number(String, 1e7)
        expected = "1 × 10⁷"
        @test result == expected

        result = pretty_number(String, 1e8)
        expected = "1 × 10⁸"
        @test result == expected

        result = pretty_number(String, 1e9)
        expected = "1 × 10⁹"
        @test result == expected

        result = pretty_number(String, 1e-1)
        expected = "1 × 10⁻¹"
        @test result == expected

        result = pretty_number(String, 1e-2)
        expected = "1 × 10⁻²"
        @test result == expected

        result = pretty_number(String, 1e-3)
        expected = "1 × 10⁻³"
        @test result == expected

        result = pretty_number(String, 1e-4)
        expected = "1 × 10⁻⁴"
        @test result == expected

        result = pretty_number(String, 1e-5)
        expected = "1 × 10⁻⁵"
        @test result == expected

        result = pretty_number(String, 1e-6)
        expected = "1 × 10⁻⁶"
        @test result == expected

        result = pretty_number(String, 1e-7)
        expected = "1 × 10⁻⁷"
        @test result == expected

        result = pretty_number(String, 1e-8)
        expected = "1 × 10⁻⁸"
        @test result == expected

        result = pretty_number(String, 1e-9)
        expected = "1 × 10⁻⁹"
        @test result == expected
    end

    @testset "Significand format" begin
        result = pretty_number(String, 1.19861987e6; significand_format = "%.8f")
        expected = "1.19861987 × 10⁶"
        @test result == expected
    end

    @testset "Show base and significand" begin
        result = pretty_number(String, 1.19861987e6; show_base = false)
        expected = "1.19862"
        @test result == expected

        result = pretty_number(
            String,
            1.19861987e6;
            show_base = false,
            significand_format = "%.8f"
        )
        expected = "1.19861987"
        @test result == expected

        result = pretty_number(String, 1.19861987e6; show_significand = false)
        expected = "10⁶"
        @test result == expected

        result = pretty_number(
            String,
            1.19861987e6;
            show_base = false,
            show_significand = false
        )
        expected = ""

        @test result == expected
    end

    @testset "New decimal base" begin
        result = pretty_number(
            String,
            1.19861987e6;
            new_decimal_base = 7
        )
        expected = "0.119862 × 10⁷"
        @test result == expected

        result = pretty_number(
            String,
            1.19861987e6;
            new_decimal_base = 5
        )
        expected = "11.9862 × 10⁵"
        @test result == expected

        result = pretty_number(
            String,
            0,
            new_decimal_base = 6
        )
        expected = "0 × 10⁶"
        @test result == expected
    end

    @testset "Multiplication sign" begin
        result = pretty_number(
            String,
            1.19861987e6;
            multiplication_sign = '⋅'
        )
        expected = "1.19862 ⋅ 10⁶"
        @test result == expected

        result = pretty_number(
            String,
            1.19861987e6;
            multiplication_sign = '⋅',
            new_decimal_base = 5
        )
        expected = "11.9862 ⋅ 10⁵"
        @test result == expected

        result = pretty_number(
            String,
            1.19861987e6;
            multiplication_sign = '❌'
        )
        expected = "1.19862 ❌ 10⁶"
        @test result == expected
    end
end


text:
### Day 9
## Explosives in Cyberspace
## Author: Thanasis Georgiou

function decompress(str, rec)
  output = 0
  i = 1
  while i <= length(str)
    # Find first marker
    markerStart = search(str, '(', i)

    # If there are no markers, add the rest of the length and skip
    if markerStart == 0
      output += length(str) - (i - 1)
      break
    else
      # Move to marker start
      output += markerStart - i
      i = markerStart

      # Parse marker
      markerEnd = search(str, ')', markerStart)
      marker = split(str[markerStart + 1:markerEnd - 1], 'x')

      len = parse(Int, marker[1])
      times = parse(Int, marker[2])

      # Extract accoarding to marker
      if rec == true
        output += times * decompress(str[markerEnd + 1:markerEnd + len], true)
      else
        output += times * len
      end

      # Move past this marker's influence
      i = markerEnd + len + 1
    end
  end

  return output
end

# Read file
f = open("input.txt")
input = chomp(readstring(f))
close(f)

# Print output
println("Length 1: $(decompress(input, false))")
println("Length 2: $(decompress(input, true))")


text:
export EliminationGraph

export eliminate!, is_leaf, getindex

mutable struct EliminationGraph
    adj::DirectedGraph{Bool}
    list::Intlist
    size::Vector{Int64}

    function EliminationGraph(a::SparseMatrix)
        @assert default_layout == a.layout

        local eg = new()

        local n = a.column_count
        eg.list = Intlist(n)
        eg.adj = DirectedGraph{Bool}(a.column_count)
        eg.size = zeros(Int64, n)

        for j = 1:n
            for i = a.columns[j]:(a.columns[j+1]-1)
                local ii = a.columns_rows[i]
                for k = a.rows[ii]:(a.rows[ii+1]-1)
                    local r = a.rows_columns[k]

                    if (r <= j)
                        continue
                    end

                    push!(eg.list, r)
                end
            end

            while !is_empty(eg.list)
                local i = pop!(eg.list)

                connect!(eg.adj, true, i, j)
                connect!(eg.adj, true, j, i)

                eg.size[i] += 1
                eg.size[j] += 1
            end
        end

        return eg
    end
end

function eliminate!(eg::EliminationGraph, vertex::Int64)
    local p = eg.adj.start[vertex]
    while NIL != p
        local i = eg.adj.vertices[p]

        local q = eg.adj.start[i]
        while NIL != q
            local j = eg.adj.vertices[q]

            if j != i && j != vertex
                push!(eg.list, j)
            end

            q = eg.adj.next[q]
        end

        q = eg.adj.start[vertex]
        while NIL != q
            local j = eg.adj.vertices[q]

            if j != i && j != vertex
                push!(eg.list, j)
            end

            q = eg.adj.next[q]
        end

        eg.size[i] = eg.list.size
        disconnect!(eg.adj, i)

        while !is_empty(eg.list)
            connect!(eg.adj, true, i, pop!(eg.list))
        end

        p = eg.adj.next[p]
    end

    eg.size[vertex] = 0
    disconnect!(eg.adj, vertex)
end

function is_leaf(eg::EliminationGraph, vertex::Int64)
    return is_leaf(eg.adj, vertex)
end

function getindex(eg::EliminationGraph, vertex::Int64)
    local vertices = Vector{Int64}()
    sizehint!(vertices, 4)
    local i = eg.adj.start[vertex]

    while NIL != i
        push!(vertices, eg.adj.vertices[i])
        i = eg.adj.next[i]
    end

    return vertices
end


text:
# Automatically generated using Clang.jl

# manually cherry-picked from the generated wrappers, because we don't need the full extend
# of the API and can reuse some structures from the CUDA driver API
# TODO: aren't enums also reusable?

# compatible structures from the CUDA driver API
const dim3 = CuDim3
const cudaStream_t = CUstream
const cudaEvent_t = CUevent

@cenum cudaError::UInt32 begin
    cudaSuccess = 0
    cudaErrorInvalidValue = 1
    cudaErrorMemoryAllocation = 2
    cudaErrorInitializationError = 3
    cudaErrorCudartUnloading = 4
    cudaErrorProfilerDisabled = 5
    cudaErrorProfilerNotInitialized = 6
    cudaErrorProfilerAlreadyStarted = 7
    cudaErrorProfilerAlreadyStopped = 8
    cudaErrorInvalidConfiguration = 9
    cudaErrorInvalidPitchValue = 12
    cudaErrorInvalidSymbol = 13
    cudaErrorInvalidHostPointer = 16
    cudaErrorInvalidDevicePointer = 17
    cudaErrorInvalidTexture = 18
    cudaErrorInvalidTextureBinding = 19
    cudaErrorInvalidChannelDescriptor = 20
    cudaErrorInvalidMemcpyDirection = 21
    cudaErrorAddressOfConstant = 22
    cudaErrorTextureFetchFailed = 23
    cudaErrorTextureNotBound = 24
    cudaErrorSynchronizationError = 25
    cudaErrorInvalidFilterSetting = 26
    cudaErrorInvalidNormSetting = 27
    cudaErrorMixedDeviceExecution = 28
    cudaErrorNotYetImplemented = 31
    cudaErrorMemoryValueTooLarge = 32
    cudaErrorInsufficientDriver = 35
    cudaErrorInvalidSurface = 37
    cudaErrorDuplicateVariableName = 43
    cudaErrorDuplicateTextureName = 44
    cudaErrorDuplicateSurfaceName = 45
    cudaErrorDevicesUnavailable = 46
    cudaErrorIncompatibleDriverContext = 49
    cudaErrorMissingConfiguration = 52
    cudaErrorPriorLaunchFailure = 53
    cudaErrorLaunchMaxDepthExceeded = 65
    cudaErrorLaunchFileScopedTex = 66
    cudaErrorLaunchFileScopedSurf = 67
    cudaErrorSyncDepthExceeded = 68
    cudaErrorLaunchPendingCountExceeded = 69
    cudaErrorInvalidDeviceFunction = 98
    cudaErrorNoDevice = 100
    cudaErrorInvalidDevice = 101
    cudaErrorStartupFailure = 127
    cudaErrorInvalidKernelImage = 200
    cudaErrorDeviceUninitilialized = 201
    cudaErrorMapBufferObjectFailed = 205
    cudaErrorUnmapBufferObjectFailed = 206
    cudaErrorArrayIsMapped = 207
    cudaErrorAlreadyMapped = 208
    cudaErrorNoKernelImageForDevice = 209
    cudaErrorAlreadyAcquired = 210
    cudaErrorNotMapped = 211
    cudaErrorNotMappedAsArray = 212
    cudaErrorNotMappedAsPointer = 213
    cudaErrorECCUncorrectable = 214
    cudaErrorUnsupportedLimit = 215
    cudaErrorDeviceAlreadyInUse = 216
    cudaErrorPeerAccessUnsupported = 217
    cudaErrorInvalidPtx = 218
    cudaErrorInvalidGraphicsContext = 219
    cudaErrorNvlinkUncorrectable = 220
    cudaErrorJitCompilerNotFound = 221
    cudaErrorInvalidSource = 300
    cudaErrorFileNotFound = 301
    cudaErrorSharedObjectSymbolNotFound = 302
    cudaErrorSharedObjectInitFailed = 303
    cudaErrorOperatingSystem = 304
    cudaErrorInvalidResourceHandle = 400
    cudaErrorIllegalState = 401
    cudaErrorSymbolNotFound = 500
    cudaErrorNotReady = 600
    cudaErrorIllegalAddress = 700
    cudaErrorLaunchOutOfResources = 701
    cudaErrorLaunchTimeout = 702
    cudaErrorLaunchIncompatibleTexturing = 703
    cudaErrorPeerAccessAlreadyEnabled = 704
    cudaErrorPeerAccessNotEnabled = 705
    cudaErrorSetOnActiveProcess = 708
    cudaErrorContextIsDestroyed = 709
    cudaErrorAssert = 710
    cudaErrorTooManyPeers = 711
    cudaErrorHostMemoryAlreadyRegistered = 712
    cudaErrorHostMemoryNotRegistered = 713
    cudaErrorHardwareStackError = 714
    cudaErrorIllegalInstruction = 715
    cudaErrorMisalignedAddress = 716
    cudaErrorInvalidAddressSpace = 717
    cudaErrorInvalidPc = 718
    cudaErrorLaunchFailure = 719
    cudaErrorCooperativeLaunchTooLarge = 720
    cudaErrorNotPermitted = 800
    cudaErrorNotSupported = 801
    cudaErrorSystemNotReady = 802
    cudaErrorSystemDriverMismatch = 803
    cudaErrorCompatNotSupportedOnDevice = 804
    cudaErrorStreamCaptureUnsupported = 900
    cudaErrorStreamCaptureInvalidated = 901
    cudaErrorStreamCaptureMerge = 902
    cudaErrorStreamCaptureUnmatched = 903
    cudaErrorStreamCaptureUnjoined = 904
    cudaErrorStreamCaptureIsolation = 905
    cudaErrorStreamCaptureImplicit = 906
    cudaErrorCapturedEvent = 907
    cudaErrorStreamCaptureWrongThread = 908
    cudaErrorUnknown = 999
    cudaErrorApiFailureBase = 10000
end
const cudaError_t = cudaError

@cenum cudaDeviceAttr::UInt32 begin
    cudaDevAttrMaxThreadsPerBlock = 1
    cudaDevAttrMaxBlockDimX = 2
    cudaDevAttrMaxBlockDimY = 3
    cudaDevAttrMaxBlockDimZ = 4
    cudaDevAttrMaxGridDimX = 5
    cudaDevAttrMaxGridDimY = 6
    cudaDevAttrMaxGridDimZ = 7
    cudaDevAttrMaxSharedMemoryPerBlock = 8
    cudaDevAttrTotalConstantMemory = 9
    cudaDevAttrWarpSize = 10
    cudaDevAttrMaxPitch = 11
    cudaDevAttrMaxRegistersPerBlock = 12
    cudaDevAttrClockRate = 13
    cudaDevAttrTextureAlignment = 14
    cudaDevAttrGpuOverlap = 15
    cudaDevAttrMultiProcessorCount = 16
    cudaDevAttrKernelExecTimeout = 17
    cudaDevAttrIntegrated = 18
    cudaDevAttrCanMapHostMemory = 19
    cudaDevAttrComputeMode = 20
    cudaDevAttrMaxTexture1DWidth = 21
    cudaDevAttrMaxTexture2DWidth = 22
    cudaDevAttrMaxTexture2DHeight = 23
    cudaDevAttrMaxTexture3DWidth = 24
    cudaDevAttrMaxTexture3DHeight = 25
    cudaDevAttrMaxTexture3DDepth = 26
    cudaDevAttrMaxTexture2DLayeredWidth = 27
    cudaDevAttrMaxTexture2DLayeredHeight = 28
    cudaDevAttrMaxTexture2DLayeredLayers = 29
    cudaDevAttrSurfaceAlignment = 30
    cudaDevAttrConcurrentKernels = 31
    cudaDevAttrEccEnabled = 32
    cudaDevAttrPciBusId = 33
    cudaDevAttrPciDeviceId = 34
    cudaDevAttrTccDriver = 35
    cudaDevAttrMemoryClockRate = 36
    cudaDevAttrGlobalMemoryBusWidth = 37
    cudaDevAttrL2CacheSize = 38
    cudaDevAttrMaxThreadsPerMultiProcessor = 39
    cudaDevAttrAsyncEngineCount = 40
    cudaDevAttrUnifiedAddressing = 41
    cudaDevAttrMaxTexture1DLayeredWidth = 42
    cudaDevAttrMaxTexture1DLayeredLayers = 43
    cudaDevAttrMaxTexture2DGatherWidth = 45
    cudaDevAttrMaxTexture2DGatherHeight = 46
    cudaDevAttrMaxTexture3DWidthAlt = 47
    cudaDevAttrMaxTexture3DHeightAlt = 48
    cudaDevAttrMaxTexture3DDepthAlt = 49
    cudaDevAttrPciDomainId = 50
    cudaDevAttrTexturePitchAlignment = 51
    cudaDevAttrMaxTextureCubemapWidth = 52
    cudaDevAttrMaxTextureCubemapLayeredWidth = 53
    cudaDevAttrMaxTextureCubemapLayeredLayers = 54
    cudaDevAttrMaxSurface1DWidth = 55
    cudaDevAttrMaxSurface2DWidth = 56
    cudaDevAttrMaxSurface2DHeight = 57
    cudaDevAttrMaxSurface3DWidth = 58
    cudaDevAttrMaxSurface3DHeight = 59
    cudaDevAttrMaxSurface3DDepth = 60
    cudaDevAttrMaxSurface1DLayeredWidth = 61
    cudaDevAttrMaxSurface1DLayeredLayers = 62
    cudaDevAttrMaxSurface2DLayeredWidth = 63
    cudaDevAttrMaxSurface2DLayeredHeight = 64
    cudaDevAttrMaxSurface2DLayeredLayers = 65
    cudaDevAttrMaxSurfaceCubemapWidth = 66
    cudaDevAttrMaxSurfaceCubemapLayeredWidth = 67
    cudaDevAttrMaxSurfaceCubemapLayeredLayers = 68
    cudaDevAttrMaxTexture1DLinearWidth = 69
    cudaDevAttrMaxTexture2DLinearWidth = 70
    cudaDevAttrMaxTexture2DLinearHeight = 71
    cudaDevAttrMaxTexture2DLinearPitch = 72
    cudaDevAttrMaxTexture2DMipmappedWidth = 73
    cudaDevAttrMaxTexture2DMipmappedHeight = 74
    cudaDevAttrComputeCapabilityMajor = 75
    cudaDevAttrComputeCapabilityMinor = 76
    cudaDevAttrMaxTexture1DMipmappedWidth = 77
    cudaDevAttrStreamPrioritiesSupported = 78
    cudaDevAttrGlobalL1CacheSupported = 79
    cudaDevAttrLocalL1CacheSupported = 80
    cudaDevAttrMaxSharedMemoryPerMultiprocessor = 81
    cudaDevAttrMaxRegistersPerMultiprocessor = 82
    cudaDevAttrManagedMemory = 83
    cudaDevAttrIsMultiGpuBoard = 84
    cudaDevAttrMultiGpuBoardGroupID = 85
    cudaDevAttrHostNativeAtomicSupported = 86
    cudaDevAttrSingleToDoublePrecisionPerfRatio = 87
    cudaDevAttrPageableMemoryAccess = 88
    cudaDevAttrConcurrentManagedAccess = 89
    cudaDevAttrComputePreemptionSupported = 90
    cudaDevAttrCanUseHostPointerForRegisteredMem = 91
    cudaDevAttrReserved92 = 92
    cudaDevAttrReserved93 = 93
    cudaDevAttrReserved94 = 94
    cudaDevAttrCooperativeLaunch = 95
    cudaDevAttrCooperativeMultiDeviceLaunch = 96
    cudaDevAttrMaxSharedMemoryPerBlockOptin = 97
    cudaDevAttrCanFlushRemoteWrites = 98
    cudaDevAttrHostRegisterSupported = 99
    cudaDevAttrPageableMemoryAccessUsesHostPageTables = 100
    cudaDevAttrDirectManagedMemAccessFromHost = 101
end

@cenum cudaLimit::UInt32 begin
    cudaLimitStackSize = 0
    cudaLimitPrintfFifoSize = 1
    cudaLimitMallocHeapSize = 2
    cudaLimitDevRuntimeSyncDepth = 3
    cudaLimitDevRuntimePendingLaunchCount = 4
    cudaLimitMaxL2FetchGranularity = 5
end

@cenum cudaFuncCache::UInt32 begin
    cudaFuncCachePreferNone = 0
    cudaFuncCachePreferShared = 1
    cudaFuncCachePreferL1 = 2
    cudaFuncCachePreferEqual = 3
end

@cenum cudaSharedMemConfig::UInt32 begin
    cudaSharedMemBankSizeDefault = 0
    cudaSharedMemBankSizeFourByte = 1
    cudaSharedMemBankSizeEightByte = 2
end

const cudaStreamDefault = 0x00
const cudaStreamNonBlocking = 0x01

const cudaEventDefault = 0x00
const cudaEventBlockingSync = 0x01
const cudaEventDisableTiming = 0x02
const cudaEventInterprocess = 0x04

struct cudaFuncAttributes
    sharedSizeBytes::Csize_t
    constSizeBytes::Csize_t
    localSizeBytes::Csize_t
    maxThreadsPerBlock::Cint
    numRegs::Cint
    ptxVersion::Cint
    binaryVersion::Cint
    cacheModeCA::Cint
    maxDynamicSharedSizeBytes::Cint
    preferredShmemCarveout::Cint
end

const cudaArray = Cvoid
const cudaArray_t = Ptr{cudaArray}

@cenum cudaMemcpyKind::UInt32 begin
    cudaMemcpyHostToHost = 0
    cudaMemcpyHostToDevice = 1
    cudaMemcpyDeviceToHost = 2
    cudaMemcpyDeviceToDevice = 3
    cudaMemcpyDefault = 4
end

struct cudaPitchedPtr
    ptr::Ptr{Cvoid}
    pitch::Csize_t
    xsize::Csize_t
    ysize::Csize_t
end

struct cudaExtent
    width::Csize_t
    height::Csize_t
    depth::Csize_t
end

struct cudaPos
    x::Csize_t
    y::Csize_t
    z::Csize_t
end

struct cudaMemcpy3DParms
    srcArray::cudaArray_t
    srcPos::cudaPos
    srcPtr::cudaPitchedPtr
    dstArray::cudaArray_t
    dstPos::cudaPos
    dstPtr::cudaPitchedPtr
    extent::cudaExtent
    kind::cudaMemcpyKind
end

@cenum cudaCGScope::UInt32 begin
    cudaCGScopeInvalid = 0
    cudaCGScopeGrid = 1
    cudaCGScopeMultiGrid = 2
end


text:
"""
This struct contains all the data for an investor.
    name: Investor's name.
    data_dir: Directoty where investors' data is stored.
    projects: Vector of all projects owned by the investor.
    markets: Vector of markets in which the investor is participating.
    market_prices: Expected market prices.
    rep_hour_weight: Representative hour weight for operating markets.
    forecast: Forecast parameters.
    cap_cost_multiplier: Capital cost multiplier.
    max_annual_projects: Maximum number of projects.
    risk_preference: Whether investor is Risk Neutral or Risk Averse.
"""
mutable struct Investor
    name::String
    data_dir::String
    projects::Vector{<: Project{<: BuildPhase}}
    markets::Vector{Symbol}
    market_prices::MarketPrices
    rep_hour_weight::Vector{Float64}
    forecast::F where F <: Forecast
    cap_cost_multiplier::Float64
    max_annual_projects::Int64
    risk_preference::T where T <: RiskPreference
end

get_name(investor::Investor) = investor.name
get_data_dir(investor::Investor) = investor.data_dir
get_projects(investor::Investor) = investor.projects
get_markets(investor::Investor) = investor.markets
get_market_prices(investor::Investor) = investor.market_prices
get_rep_hour_weight(investor::Investor) = investor.rep_hour_weight
get_forecast(investor::Investor) = investor.forecast
get_cap_cost_multiplier(investor::Investor) = investor.cap_cost_multiplier
get_max_annual_projects(investor::Investor) = investor.max_annual_projects
get_risk_preference(investor::Investor) = investor.risk_preference

# Get projects based on their buildphases
function get_existing(investor::Investor)
    leaftypes_existing = leaftypes(Project{Existing})
    projects = get_projects(investor)
    existing_projects = filter(project -> in(typeof(project), leaftypes_existing), projects)

    return existing_projects
end

function get_planned(investor::Investor)
    leaftypes_planned = leaftypes(Project{Planned})
    projects = get_projects(investor)
    planned_projects = filter(project -> in(typeof(project), leaftypes_planned), projects)

    return planned_projects
end

function get_queue(investor::Investor)
    leaftypes_queue = leaftypes(Project{Queue})
    projects = get_projects(investor)
    queue_projects = filter(project -> in(typeof(project), leaftypes_queue), projects)

    return queue_projects
end

function get_options(investor::Investor)
    leaftypes_option = leaftypes(Project{Option})
    projects = get_projects(investor)
    option_projects = filter(project -> in(typeof(project), leaftypes_option), projects)

    return option_projects
end

function get_retired(investor::Investor)
    leaftypes_retired = leaftypes(Project{Retired})
    projects = get_projects(investor)
    retired_projects = filter(project -> in(typeof(project), leaftypes_retired), projects)

    return retired_projects
end

function find_active_invested_projects(projects::Vector{<: Project})
    leaftypes_option = leaftypes(Project{Option})
    leaftypes_retired= leaftypes(Project{Retired})
    active_invested_projects = filter(project -> (!in(typeof(project), leaftypes_option) && !in(typeof(project), leaftypes_retired) ), projects)

    return active_invested_projects
end

function find_option_projects(projects::Vector{<: Project})
    leaftypes_option = leaftypes(Project{Option})
    option_projects = filter(project -> in(typeof(project), leaftypes_option), projects)

    return option_projects
end

function set_market_prices!(investor::Investor,
                           market_prices::MarketPrices)
    investor.market_prices = market_prices
end


text:
# write your own tests here
N = 10
ph = PortHamiltonian.weak_phs1(N, 0, 1);
eigval, eigvec = eigen(ph);
num_freq = frequencies(eigval)

@test abs(num_freq[2]-pi) < 1e-13

N = 10
ph = PortHamiltonian.weak_phs2(N, 0, 1);
eigval, eigvec = eigen(ph);
num_freq = frequencies(eigval)

@test abs(num_freq[2]-pi) < 1e-13

ph = PortHamiltonian.finelem(N+1,5, 0, 1)
eigval, eigvec = eigen(ph);
num_freq = frequencies(eigval)
@test abs(num_freq[2]-pi) < 1e-13

ph = PortHamiltonian.finelem(N,5, 0, 1)
eigval, eigvec = eigen(ph);
num_freq = frequencies(eigval)
@test abs(num_freq[2]-pi*3/2) < 1e-13

max_stars_repo_name: flavioluiz/phjulia

max_issues_repo_name: flavioluiz/phjulia

max_forks_repo_name: flavioluiz/phjulia


text:
#EasyPlotQwt base types & core functions
#-------------------------------------------------------------------------------

#==Constants
===============================================================================#

#TODO: Support transparent, or *read* plot background color somehow.
const COLOR_BACKGROUND = EasyPlot.COLOR_WHITE

const scalemap = Dict{Symbol, String}(
	:lin => "lin",
	:log => "log",
)

const linestylemap = Dict{Symbol, String}(
	:none    => "",
	:solid   => "-",
	:dash    => "--",
	:dot     => ":",
	:dashdot => "-.",
)

const markermap = Dict{Symbol, String}(
	:none      => "",
	:square    => "s",
	:diamond   => "d",
	:uarrow    => "^", :darrow => "v",
	:larrow    => "<", :rarrow => ">",
	:cross     => "+", :+ => "+",
	:diagcross => "x", :x => "x",
	:circle    => "o", :o => "o",
	:star      => "*", :* => "*",
)

struct FlagType{T}; end
const NOTFOUND = FlagType{:NOTFOUND}()

#==Base types
===============================================================================#
const NullOr{T} = Union{Nothing, T} #Simpler than Nullable

mutable struct EPAxes{T} <: EasyPlot.AbstractAxes{T}
	ref::Axes #Axes reference
	theme::EasyPlot.Theme
	eye::NullOr{EasyPlot.EyeAttributes}
end
EPAxes(style::Symbol, ref::Axes, theme::EasyPlot.Theme, eye=nothing) =
	EPAxes{style}(ref, theme, eye)

mutable struct WfrmAttributes
	title #Not label, for some reason
	color #linecolor
	linewidth
	linestyle
	marker
	markersize
	markerfacecolor
	markeredgecolor
#	markeredgewidth #Not supported
#	fillstyle #Not supported
#==Unknown options:
	shade, fitted, curvestyle, curvetype, baseline
==#
end
WfrmAttributes(;label=nothing,
	color=nothing, linewidth=nothing, linestyle=nothing,
	marker=nothing, markersize=nothing, markerfacecolor=nothing) =
	WfrmAttributes(label, color, linewidth, linestyle,
		marker, markersize, markerfacecolor, color
	)

#==Helper functions
===============================================================================#
const HEX_CODES = UInt8[
	'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
]
function int2mplcolorstr(v::UInt)
	result = Array{UInt8}(undef, 7) #6Hex+hash character
	result[1] = '#'
	for i in length(result):-1:2
		result[i] = HEX_CODES[(v & 0xF)+1]
		v >>= 4
	end
	return String(result)
end

function mapcolor(v::Colorant)
	v = convert(RGB24, v)
	return int2mplcolorstr(UInt(v.color))
end

mapfacecolor(v) = mapcolor(v) #In case we want to diverge

#Linewidth:
maplinewidth(w) = w
maplinewidth(::Nothing) = maplinewidth(1) #default

#Marker size:
mapmarkersize(sz) = 5*sz
mapmarkersize(::Nothing) = mapmarkersize(1)

function maplinestyle(v::Symbol)
	result = get(linestylemap, v, NOTFOUND)
	if NOTFOUND == result
		info("Line style not supported")
		result = maplinestyle(nothing)
	end
	return result
end
maplinestyle(::Nothing) = "-" #default

function mapmarkershape(v::Symbol)
	result = get(markermap, v, NOTFOUND)
	if "" == result
		result = nothing
	elseif NOTFOUND == result
		info("Marker shape not supported")
		result = "o" #Use some supported marker
	end
	return result
end
mapmarkershape(::Nothing) = mapmarkershape(:none) #default (no marker)

function WfrmAttributes(id::String, attr::EasyPlot.WfrmAttributes)
	#TODO: Figure out how to support transparency:
	markerfacecolor = attr.glyphfillcolor==EasyPlot.COLOR_TRANSPARENT ?
		mapfacecolor(COLOR_BACKGROUND) : mapfacecolor(attr.glyphfillcolor)

	return WfrmAttributes(label=id,
		color=mapcolor(attr.linecolor),
		linewidth=maplinewidth(attr.linewidth),
		linestyle=maplinestyle(attr.linestyle),
		marker=mapmarkershape(attr.glyphshape),
		markersize=mapmarkersize(attr.glyphsize),
		markerfacecolor=markerfacecolor,
	)
end

function _setlim(ax::Axes, setfn::Symbol, _min, _max)
	hasmin = nothing!=min
	hasmax = nothing!=max
	if hasmin && hasmax
		ax[setfn] = (_min, _max)
	elseif (hasmin && !hasmax) || (hasmax && !hasmin)
		warn("Partial limits not supported: $setfn($_min, $_max)")
	end
end

#==Rendering functions
===============================================================================#

#Add DataF1 results:
function _addwfrm(ax::Axes, d::DataF1, a::WfrmAttributes)
	kwargs = Any[]
	for attrib in fieldnames(a)
		v = getfield(a,attrib)

		if v != nothing
			push!(kwargs, tuple(attrib, v))
		end
	end

	#TODO: is result of add the "wfrm" we want to return?
	wfrm = Curve(d.x, d.y; kwargs...)
	add(ax, wfrm)
	return wfrm
end

#Called by EasyPlot, for each individual DataF1 ∈ DataMD.
function EasyPlot.addwfrm(ax::EPAxes, d::DataF1, id::String,
	la::EasyPlot.LineAttributes, ga::EasyPlot.GlyphAttributes)
	attr = EasyPlot.WfrmAttributes(ax.theme, la, ga) #Apply theme to attributes
	qwtattr = WfrmAttributes(id, attr) #Attributes understood by Qwt
	_addwfrm(ax.ref, d, qwtattr)
end

function rendersubplot(ax::Axes, subplot::EasyPlot.Subplot, theme::EasyPlot.Theme)
	#TODO: add support for supblot title

	#TODO Ugly: setting defaults like this should be done in EasyPlot
	ep = nothing
	if :eye == subplot.style
		ep = subplot.eye
		if nothing == ep.teye; ep.teye = ep.tbit; end
	end

	axes = EPAxes(subplot.style, ax, theme, ep)

	for (i, wfrm) in enumerate(subplot.wfrmlist)
		EasyPlot.addwfrm(axes, wfrm, i)
	end

	srca = subplot.axes

	#Update axis limits:
	_lim = ax[:xlimits]
	(xmin, xmax) = _lim != nothing ? _lim : (nothing, nothing)
	if srca.xmin != nothing; xmin = srca.xmin; end
	if srca.xmax != nothing; xmax = srca.xmax; end
	_lim = ax[:ylimits]
	(ymin, ymax) = _lim != nothing ? _lim : (nothing, nothing)
	if srca.ymin != nothing; ymin = srca.ymin; end
	if srca.ymax != nothing; ymax = srca.ymax; end
	_setlim(ax, :set_xlim, xmin, xmax)
	_setlim(ax, :set_ylim, ymin, ymax)

	#Apply x/y scales:
	ax[:xscale] = scalemap[srca.xscale]
	ax[:yscale] = scalemap[srca.yscale]

	#Apply x/y labels:
	if srca.xlabel != nothing; ax[:xlabel] = (string(srca.xlabel), ""); end
	if srca.ylabel != nothing; ax[:ylabel] = (string(srca.ylabel), ""); end

	return ax
end

function render(fig::Figure, eplot::EasyPlot.Plot)
	ncols = eplot.ncolumns
	nrows = div(length(eplot.subplots)-1, ncols)+1
	subplotidx = 0

	for s in eplot.subplots
#		row = div(subplotidx, ncols) + 1
#		col = mod(subplotidx, ncols) + 1
		ax = subplot(fig, nrows, ncols, subplotidx+1)
		rendersubplot(ax, s, eplot.theme)
		if eplot.displaylegend; add(ax, :legend); end
		subplotidx += 1
	end

	return fig
end

#Last line