text:
function partialbridgeode!(::R3, t, L, Σ, Lt, Mt, μt, P)
    m, d = size(L)
    Lt[end] = L
    Mt[end] = inv(Σ)
    M⁺ = Σ
    μt[end] = μ = 0*L[:,1]

    @assert size(L[:,1]) == (m,)
    @assert size(L*L') == size(Σ) == (m, m)

    for i in length(t)-1:-1:1
        dt = t[i] - t[i+1]
        L = kernelr3((t, y, P) -> -y*B(t, P), t[i+1], L, dt, P)
        M⁺ = kernelr3((t, y, (L,P)) -> -outer(L*σ(t, P)), t[i+1], M⁺, dt, (L,P))
        μ = kernelr3((t, y, (L,P)) -> -L*β(t, P), t[i+1], μ, dt, (L,P))

        Lt[i] = L
        Mt[i] = inv(M⁺)
        μt[i] = μ
    end
    Lt, Mt, μt
 end

"""
    PartialBridge
Guided proposal process for diffusion bridge using backward recursion.
    PartialBridge(tt, P, Pt,  L, v, Σ)
Guided proposal process for a partial diffusion bridge of `P` to `v` on
the time grid `tt` using guiding term derived from linear process `Pt`.
Simulate with `bridge!`.
"""
struct PartialBridge{T,R,R2,Tv,TL,TM} <: ContinuousTimeProcess{T}
    Target::R
    Pt::R2
    tt::Vector{Float64}
    v::Tv
    L::Vector{TL}
    M::Vector{TM}
    μ::Vector{Tv}

    function PartialBridge(tt_, P, Pt, L::TL, v::Tv, Σ::TM = Bridge.outer(zero(v))) where {TL, Tv, TM}
        tt = collect(tt_)
        N = length(tt)
        Lt = zeros(TL, N)
        Mt = zeros(TM, N)
        μt = zeros(Tv, N)
        partialbridgeode!(R3(), tt, L, Σ, Lt, Mt, μt, Pt)
        new{Bridge.valtype(P),typeof(P),typeof(Pt),Tv,TL,TM}(P, Pt, tt, v, Lt, Mt, μt)
    end
end

function _b((i,t)::IndexedTime, x, P::PartialBridge)
    b(P.tt[i], x, P.Target) + a(P.tt[i], x, P.Target)*P.L[i]'*P.M[i]*(P.v - P.μ[i] -  P.L[i]*x)
end

r((i,t)::IndexedTime, x, P::PartialBridge) = P.L[i]'*P.M[i]*(P.v - P.μ[i] -  P.L[i]*x)
H((i,t)::IndexedTime, x, P::PartialBridge) = P.L[i]' * P.M[i] * P.L[i]

σ(t, x, P::PartialBridge) = σ(t, x, P.Target)
a(t, x, P::PartialBridge) = a(t, x, P.Target)
Γ(t, x, P::PartialBridge) = Γ(t, x, P.Target)
constdiff(P::PartialBridge) = constdiff(P.Target) && constdiff(P.Pt)

function llikelihood(::LeftRule, Xcirc::SamplePath, Po::PartialBridge; skip = 0)
    tt = Xcirc.tt
    xx = Xcirc.yy

    som::Float64 = 0.
    for i in 1:length(tt)-1-skip #skip last value, summing over n-1 elements
        s = tt[i]
        x = xx[i]
        r = Bridge.r((i,s), x, Po)

        som += dot( _b((i,s), x, target(Po)) - _b((i,s), x, auxiliary(Po)), r ) * (tt[i+1]-tt[i])

        if !constdiff(Po)
            H = Bridge.H((i,s), x, Po)
            A = Bridge.a((i,s), x, target(Po)) - Bridge.a((i,s),  auxiliary(Po))
            som -= 0.5*tr(A *H ) * (tt[i+1]-tt[i])
            som += 0.5*( r'*A*r ) * (tt[i+1]-tt[i])
        end
    end
    som
end


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

using Base: @deprecate, depwarn

# 1.0 deprecations
function (+)(x::AbstractArray{<:TimeType}, y::GeneralPeriod)
    # depwarn("non-broadcasted arithmetic is deprecated for Dates.TimeType; use broadcasting instead", nothing)
    x .+ y
end
function (+)(x::StridedArray{<:GeneralPeriod}, y::TimeType)
    # depwarn("non-broadcasted arithmetic is deprecated for Dates.TimeType; use broadcasting instead", nothing)
    x .+ y
end
function (+)(y::GeneralPeriod, x::AbstractArray{<:TimeType})
    # depwarn("non-broadcasted arithmetic is deprecated for Dates.TimeType; use broadcasting instead", nothing)
    x .+ y
end
function (+)(y::TimeType, x::StridedArray{<:GeneralPeriod})
    # depwarn("non-broadcasted arithmetic is deprecated for Dates.TimeType; use broadcasting instead", nothing)
    x .+ y
end
function (-)(x::AbstractArray{<:TimeType}, y::GeneralPeriod)
    # depwarn("non-broadcasted arithmetic is deprecated for Dates.TimeType; use broadcasting instead", nothing)
    x .- y
end
function (-)(x::StridedArray{<:GeneralPeriod}, y::TimeType)
    # depwarn("non-broadcasted arithmetic is deprecated for Dates.TimeType; use broadcasting instead", nothing)
    x .- y
end

# TimeType, AbstractArray{TimeType}
function (-)(x::AbstractArray{T}, y::T) where {T<:TimeType}
    # depwarn("non-broadcasted arithmetic is deprecated for Dates.TimeType; use broadcasting instead", nothing)
    x .- y
end
function (-)(y::T, x::AbstractArray{T}) where {T<:TimeType}
    # depwarn("non-broadcasted arithmetic is deprecated for Dates.TimeType; use broadcasting instead", nothing)
    y .- x
end

for (op, Ty, Tz) in ((:*, Real, :P),
                   (:/, :P, Float64), (:/, Real, :P))
    @eval begin
        function ($op)(X::StridedArray{P}, y::$Ty) where P<:Period
            # depwarn("non-broadcasted arithmetic is deprecated for Dates.TimeType; use broadcasting instead", nothing)
            Z = similar(X, $Tz)
            for (Idst, Isrc) in zip(eachindex(Z), eachindex(X))
                @inbounds Z[Idst] = ($op)(X[Isrc], y)
            end
            return Z
        end
    end
end

function (+)(x::StridedArray{<:GeneralPeriod})
    # depwarn("non-broadcasted operations are deprecated for Dates.TimeType; use broadcasting instead", nothing)
    x
end

for op in (:+, :-)
    @eval begin
        function ($op)(X::StridedArray{<:GeneralPeriod}, Y::StridedArray{<:GeneralPeriod})
            # depwarn("non-broadcasted arithmetic is deprecated for Dates.TimeType; use broadcasting instead", nothing)
            reshape(CompoundPeriod[($op)(x, y) for (x, y) in zip(X, Y)], promote_shape(size(X), size(Y)))
        end
    end
end

ext: jl

max_stars_repo_name: TimoLarson/julia

max_issues_repo_name: AsForMe/julia

max_forks_repo_name: AsForMe/julia


text:
@testset "upper/lower recasting" begin
end

@testset "inner/outer recasting" begin
   import SigmoidNumbers: isulp, glb, lub

   @test SigmoidNumbers.@d_lower(WP(0b0010) → WP(0b0100)) == Sigmoid{4,0,:outward_exact}(0b0010)
   @test SigmoidNumbers.@d_lower(WP(0b0011) → WP(0b0100)) == Sigmoid{4,0,:outward_ulp}(0b0010)
   @test SigmoidNumbers.@d_lower(WP(0b1100) → WP(0b1110)) == Sigmoid{4,0,:inward_exact}(0b1100)
   @test SigmoidNumbers.@d_lower(WP(0b1101) → WP(0b1110)) == Sigmoid{4,0,:inward_ulp}(0b1100)
   @test SigmoidNumbers.@d_lower(WP(0b0000) → WP(0b1100)) == Sigmoid{4,0,:outward_exact}(0b0000)
   @test SigmoidNumbers.@d_lower(WP(0b0000) → WP(0b0000)) == Sigmoid{4,0,:inward_exact}(0b0000)
   @test SigmoidNumbers.@d_lower(WP(0b1000) → WP(0b1100)) == Sigmoid{4,0,:inward_exact}(0b1000)
   @test SigmoidNumbers.@d_lower(WP(0b1000) → WP(0b1000)) == Sigmoid{4,0,:outward_exact}(0b1000)

   @test SigmoidNumbers.@d_upper(WP(0b0010) → WP(0b0100)) == Sigmoid{4,0,:inward_exact}(0b0100)
   @test SigmoidNumbers.@d_upper(WP(0b0010) → WP(0b0011)) == Sigmoid{4,0,:inward_ulp}(0b00100)
   @test SigmoidNumbers.@d_upper(WP(0b1100) → WP(0b1110)) == Sigmoid{4,0,:outward_exact}(0b1110)
   @test SigmoidNumbers.@d_upper(WP(0b1100) → WP(0b1101)) == Sigmoid{4,0,:outward_ulp}(0b1110)
   @test SigmoidNumbers.@d_upper(WP(0b1100) → WP(0b0000)) == Sigmoid{4,0,:outward_exact}(0b0000)
   @test SigmoidNumbers.@d_upper(WP(0b0000) → WP(0b0000)) == Sigmoid{4,0,:inward_exact}(0b0000)
   @test SigmoidNumbers.@d_upper(WP(0b0100) → WP(0b1000)) == Sigmoid{4,0,:inward_exact}(0b1000)
   @test SigmoidNumbers.@d_upper(WP(0b1000) → WP(0b1000)) == Sigmoid{4,0,:outward_exact}(0b1000)

   @test SigmoidNumbers.@d_upper(WP(0b1101) → WP(0b0100)) == Sigmoid{4,0,:inward_exact}(0b0100)
end

max_stars_repo_name: ityonemo/SigmoidNumbers

max_issues_repo_name: ityonemo/SigmoidNumbers

max_forks_repo_name: ityonemo/SigmoidNumbers


text:
module Dec7Part2

function extract_chunks(x::String, pattern::Regex)::Array{String,1}
    matches = split(x, pattern)
    return strip.(String.(matches))
end

function capture_groups(x::String, pattern::Regex)::Tuple{String,String}
    matching = match(pattern, x)
    return strip(String(matching[1])), strip(String(matching[2]))
end

function extract_colors_number(x::String)::Tuple{Union{Nothing,Int64},Union{Nothing,String}}
    if x == "no other bags."
        return nothing, nothing
    end
    count, color = capture_groups(x, r"(\d)\s?([a-zA-Z ]+)\s?bags?")
    return parse(Int64, count), color
end

function get_parent_child(x::String)::Tuple
    strings = extract_chunks(x, r"bags contain|,")
    child_count = extract_colors_number.(strings[2:end])
    parent = strings[1]
    return parent, child_count
end

function get_nested_counts(x::Dict, key::String)::Union{Nothing,Int64}
    total = 0
    for child in x[key]
        count = child[1]
        child_name = child[2]
        if count === nothing
            return 1
        end
        total += count * get_nested_counts(x, child_name)
    end
    return total + 1
end

function main(file_path::String)::Int64
    baggage_conditions = readlines(file_path)
    parents_child = Dict(get_parent_child.(baggage_conditions))
    bags = get_nested_counts(parents_child, "shiny gold") - 1
    return bags
end
end


text:
module DataGenerator

import Distributions; D = Distributions
using LinearAlgebra

export linregdata, logregdata, poissonregdata

eye(p) = Matrix(1.0 * I, p, p)

defaultβ(p) = collect(range(-1, stop=1, length=p))

function linregdata(n, p; β = defaultβ(p), V = eye(p), μ = zeros(p), σ = 1.0)
	x = rand(D.MvNormal(μ, V), n)'
	y = x * β + σ * randn(n)
	return x, y, β
end

function logregdata(n, p, sgn = true; β = defaultβ(p), V = eye(p), μ = zeros(p))
	x = rand(D.MvNormal(μ, V), n)'
	y = Float64[rand(D.Bernoulli(1 / (1 + exp(-η)))) for η in x * β]
	if sgn
		y = 2y .- 1
	end
	return x, y, β
end

function poissonregdata(n, p, β = defaultβ(p), V = eye(p), μ = zeros(p))
	x = rand(D.MvNormal(μ, V), n)'
	y = Float64[rand(D.Poisson(exp(η))) for η in x * β]
	return x, y, β
end

end


text:
#####
##### The turbulence closure proposed by Smagorinsky and Lilly.
##### We also call this 'Constant Smagorinsky'.
#####

"""
    SmagorinskyLilly{FT} <: AbstractSmagorinsky{FT}

Parameters for the Smagorinsky-Lilly turbulence closure.
"""
struct SmagorinskyLilly{FT, P, K} <: AbstractSmagorinsky{FT}
     C :: FT
    Cb :: FT
    Pr :: P
     ν :: FT
     κ :: K

    function SmagorinskyLilly{FT}(C, Cb, Pr, ν, κ) where FT
        Pr = convert_diffusivity(FT, Pr)
         κ = convert_diffusivity(FT, κ)
        return new{FT, typeof(Pr), typeof(κ)}(C, Cb, Pr, ν, κ)
    end
end

"""
    SmagorinskyLilly([FT=Float64;] C=0.23, Pr=1, ν=1.05e-6, κ=1.46e-7)

Return a `SmagorinskyLilly` type associated with the turbulence closure proposed by
Lilly (1962) and Smagorinsky (1958, 1963), which has an eddy viscosity of the form

    `νₑ = (C * Δᶠ)² * √(2Σ²) * √(1 - Cb * N² / Σ²) + ν`,

and an eddy diffusivity of the form

    `κₑ = (νₑ - ν) / Pr + κ`

where `Δᶠ` is the filter width, `Σ² = ΣᵢⱼΣᵢⱼ` is the double dot product of
the strain tensor `Σᵢⱼ`, `Pr` is the turbulent Prandtl number, and `N²` is
the total buoyancy gradient, and `Cb` is a constant the multiplies the Richardson number
modification to the eddy viscosity.

Keyword arguments
=================
    - `C`  : Model constant
    - `Cb` : Buoyancy term multipler (`Cb = 0` turns it off, `Cb ≠ 0` turns it on.
             Typically `Cb=1/Pr`.)
    - `Pr` : Turbulent Prandtl numbers for each tracer. Either a constant applied to every
             tracer, or a `NamedTuple` with fields for each tracer individually.
    - `ν`  : Constant background viscosity for momentum
    - `κ`  : Constant background diffusivity for tracer. Can either be a single number
             applied to all tracers, or `NamedTuple` of diffusivities corresponding to each
             tracer.

References
==========
Smagorinsky, J. "On the numerical integration of the primitive equations of motion for
    baroclinic flow in a closed region." Monthly Weather Review (1958)

Lilly, D. K. "On the numerical simulation of buoyant convection." Tellus (1962)

Smagorinsky, J. "General circulation experiments with the primitive equations: I.
    The basic experiment." Monthly weather review (1963)
"""
SmagorinskyLilly(FT=Float64; C=0.23, Cb=1.0, Pr=1.0, ν=ν₀, κ=κ₀) =
    SmagorinskyLilly{FT}(C, Cb, Pr, ν, κ)

function with_tracers(tracers, closure::SmagorinskyLilly{FT}) where FT
    Pr = tracer_diffusivities(tracers, closure.Pr)
     κ = tracer_diffusivities(tracers, closure.κ)
    return SmagorinskyLilly{FT}(closure.C, closure.Cb, Pr, closure.ν, κ)
end

"""
    stability(N², Σ², Cb)

Return the stability function

    ``\$ \\sqrt(1 - Cb N^2 / Σ^2 ) \$``

when ``N^2 > 0``, and 1 otherwise.
"""
@inline stability(N²::FT, Σ²::FT, Cb::FT) where FT =
    ifelse(Σ²==0, zero(FT), sqrt(one(FT) - stability_factor(N², Σ², Cb)))

@inline stability_factor(N²::FT, Σ²::FT, Cb::FT) where FT = min(one(FT), Cb * N² / Σ²)

"""
    νₑ(ς, C, Δᶠ, Σ²)

Return the eddy viscosity for constant Smagorinsky
given the stability `ς`, model constant `C`,
filter width `Δᶠ`, and strain tensor dot product `Σ²`.
"""
@inline νₑ_deardorff(ς, C, Δᶠ, Σ²) = ς * (C*Δᶠ)^2 * sqrt(2Σ²)

@inline function νᶜᶜᶜ(i, j, k, grid, clo::SmagorinskyLilly{FT}, buoyancy, U, C) where FT
    Σ² = ΣᵢⱼΣᵢⱼᶜᶜᶜ(i, j, k, grid, U.u, U.v, U.w)
    N² = max(zero(FT), ℑzᵃᵃᶜ(i, j, k, grid, ∂z_b, buoyancy, C))
    Δᶠ = Δᶠ_ccc(i, j, k, grid, clo)
     ς = stability(N², Σ², clo.Cb) # Use unity Prandtl number.

    return νₑ_deardorff(ς, clo.C, Δᶠ, Σ²) + clo.ν
end

#####
##### Abstract Smagorinsky functionality
#####

"""
    κ_∂x_c(i, j, k, grid, c, tracer, closure, νₑ)

Return `κ ∂x c`, where `κ` is a function that computes
diffusivity at cell centers (location `ccc`), and `c` is an array of scalar
data located at cell centers.
"""
@inline function κ_∂x_c(i, j, k, grid, closure::AbstractSmagorinsky,
                        c, ::Val{tracer_index}, νₑ) where tracer_index

    @inbounds Pr = closure.Pr[tracer_index]
    @inbounds κ = closure.κ[tracer_index]

    νₑ = ℑxᶠᵃᵃ(i, j, k, grid, νₑ, closure)
    κₑ = (νₑ - closure.ν) / Pr + κ
    ∂x_c = ∂xᶠᵃᵃ(i, j, k, grid, c)
    return κₑ * ∂x_c
end

"""
    κ_∂y_c(i, j, k, grid, c, tracer, closure, νₑ)

Return `κ ∂y c`, where `κ` is a function that computes
diffusivity at cell centers (location `ccc`), and `c` is an array of scalar
data located at cell centers.
"""
@inline function κ_∂y_c(i, j, k, grid, closure::AbstractSmagorinsky,
                        c, ::Val{tracer_index}, νₑ) where tracer_index

    @inbounds Pr = closure.Pr[tracer_index]
    @inbounds κ = closure.κ[tracer_index]

    νₑ = ℑyᵃᶠᵃ(i, j, k, grid, νₑ, closure)
    κₑ = (νₑ - closure.ν) / Pr + κ
    ∂y_c = ∂yᵃᶠᵃ(i, j, k, grid, c)
    return κₑ * ∂y_c
end

"""
    κ_∂z_c(i, j, k, grid, c, tracer, closure, νₑ)

Return `κ ∂z c`, where `κ` is a function that computes
diffusivity at cell centers (location `ccc`), and `c` is an array of scalar
data located at cell centers.
"""
@inline function κ_∂z_c(i, j, k, grid, closure::AbstractSmagorinsky,
                        c, ::Val{tracer_index}, νₑ) where tracer_index

    @inbounds Pr = closure.Pr[tracer_index]
    @inbounds κ = closure.κ[tracer_index]

    νₑ = ℑzᵃᵃᶠ(i, j, k, grid, νₑ, closure)
    κₑ = (νₑ - closure.ν) / Pr + κ
    ∂z_c = ∂zᵃᵃᶠ(i, j, k, grid, c)
    return κₑ * ∂z_c
end

"""
    ∇_κ_∇c(i, j, k, grid, clock, c, closure, diffusivities)

Return the diffusive flux divergence `∇ ⋅ (κ ∇ c)` for the turbulence
`closure`, where `c` is an array of scalar data located at cell centers.
"""
@inline ∇_κ_∇c(i, j, k, grid, clock, closure::AbstractSmagorinsky, c, tracer_index,
               diffusivities, args...) = (

      ∂xᶜᵃᵃ(i, j, k, grid, κ_∂x_c, closure, c, tracer_index, diffusivities.νₑ)
    + ∂yᵃᶜᵃ(i, j, k, grid, κ_∂y_c, closure, c, tracer_index, diffusivities.νₑ)
    + ∂zᵃᵃᶜ(i, j, k, grid, κ_∂z_c, closure, c, tracer_index, diffusivities.νₑ)

)

function calculate_diffusivities!(K, arch, grid, closure::AbstractSmagorinsky, buoyancy, U, C)

    event = launch!(arch, grid, :xyz, calculate_nonlinear_viscosity!, K.νₑ, grid, closure, buoyancy, U, C,
                    dependencies=Event(device(arch)))

    wait(device(arch), event)

    return nothing
end

#####
##### Double dot product of strain on cell edges (currently unused)
#####

"Return the filter width for Constant Smagorinsky on a Regular Cartesian grid."
@inline Δᶠ(i, j, k, grid::RegularCartesianGrid, ::AbstractSmagorinsky) = geo_mean_Δᶠ(i, j, k, grid)

# Temporarily set filter widths to cell-size (rather than distance between cell centers, etc.)
const Δᶠ_ccc = Δᶠ
const Δᶠ_ccf = Δᶠ
const Δᶠ_ffc = Δᶠ
const Δᶠ_fcf = Δᶠ
const Δᶠ_cff = Δᶠ

# tr_Σ² : ccc
#   Σ₁₂ : ffc
#   Σ₁₃ : fcf
#   Σ₂₃ : cff

"Return the double dot product of strain at `ccc`."
@inline function ΣᵢⱼΣᵢⱼᶜᶜᶜ(i, j, k, grid, u, v, w)
    return (
                    tr_Σ²(i, j, k, grid, u, v, w)
            + 2 * ℑxyᶜᶜᵃ(i, j, k, grid, Σ₁₂², u, v, w)
            + 2 * ℑxzᶜᵃᶜ(i, j, k, grid, Σ₁₃², u, v, w)
            + 2 * ℑyzᵃᶜᶜ(i, j, k, grid, Σ₂₃², u, v, w)
            )
end

"Return the double dot product of strain at `ffc`."
@inline function ΣᵢⱼΣᵢⱼᶠᶠᶜ(i, j, k, grid, u, v, w)
    return (
                  ℑxyᶠᶠᵃ(i, j, k, grid, tr_Σ², u, v, w)
            + 2 *    Σ₁₂²(i, j, k, grid, u, v, w)
            + 2 * ℑyzᵃᶠᶜ(i, j, k, grid, Σ₁₃², u, v, w)
            + 2 * ℑxzᶠᵃᶜ(i, j, k, grid, Σ₂₃², u, v, w)
            )
end

"Return the double dot product of strain at `fcf`."
@inline function ΣᵢⱼΣᵢⱼᶠᶜᶠ(i, j, k, grid, u, v, w)
    return (
                  ℑxzᶠᵃᶠ(i, j, k, grid, tr_Σ², u, v, w)
            + 2 * ℑyzᵃᶜᶠ(i, j, k, grid, Σ₁₂², u, v, w)
            + 2 *    Σ₁₃²(i, j, k, grid, u, v, w)
            + 2 * ℑxyᶠᶜᵃ(i, j, k, grid, Σ₂₃², u, v, w)
            )
end

"Return the double dot product of strain at `cff`."
@inline function ΣᵢⱼΣᵢⱼᶜᶠᶠ(i, j, k, grid, u, v, w)
    return (
                  ℑyzᵃᶠᶠ(i, j, k, grid, tr_Σ², u, v, w)
            + 2 * ℑxzᶜᵃᶠ(i, j, k, grid, Σ₁₂², u, v, w)
            + 2 * ℑxyᶜᶠᵃ(i, j, k, grid, Σ₁₃², u, v, w)
            + 2 *    Σ₂₃²(i, j, k, grid, u, v, w)
            )
end

@inline function ΣᵢⱼΣᵢⱼᶜᶜᶠ(i, j, k, grid, u, v, w)
    return (
                    ℑzᵃᵃᶠ(i, j, k, grid, tr_Σ², u, v, w)
            + 2 * ℑxyzᶜᶜᶠ(i, j, k, grid, Σ₁₂², u, v, w)
            + 2 *   ℑxᶜᵃᵃ(i, j, k, grid, Σ₁₃², u, v, w)
            + 2 *   ℑyᵃᶜᵃ(i, j, k, grid, Σ₂₃², u, v, w)
            )
end

Base.show(io::IO, closure::SmagorinskyLilly) =
    print(io, "SmagorinskyLilly: C=$(closure.C), Cb=$(closure.Cb), Pr=$(closure.Pr), ν=$(closure.ν), κ=$(closure.κ)")


text:
# http://web.mit.edu/puzzle/www/2012/puzzles/phantom_of_the_operator/solution/
@testset "phantom of the operator meta" begin
    f = best_feature(wordlist(IOBuffer("""
        FIRESTONE
        CLINTON
        UNION
        MERCURY
        PERSHING
        CHERRY
        VALLEY
        VIKING
        TERMINAL
        """)))
    @test f.description == "is a Ma Bell recommended telephone exchange name"
end


text:
"""initialises netCDF files for data output."""
function output_ini(u,v,η,sst)
    # only process with rank 0 defines the netCDF file
    if output #&& prank == 0

        # Attributes
        Dictu = Dict{String,Any}("description"=>"Data from shallow-water model juls.")
        Dictu["details"] = "Cartesian coordinates, f or beta-plane, Arakawa C-grid"
        Dictu["reference"] = "github.com/milankl/juls"

        Dictu["nx"] = nx
        Dictu["Lx"] = Lx
        Dictu["L_ratio"] = L_ratio
        Dictu["delta"] = Δ

        Dictu["halo"] = halo
        Dictu["haloeta"] = haloη
        Dictu["halosstx"] = halosstx
        Dictu["halossty"] = halossty

        Dictu["g"] = gravity
        Dictu["water_depth"] = water_depth
        Dictu["phi"] = ϕ
        Dictu["density"] = ρ

        Dictu["wind_forcing"] = wind_forcing
        Dictu["Fx0"] = Fx0

        Dictu["topography_feature"] = topography_feature
        Dictu["topofeat_height"] = topofeat_height
        Dictu["topofeat_width"] = topofeat_width

        Dictu["surface_forcing"] = string(surface_forcing)
        Dictu["t_relax"] = t_relax
        Dictu["eta_refh"] = η_refh
        Dictu["η_refw"] = η_refw

        Dictu["Numtype"] = string(Numtype)
        Dictu["output_dt"] = output_dt
        Dictu["nout"] = nout
        Dictu["nadvstep"] = nadvstep

        Dictu["RKo"] = RKo
        Dictu["cfl"] = cfl
        Dictu["Ndays"] = Ndays

        Dictu["bc_x"] = bc_x
        Dictu["lbc"] = lbc

        Dictu["adv_scheme"] = adv_scheme

        Dictu["bottom_friction"] = bottom_friction
        Dictu["drag"] = drag
        Dictu["taudrag"] = τdrag

        Dictu["diffusion"] = diffusion
        Dictu["nuConst"] = ν_const
        Dictu["c_smag"] = c_smag

        Dictu["tracer_advcetion"] = string(tracer_advection)
        Dictu["tracer_relaxation"] = string(tracer_relaxation)
        Dictu["injection_region"] = injection_region
        Dictu["sstrestart"] = string(sstrestart)
        Dictu["Uadv"] = Uadv
        Dictu["SSTmax"] = SSTmax
        Dictu["SSTmin"] = SSTmin
        Dictu["tauSST"] = τSST
        Dictu["SSTw"] = SSTw
        Dictu["SSTphi"] = SSTϕ

        Dictu["initial_cond"] = initial_cond
        Dictu["init_run_id"] = init_run_id
        Dictu["initpath"] = initpath

        if "u" in output_vars
            xudim = NcDim("x",nux,values=x_u)
            yudim = NcDim("y",nuy,values=y_u)
            tdim = NcDim("t",0,unlimited=true)

            uvar = NcVar("u",[xudim,yudim,tdim],t=Float32)
            tvaru = NcVar("t",tdim,t=Int64)

            ncu = NetCDF.create(runpath*"u.nc",[uvar,tvaru],mode=NC_NETCDF4)
            NetCDF.putatt(ncu,"u",Dict("units"=>"m/s","long_name"=>"zonal velocity"))
        else
            ncu = 0
        end

        if "v" in output_vars
            xvdim = NcDim("x",nvx,values=x_v)
            yvdim = NcDim("y",nvy,values=y_v)
            tdim = NcDim("t",0,unlimited=true)

            vvar = NcVar("v",[xvdim,yvdim,tdim],t=Float32)
            tvarv = NcVar("t",tdim,t=Int64)

            ncv = NetCDF.create(runpath*"v.nc",[vvar,tvarv],mode=NC_NETCDF4)
            NetCDF.putatt(ncv,"v",Dict("units"=>"m/s","long_name"=>"meridional velocity"))
        else
            ncv = 0
        end

        if "eta" in output_vars
            xTdim = NcDim("x",nx,values=x_T)
            yTdim = NcDim("y",ny,values=y_T)
            tdim = NcDim("t",0,unlimited=true)

            ηvar = NcVar("eta",[xTdim,yTdim,tdim],t=Float32)
            tvarη = NcVar("t",tdim,t=Int64)

            ncη = NetCDF.create(runpath*"eta.nc",[ηvar,tvarη],mode=NC_NETCDF4)
            NetCDF.putatt(ncη,"eta",Dict("units"=>"m","long_name"=>"sea surface height"))
        else
            ncη = 0
        end

        if "sst" in output_vars
            xTdim = NcDim("x",nx,values=x_T)
            yTdim = NcDim("y",ny,values=y_T)
            tdim = NcDim("t",0,unlimited=true)

            ηvar = NcVar("sst",[xTdim,yTdim,tdim],t=Float32)
            tvarη = NcVar("t",tdim,t=Int64)

            ncsst = NetCDF.create(runpath*"sst.nc",[ηvar,tvarη],mode=NC_NETCDF4)
            NetCDF.putatt(ncsst,"sst",Dict("units"=>"1","long_name"=>"sea surface temperature"))
        else
            ncsst = 0
        end

        ncs = (ncu,ncv,ncη,ncsst)

        # Write attributes and units
        for nc in ncs
            if nc != 0
                NetCDF.putatt(nc,"global",Dictu)
                NetCDF.putatt(nc,"t",Dict("units"=>"s","long_name"=>"time"))
                NetCDF.putatt(nc,"x",Dict("units"=>"m","long_name"=>"zonal coordinate"))
                NetCDF.putatt(nc,"y",Dict("units"=>"m","long_name"=>"meridional coordinate"))
            end
        end

        # write initial conditions
        iout = 1   # counter for output time steps
        ncs,iout = output_nc(ncs,u,v,η,sst,0,iout)

        # also output scripts
        scripts_output()

        return ncs,iout
    else
        return nothing, nothing
    end
end

""" Writes data to a netCDF file."""
function output_nc(ncs,u,v,η,sst,i,iout)

    # if nprocs > 1
    #     #TODO MPI Gather data
    #     #TODO rename u,v,η necessary? To distinguish between the loval u,v,η and the gathered u,v,η?
    # end

    # output only every nout time steps
    # only process 0 will do the output
    if i % nout == 0 && output #&& prank == 0

        # cut off the halo
        if ncs[1] != 0
            NetCDF.putvar(ncs[1],"u",Float32.(u[halo+1:end-halo,halo+1:end-halo]),start=[1,1,iout],count=[-1,-1,1])
        end
        if ncs[2] != 0
            NetCDF.putvar(ncs[2],"v",Float32.(v[halo+1:end-halo,halo+1:end-halo]),start=[1,1,iout],count=[-1,-1,1])
        end
        if ncs[3] != 0
            NetCDF.putvar(ncs[3],"eta",Float32.(η[haloη+1:end-haloη,haloη+1:end-haloη]),start=[1,1,iout],count=[-1,-1,1])
        end
        if ncs[4] != 0
            NetCDF.putvar(ncs[4],"sst",Float32.(sst[halosstx+1:end-halosstx,halossty+1:end-halossty]),start=[1,1,iout],count=[-1,-1,1])
        end

        for nc in ncs
            if nc !=0
                NetCDF.putvar(nc,"t",Int64[i*dtint],start=[iout])
                NetCDF.sync(nc)     # sync to view netcdf while model is still running
            end
        end

        iout += 1
    end

    #TODO MPI Barrier, Waitall?

    return ncs,iout
end

"""Closes netCDF and progress.txt files."""
function output_close(ncs,progrtxt)
    if output #&& prank == 0
        for nc in ncs
            if nc !=0
                NetCDF.close(nc)
            end
        end
        println("All data stored.")
        write(progrtxt,"All data stored.")
        close(progrtxt)
    end
end

"""Checks output folders to determine a 4-digit run id number."""
function get_run_id_path(order="continue",run_id=nothing)

    """Finds the first gap in a list of integers."""
    function gap(a::Array{Int,1})
        try
            return minimum([i for i in minimum(a):maximum(a) if ~(i in a)])
        catch
            return maximum(a)+1
        end
    end

    # only process rank 0 checks existing folders
    if output #&& prank == 0
        runlist = filter(x->startswith(x,"run"),readdir(outpath))
        existing_runs = [parse(Int,id[4:end]) for id in runlist]
        if length(existing_runs) == 0           # if no runfolder exists yet
            runpath = outpath*"run0000/"
            mkdir(runpath)
            return 0,runpath
        else                                    # create next folder
            if order == "fill"  # find the smallest gap in runfolders
                run_id = gap(existing_runs)
                runpath = outpath*"run"*@sprintf("%04d",run_id)*"/"
                mkdir(runpath)

            elseif order == "specific" # specify the run_id as input argument
                runpath = outpath*"run"*@sprintf("%04d",run_id)*"/"
                try # create folder if not existent
                    mkdir(runpath)
                catch # else rm folder and create new one
                    rm(runpath,recursive=true)
                    mkdir(runpath)
                end

            elseif order == "continue" # find largest folder and count one up
                run_id = maximum(existing_runs)+1
                runpath = outpath*"run"*@sprintf("%04d",run_id)*"/"
                mkdir(runpath)
            else
                throw(error("Order $order is not valid for get_run_id_path(), chose continue, specific or fill."))
            end
            return run_id,runpath
        end
    else
        return 0,"no runpath"
    end
end

#TODO in ensemble mode, the .jl files might have changed since the start and do not correspond to what
#TODO is actually executed!
"""Archives all .jl files of juls in the output folder to make runs reproducible."""
function scripts_output()
    if output #&& prank == 0
        # copy all files in juls main folder
        mkdir(runpath*"scripts")
        for juliafile in filter(x->endswith(x,".jl"),readdir())
            cp(juliafile,runpath*"scripts/"*juliafile)
        end

        # and also in the src folder
        mkdir(runpath*"scripts/src")
        for juliafile in filter(x->endswith(x,".jl"),readdir("src"))
            cp("src/"*juliafile,runpath*"scripts/src/"*juliafile)
        end
    end
end

max_stars_repo_name: eschnett/juls

max_issues_repo_name: eschnett/juls

max_forks_repo_name: eschnett/juls


text:
"""
**Check Rewiring parameters**

This function will check that all the required rewiring parameters are present
"""
function check_rewiring_parameters(rewireP,rewireMethod)
  if rewireMethod == :ADBM
    required_keys = [
    :e,
    :a_adbm,
    :ai,
    :aj,
    :b,
    :h_adbm,
    :hi,
    :hj,
    :n,
    :ni,
    :Nmethod,
    :Hmethod,
    :rewire_method,
    :adbm_trigger,
    :costMat,
    :extinctions,
    :extinctionstime,
    :tmpA]
    if rewireP[:adbm_trigger] == :interval
      append!(required_keys, [:adbm_interval, :rewiretime])
    end
  elseif rewireMethod ∈ [:Gilljam, :DS]
    required_keys = [
    :rewire_method,
    :similarity,
    :specialistPrefMag,
    :extinctions,
    :extinctionstime,
    :tmpA,
    :preferenceMethod,
    :cost,
    :costMat,
    :specialistPref]
  elseif rewireMethod ∈ [:stan, :DO]
    required_keys = [
    :rewire_method,
    :extinctions,
    :extinctionstime,
    :tmpA]
  end

  if rewireMethod ∈ [:Gilljam, :ADBM, :stan, :DO, :DS]
    for k in required_keys
      @assert get(rewireP, k, nothing) != nothing
    end
  end

end


text:
instrs = split(strip(read("input.txt", String)), "\n")

function interpret(instrs)
    acc = 0
    ip = 1
    visited = Set()

    while ip <= length(instrs)
        if ip in visited
            return (acc, false)
        end

        push!(visited, ip)
        instr = instrs[ip]

        if startswith(instr, "acc")
            acc += parse(Int, instr[5:end])
        end

        if startswith(instr, "jmp")
            ip += parse(Int, instr[5:end])
        else
            ip += 1
        end
    end

    (acc, true)
end

interpret(instrs)[1]

function correct(instrs)
    for i in eachindex(instrs)
        instr = instrs[i]
        if startswith(instr, "acc")
            continue
        end
        newinstr = (startswith(instr, "jmp") ? "nop" : "jmp") * instr[4:end]
        newinstrs = deepcopy(instrs)
        newinstrs[i] = newinstr
        result = interpret(newinstrs)
        if result[2]
            return result[1]
        end
    end
end

correct(instrs)

max_stars_repo_name: stellartux/advent-of-code

max_issues_repo_name: stellartux/advent-of-code

max_forks_repo_name: stellartux/advent-of-code


text:
module lmv
"""
Export matrices and vectors to disk so that they can be read by the code dcsrmv.
This code performs sparse CSR matrix- dense vector multiplication on the GPU.

"""

using SparseArrays

function write_vector(filename::String, u::Array{T, 1};
                                        verbose::Bool=false) where T
        fh = open(filename, "w")
        write(fh, sizeof(T))
        n = length(u)
        bytes = write(fh, UInt64(n))
        write(fh, u)
        close(fh)
        if verbose
                println("Wrote vector of length ", n, " to ", filename)
        end
end

function read_vector(type, filename::String; verbose::Bool=false)
        fh = open(filename, "r")
        type_size = read(fh, UInt64)
        n = read(fh, UInt64)
        @assert(sizeof(type) == type_size)
        u = zeros(type, n)
        for i=1:n
                @inbounds u[i] = read(fh, type)
        end
        close(fh)
        if verbose
                println("read vector of length ", n, " from ", filename)
        end
        return u
end

function write_csr_matrix(filename::String, A::SparseMatrixCSC{Tv, Ti};
                          verbose::Bool=false) where {Tv, Ti}
        fh = open(filename, "w")
        B = copy(A')
        write(fh, sizeof(Tv))
        write(fh, sizeof(Ti))
        write(fh, UInt64(B.n))
        write(fh, UInt64(B.m))
        nnz = length(B.nzval)
        write(fh, UInt64(nnz))

        # Convert to zero-indexing
        rows =  B.colptr .- 1
        cols =  B.rowval .- 1

        write(fh, Ti.(rows))
        write(fh, Ti.(cols))
        write(fh, Tv.(B.nzval))
        close(fh)

        if verbose
                println("Wrote CSR matrix <", A.m, " x ", A.n, "> containing ",
                        nnz, " non-zeros to ", filename)
        end
end

function read_csr_matrix(Tv, Ti, filename::String; verbose=false::Bool)
        fh = open(filename, "r")
        tv = read(fh, UInt64)
        ti = read(fh, UInt64)
        m = read(fh, UInt64)
        n = read(fh, UInt64)
        nnz = read(fh, UInt64)

        colptr = zeros(Ti, m + 1)
        for i=1:(m + 1)
                colptr[i] = read(fh, Ti) + 1
        end

        rowval = zeros(Ti, nnz)
        for i=1:nnz
                rowval[i] = read(fh, Ti) + 1
        end

        nzval = zeros(Tv, nnz)
        for i=1:nnz
                nzval[i] = read(fh, Tv)
        end
        close(fh)

        B = SparseMatrixCSC(n, m, colptr, rowval, nzval)
        A = copy(B')

        if verbose
                println("Read CSR matrix <", A.m, " x ", A.n, "> containing ",
                        nnz, " non-zeros from ", filename)
        end

        return A
end

function write_dense_matrix(filename::String, A::Array{Float64, 2};
                                              verbose=false::Bool)

        fh = open(filename, "w")
        m = size(A, 1)
        n = size(A, 2)
        write(fh, m)
        write(fh, n)
        write(fh, A)
        close(fh)

        if verbose
                println("Wrote dense matrix <", m, " x ", n, "> to ", filename)
        end

end

function read_dense_matrix(filename::String; verbose=false::Bool)

        fh = open(filename, "r")
        m = read(fh, Int64)
        n = read(fh, Int64)
        A = zeros(m, n)
        for j=1:n
                for i=1:m
                        @inbounds A[i,j] = read(fh, Float64)
                end
        end

        if verbose
                println("Read dense matrix <", m, " x ", n, "> to ", filename)
        end

        return A

end

function write_config(filename::String, args::Dict; verbose=false::Bool,
                                        skip_types=false::Bool)
        fh = open(filename, "w")
        for arg in args
                if skip_types == true
                        println(fh, arg.first, "=", arg.second)
                else
                        println(fh, arg.first, ":", string(typeof(arg.second)),
                                    "=", arg.second)
                end
        end
        close(fh)

        if verbose
                println("Wrote configuration file: ", filename)
        end
end

function read_config(filename::String; verbose=false::Bool)
        fh = open(filename, "r")
        cfg = Dict()
        for ln in eachline(fh)
                name, tmp = split(ln, ":")
                typ, value = split(tmp, "=")
                typ = eval(Meta.parse(typ))
                cfg[name] = parse(typ, value)
        end
        close(fh)

        if verbose
                println("Read configuration file: ", filename)
        end

        return cfg
end

end

max_stars_repo_name: ooreilly/sbpjl

max_issues_repo_name: ooreilly/sbpjl

max_forks_repo_name: ooreilly/sbpjl


text:
#=
For each mode, the first letter h or d specifies whether the matrix
data (and subsequent linear solver algorithms) will run on the host or
device. The second D or F specifies the precision (double or float) of
the Matrix data. The third D or F specifies the precision (double or float) of
any Vector (including right-handside or unknown vectors). The last I specifies
that 32-bit int types are used for all indices. Future versions of AMGX may
support additional precisions or mixed precision modes
=#

@enum Mode begin
    hDDI = Int(API.AMGX_mode_hDDI)
    hDFI = Int(API.AMGX_mode_hDFI)
    hFFI = Int(API.AMGX_mode_hFFI)
    dDDI = Int(API.AMGX_mode_dDDI)
    dDFI = Int(API.AMGX_mode_dDFI)
    dFFI = Int(API.AMGX_mode_dFFI)
    # TODO: Add support for theses:
    #=
    hIDI = Int(API.AMGX_mode_hIDI)
    hIFI = Int(API.AMGX_mode_hIFI)
    dIDI = Int(API.AMGX_mode_dIDI)
    dIFI = Int(API.AMGX_mode_dIFI)
    hZZI = Int(API.AMGX_mode_hZZI)
    hZCI = Int(API.AMGX_mode_hZCI)
    hCCI = Int(API.AMGX_mode_hCCI)
    dZZI = Int(API.AMGX_mode_dZZI)
    dZCI = Int(API.AMGX_mode_dZCI)
    dCCI = Int(API.AMGX_mode_dCCI)
    =#
end

function _type(c::Char)
    c == 'D' ? Float64 :
    c == 'F' ? Float32 :
    c == 'I' ? Cint :
    c == 'Z' ? ComplexF64 :
    c == 'C' ? ComplexF32 :
    error("unexpected char '$c'")
end

vector_type(m::Mode) = _type(string(m)[3])
matrix_type(m::Mode) = _type(string(m)[2])


text:
# To run this script, `cd` to the `./test/fixtures` directory and then, from the Julia terminal, `include("./runner.jl")`.

import JSON

# Small values:
x = linspace( 1e-36, 1e-38, 1007 )

y = Array( Any, length(x) )
z = Array( Any, length(x) )
for i in eachindex(x)
	# Mimic implicit type promotion in JavaScript where we need to cast a Float64 to a Float32 and then back to Float64 when writing out:
	f32 = convert( Float32, x[i] )
	o = frexp( f32 )
	y[i] = [ convert( Float64, o[1] ), o[2] ]
	z[i] = convert( Float64, f32 )
end

data = Dict([
	("x", z),
	("expected", y)
])

outfile = open("frexp_1e-36_1e-38.json", "w")
write( outfile, JSON.json(data) )
close( outfile );

# Medium values:
x = linspace( -1e3, 1e3, 1007 )

y = Array( Any, length(x) )
z = Array( Any, length(x) )
for i in eachindex(x)
	# Mimic implicit type promotion in JavaScript where we need to cast a Float64 to a Float32 and then back to Float64 when writing out:
	f32 = convert( Float32, x[i] )
	o = frexp( f32 )
	y[i] = [ convert( Float64, o[1] ), o[2] ]
	z[i] = convert( Float64, f32 )
end

data = Dict([
	("x", z),
	("expected", y)
])

outfile = open("frexp_-1e3_1e3.json", "w")
write( outfile, JSON.json(data) )
close( outfile );

# Large values:
x = linspace( 1e36, 1e38, 1007 )

y = Array( Any, length(x) )
z = Array( Any, length(x) )
for i in eachindex(x)
	# Mimic implicit type promotion in JavaScript where we need to cast a Float64 to a Float32 and then back to Float64 when writing out:
	f32 = convert( Float32, x[i] )
	o = frexp( f32 )
	y[i] = [ convert( Float64, o[1] ), o[2] ]
	z[i] = convert( Float64, f32 )
end

data = Dict([
	("x", z),
	("expected", y)
])

outfile = open("frexp_1e36_1e38.json", "w")
write( outfile, JSON.json(data) )
close( outfile );

# Subnormal values:
x = linspace( 1e-39, 1e-45, 1007 )

y = Array( Any, length(x) )
z = Array( Any, length(x) )
for i in eachindex(x)
	# Mimic implicit type promotion in JavaScript where we need to cast a Float64 to a Float32 and then back to Float64 when writing out:
	f32 = convert( Float32, x[i] )
	o = frexp( f32 )
	y[i] = [ convert( Float64, o[1] ), o[2] ]
	z[i] = convert( Float64, f32 )
end

data = Dict([
	("x", z),
	("expected", y)
])

outfile = open("frexp_1e-39_1e-45.json", "w")
write( outfile, JSON.json(data) )
close( outfile );