text:
module ModularPlane

using ExportAll
import Base.getindex, Base.size, Base.setindex!, Base.length, Base.+, Base.-, Base.*, Base.÷, Base.show, Base.print, Base.string, Base.println, Base.<, Base.>, Base.<=, Base.>=

# wraps numbers to stay between 1 <= y <= m
modp1(x::Integer, m::Integer) = x < 1 ? m + x % m : 1 + (x - 1) % m

"""
modular integer
where 1 <= val <= mod
"""
struct MInt <: Integer
    val::UInt8
    mod::UInt8
    MInt(val, mod) = 1 <= val <= mod ? new(val, mod) : new(modp1(val, mod), mod)
end

getindex(A::Matrix, i1::MInt, i2::MInt) = A[i1.val, i2.val]
function setindex!(A::Matrix, v::Number, i1::MInt, i2::MInt)
    A[i1.val, i2.val] = v
end
+(a::MInt, b::Integer) = MInt(a.val + b, a.mod)
+(b::Integer, a::MInt) = MInt(a.val + b, a.mod)
-(b::Integer, a::MInt) = MInt(b - a.val, a.mod)
-(a::MInt, b::Integer) = MInt(a.val - b, a.mod)
*(a::MInt, b::Integer) = MInt(a.val * b, a.mod)
*(b::Integer, a::MInt) = MInt(a.val * b, a.mod)
÷(b::Integer, a::MInt) = MInt(b ÷ a.val, a.mod)
÷(a::MInt, b::Integer) = MInt(a.val ÷ b, a.mod)
<(a::MInt, b::Integer) = a.val < b
<(b::Integer, a::MInt) = a.val > b
<(a::MInt, b::MInt) = a.val > b.val
>(a::MInt, b::Integer) = a.val > b
>(b::Integer, a::MInt) = a.val < b
>(a::MInt, b::MInt) = a.val > b.val
<=(a::MInt, b::Integer) = a.val <= b
<=(b::Integer, a::MInt) = a.val >= b
<=(a::MInt, b::MInt) = a.val <= b.val
>=(a::MInt, b::Integer) = a.val >= b
>=(b::Integer, a::MInt) = a.val <= b
>=(a::MInt, b::MInt) = a.val >= b.val

show(io::IO, a::MInt) = print(io, a.val, "%", a.mod)

"""
matrix indexer whose indexing wraps
"""
struct GridIndex
    I::Tuple{MInt, MInt}
    GridIndex(x::MInt, y::MInt) = new(Tuple((x, y)))
    GridIndex(tup::Tuple{MInt, MInt}) = new(tup)
end

getindex(A::Matrix, I::GridIndex) = A[I.I[1], I.I[2]]
function setindex!(A::Matrix, v::Number, I::GridIndex)
    A[I.I[1], I.I[2]] = v
end
@exportAll()

end

max_stars_repo_name: AlexTMallen/the-multiverse

max_issues_repo_name: AlexTMallen/the-multiverse

max_forks_repo_name: AlexTMallen/the-multiverse


text:
export PushEach, PushEachBut, PushNew, PushNewBut, PushStrategy

"""
    PushEach

`PushEach` update strategy specifies the strategy to emit new value each time an inner observable emit a new value

See also: [`combineLatest`](@ref), [`PushEachBut`](@ref), [`PushNew`](@ref), [`PushNewBut`](@ref), [`PushStrategy`](@ref)
"""
struct PushEach end

"""
    PushEachBut{I}

`PushEachBut` update strategy specifies the strategy to emit new value if and only if an inner observable with index `I` have a new value

See also: [`combineLatest`](@ref), [`PushEach`](@ref), [`PushNew`](@ref), [`PushNewBut`](@ref), [`PushStrategy`](@ref)
"""
struct PushEachBut{I} end

"""
    PushNew

`PushNew` update strategy specifies the strategy to emit new value if and only if all inner observables have a new value

See also: [`combineLatest`](@ref), [`PushEach`](@ref), [`PushEachBut`](@ref), [`PushNewBut`](@ref), [`PushStrategy`](@ref)
"""
struct PushNew end

"""
    PushNewBut{I}

`PushNewBut{I}` update strategy specifies the strategy to emit new value if and only if all inner observables except with index `I` have a new value

See also: [`combineLatest`](@ref), [`PushEach`](@ref), [`PushEachBut`](@ref), [`PushNew`](@ref), [`PushStrategy`](@ref)
"""
struct PushNewBut{I} end

"""
    PushStrategy(strategy::BitArray{1})

`PushStrategy` update strategy specifies the strategy to emit new value if and only if all inner observables with index such that `strategy[index] = false` have a new value

See also: [`combineLatest`](@ref), [`PushEach`](@ref), [`PushEachBut`](@ref), [`PushNew`](@ref), [`PushNewBut`](@ref), [`collectLatest`](@ref)
"""
struct PushStrategy
    strategy :: BitArray{1}
end

getustorage(::Type{T}) where T = getustorage(T, _staticlength(T))

## Generic updates structure

struct GenericUpdatesStatus
    cstatus  :: BitArray{1} # Completion status
    vstatus  :: BitArray{1} # Values status
    ustatus  :: BitArray{1} # Updates status

    GenericUpdatesStatus(nsize::Int) = new(falses(nsize), falses(nsize), falses(nsize))
end

getustorage(::Type{T}, ::Val{N}) where { T, N } = GenericUpdatesStatus(N)

cstatus(updates::GenericUpdatesStatus, index) = @inbounds updates.cstatus[index]
vstatus(updates::GenericUpdatesStatus, index) = @inbounds updates.vstatus[index]
ustatus(updates::GenericUpdatesStatus, index) = @inbounds updates.ustatus[index]

cstatus!(updates::GenericUpdatesStatus, index, v) = @inbounds updates.cstatus[index] = v
vstatus!(updates::GenericUpdatesStatus, index, v) = @inbounds updates.vstatus[index] = v
ustatus!(updates::GenericUpdatesStatus, index, v) = @inbounds updates.ustatus[index] = v

all_cstatus(updates::GenericUpdatesStatus) = all(updates.cstatus)
all_vstatus(updates::GenericUpdatesStatus) = all(updates.vstatus)
all_ustatus(updates::GenericUpdatesStatus) = all(updates.ustatus)

fill_cstatus!(updates::GenericUpdatesStatus, v) = fill!(updates.cstatus, v)
fill_vstatus!(updates::GenericUpdatesStatus, v) = fill!(updates.vstatus, v)
fill_ustatus!(updates::GenericUpdatesStatus, v) = fill!(updates.ustatus, v)

function push_update!(::Int, ::GenericUpdatesStatus, ::PushEach)
    return nothing
end

function push_update!(::Int, updates::GenericUpdatesStatus, ::PushEachBut{I}) where I
    vstatus!(updates, I, false)
    return nothing
end

function push_update!(nsize::Int, updates::GenericUpdatesStatus, ::PushNew)
    unsafe_copyto!(updates.vstatus, 1, updates.cstatus, 1, nsize)
    return nothing
end

function push_update!(nsize::Int, updates::GenericUpdatesStatus, ::PushNewBut{I}) where I
    push_update!(nsize, updates, PushNew())
    vstatus!(updates, I, true)
    return nothing
end

function push_update!(nsize::Int, updates::GenericUpdatesStatus, strategy::PushStrategy)
    push_update!(nsize, updates, PushNew())
    map!(|, updates.vstatus, updates.vstatus, strategy.strategy)
    return nothing
end

## Int8 updates structure

mutable struct UInt8UpdatesStatus
    mask     :: UInt8
    cstatus  :: UInt8 # Completion status
    vstatus  :: UInt8 # Values status
    ustatus  :: UInt8 # Updates status

    UInt8UpdatesStatus(mask) = new(mask, 0b00000000, 0b00000000, 0b00000000)
end

getustorage(::Type{T}, ::Val{1}) where { T } = UInt8UpdatesStatus(0b1)
getustorage(::Type{T}, ::Val{2}) where { T } = UInt8UpdatesStatus(0b11)
getustorage(::Type{T}, ::Val{3}) where { T } = UInt8UpdatesStatus(0b111)
getustorage(::Type{T}, ::Val{4}) where { T } = UInt8UpdatesStatus(0b1111)
getustorage(::Type{T}, ::Val{5}) where { T } = UInt8UpdatesStatus(0b11111)
getustorage(::Type{T}, ::Val{6}) where { T } = UInt8UpdatesStatus(0b111111)
getustorage(::Type{T}, ::Val{7}) where { T } = UInt8UpdatesStatus(0b1111111)
getustorage(::Type{T}, ::Val{8}) where { T } = UInt8UpdatesStatus(0b11111111)

@inline _testbit(x::UInt8, bit::UInt8)   = x & (1 << (7 & (bit - 1))) !== 0
@inline _testbit(x::UInt8, bit::Integer) = _testbit(x, bit % UInt8)

@inline _setbit(x::UInt8, bit::UInt8, v)   = v ? (x | (0b1 << (bit - 1))) : (x & (~(0b1 << (bit - 1))))
@inline _setbit(x::UInt8, bit::Integer, v) = _setbit(x, bit % UInt8, v)

cstatus(updates::UInt8UpdatesStatus, index) = _testbit(updates.cstatus, index)
vstatus(updates::UInt8UpdatesStatus, index) = _testbit(updates.vstatus, index)
ustatus(updates::UInt8UpdatesStatus, index) = _testbit(updates.ustatus, index)

cstatus!(updates::UInt8UpdatesStatus, index, v) = updates.cstatus = _setbit(updates.cstatus, index, v)
vstatus!(updates::UInt8UpdatesStatus, index, v) = updates.vstatus = _setbit(updates.vstatus, index, v)
ustatus!(updates::UInt8UpdatesStatus, index, v) = updates.ustatus = _setbit(updates.ustatus, index, v)

all_cstatus(updates::UInt8UpdatesStatus) = (updates.cstatus & updates.mask) === updates.mask
all_vstatus(updates::UInt8UpdatesStatus) = (updates.vstatus & updates.mask) === updates.mask
all_ustatus(updates::UInt8UpdatesStatus) = (updates.ustatus & updates.mask) === updates.mask

fill_cstatus!(updates::UInt8UpdatesStatus, v) = updates.cstatus = v ? updates.mask : ~(updates.mask)
fill_vstatus!(updates::UInt8UpdatesStatus, v) = updates.vstatus = v ? updates.mask : ~(updates.mask)
fill_ustatus!(updates::UInt8UpdatesStatus, v) = updates.ustatus = v ? updates.mask : ~(updates.mask)

function push_update!(::Int, ::UInt8UpdatesStatus, ::PushEach)
    return nothing
end

function push_update!(::Int, updates::UInt8UpdatesStatus, ::PushEachBut{I}) where I
    vstatus!(updates, I, false)
    return nothing
end

function push_update!(nsize::Int, updates::UInt8UpdatesStatus, ::PushNew)
    updates.vstatus = updates.cstatus
    return nothing
end

function push_update!(nsize::Int, updates::UInt8UpdatesStatus, ::PushNewBut{I}) where I
    push_update!(nsize, updates, PushNew())
    vstatus!(updates, I, true)
    return nothing
end

function push_update!(nsize::Int, updates::UInt8UpdatesStatus, strategy::PushStrategy)
    @assert length(strategy.strategy) <= 8
    push_update!(nsize, updates, PushNew())
    updates.vstatus = updates.vstatus | UInt8(first(strategy.strategy.chunks))
    return nothing
end

ext: jl


text:
module LightPropagation

using Parameters
using SpecialFunctions
using JLD
using ForwardDiff
using FastGaussQuadrature: gausslegendre

### Diffusion Theory

# Infinite
export fluence_DA_inf_CW
export fluence_DA_inf_TD

# Semi-infinite
export fluence_DA_semiinf_TD
export fluence_DA_semiinf_CW

export flux_DA_semiinf_CW
export flux_DA_semiinf_TD

# Slab
export fluence_DA_slab_CW
export fluence_DA_slab_TD

export flux_DA_slab_CW
export flux_DA_slab_TD

# Parallelepiped
export fluence_DA_paralpip_TD
export fluence_DA_paralpip_CW

# Layered cylinder
export fluence_DA_Nlay_cylinder_CW
export fluence_DA_Nlay_cylinder_TD

export flux_DA_Nlay_cylinder_CW
export flux_DA_Nlay_cylinder_TD

# g2 for DCS
export g1_DA_semiinf_CW, g1_DA_semiinf_TD
export g2_DA_semiinf_CW, g2_DA_semiinf_TD

export g1_DA_Nlay_cylinder_CW, g1_DA_Nlay_cylinder_TD
export g2_DA_Nlay_cylinder_CW, g2_DA_Nlay_cylinder_TD

# Structures
export Nlayer_cylinder
export DAsemiinf_DCS, Nlayer_cylinder_DCS

# Abstract types
export DiffusionParameters

# constants
export besselroots

#export getfit
#export load_asc_data
#export fitDTOF, DTOF_fitparams

include("forwardmodels/Diffusion Approximation/diffusionparameters.jl")

include("forwardmodels/Diffusion Approximation/Infinite/DAinfinite.jl")
include("forwardmodels/Diffusion Approximation/Semi-infinite/DAsemiinf.jl")
include("forwardmodels/Diffusion Approximation/Slab/DAslab.jl")
include("forwardmodels/Diffusion Approximation/Parallelepiped/DAparalpip.jl")

include("forwardmodels/Diffusion Approximation/transforms.jl")
include("forwardmodels/Diffusion Approximation/DAcylinder_layered.jl")

include("forwardmodels/Diffusion Approximation/DCS/semiinf.jl")
include("forwardmodels/Diffusion Approximation/DCS/layered_cylinder.jl")

const besselroots = load(joinpath(@__DIR__,"..", "src/forwardmodels/Diffusion Approximation/besselzeroroots.jld"))["besselroots"]

end


text:
##==============================================================================
## Partial Pose3 Priors
##==============================================================================
# Partial prior constraint on Z, Roll and Pitch
# ------------------------------------------------------------------------------

"""
    $(TYPEDEF)

Partial prior belief on Z, Roll, and Pitch of a `Pose3`.
"""
mutable struct PriorPose3ZRP{T1<:SamplableBelief,T2<:SamplableBelief} <: IncrementalInference.AbstractPrior
  z::T1
  rp::T2
  partial::Tuple{Int,Int,Int}
  PriorPose3ZRP{T1,T2}() where {T1, T2} = new{T1,T2}()
  PriorPose3ZRP{T1,T2}(z::T1,rp::T2) where {T1 <: IIF.SamplableBelief, T2 <: IIF.SamplableBelief} = new{T1,T2}(z, rp, (3,4,5))
end

PriorPose3ZRP(z::T1,rp::T2) where {T1 <: SamplableBelief, T2 <: SamplableBelief} = PriorPose3ZRP{T1,T2}(z, rp)

getManifold(::PriorPose3ZRP) = SpecialEuclidean(3)

#FIXME update to also only one measurement
function getSample(cf::CalcFactor{<:PriorPose3ZRP})

  M = getManifold(cf.factor)

  ϵ = identity_element(M)

  #Rotation part: roll and pitch
  r,p = rand(cf.factor.rp)
  R = Rotations.RotYX(p, r) #TODO confirm RotYX(p,r) or RotXY(r,p)

  # Translation part: Z
  T = [0; 0; rand(cf.factor.z)]

  return ProductRepr(T, R)
end

"""
    $TYPEDEF

Serialization type of `PriorPose3ZRP`.
"""
mutable struct PackedPriorPose3ZRP <: IIF.PackedInferenceType
  zdata::String
  rpdata::String
  PackedPriorPose3ZRP() = new()
  PackedPriorPose3ZRP(x1::AS,x2::AS) where {AS <:AbstractString} = new(x1,x2)
end
function convert(::Type{PriorPose3ZRP}, d::PackedPriorPose3ZRP)
  # TODO: Change out for extractdistributionJson
  PriorPose3ZRP( convert(SamplableBelief, d.zdata), convert(SamplableBelief, d.rpdata)  )
end
function convert(::Type{PackedPriorPose3ZRP}, d::PriorPose3ZRP)
  PackedPriorPose3ZRP( convert(PackedSamplableBelief, d.z), convert(PackedSamplableBelief, d.rp) )
end

function compare(a::PriorPose3ZRP, b::PriorPose3ZRP; tol::Float64=1e-10)
  TP = true
  TP = TP && compareDensity(a.rp, b.rp)
  TP = TP && compareDensity(a.z, b.z)
  TP = TP && norm(collect(a.partial)-collect(b.partial)) < tol
  return TP
end

##==============================================================================
## Partial Pose3 Pose3 Factors
##==============================================================================
# Partial pairwise constraint between poses X,Y,Yaw
# ------------------------------------------------------------------------------

"""
    $TYPEDEF

Partial factor between XY and Yaw of two Pose3 variables.

```
wR2 = wR1*1R2 = wR1*(1Rψ*Rθ*Rϕ)
wRz = wR1*1Rz
zRz = wRz \\ wR(Δψ)

M_R = SO(3)
δ(α,β,γ) = vee(M_R, R_0, log(M_R, R_0, zRz))

M = SE(3)
p0 = identity_element(M)
δ(x,y,z,α,β,γ) = vee(M, p0, log(M, p0, zRz))
```

"""
struct Pose3Pose3XYYaw{T <: SamplableBelief} <: IIF.AbstractManifoldMinimize
  Z::T
  # partial::Tuple{Int,Int,Int,Int,Int}
  partial::Tuple{Int,Int,Int}
end
Pose3Pose3XYYaw(xy::SamplableBelief, yaw::SamplableBelief) = error("Pose3Pose3XYYaw(xy::SamplableBelief, yaw::SamplableBelief) where {T1 <: , T2 <: IIF.SamplableBelief} is deprecated, use one belief")

# Lie exponentials (pqr) are all three affected by changes in Yaw
# Pose3Pose3XYYaw(z::SamplableBelief) = Pose3Pose3XYYaw(z, (1,2,4,5,6))   # (1,2,6))
Pose3Pose3XYYaw(z::SamplableBelief) = Pose3Pose3XYYaw(z, (1,2,6))

function getSample(cf::CalcFactor{<:Pose3Pose3XYYaw})
  return sampleTangent(getManifold(cf.factor), cf.factor.Z)
end

getManifold(::Pose3Pose3XYYaw) = SpecialEuclidean(2)

## NOTE, Yaw only works if you assume a preordained global reference point, such as identity_element(Pose3)
function (cfo::CalcFactor{<:Pose3Pose3XYYaw})(X, wTp, wTq )
  #
  M = SpecialEuclidean(2)

  rx = normalize(view(wTp.parts[2],1:2, 1))
  R = SA[rx[1] -rx[2];
         rx[2]  rx[1]]
  p = ProductRepr(view(wTp.parts[1], 1:2), R)

  rx = normalize(view(wTq.parts[2],1:2, 1))
  R = SA[rx[1] -rx[2];
         rx[2]  rx[1]]
  q = ProductRepr(view(wTq.parts[1], 1:2), R)

  q̂ = Manifolds.compose(M, p, exp(M, identity_element(M, p), X))
  #TODO allocalte for vee! see Manifolds #412, fix for AD
  Xc = zeros(3)
  vee!(M, Xc, q, log(M, q, q̂))
  return Xc

end

## Old code and other ideas:
  # # Yaw is around the positive z axis
  # ##
  # # new Manifolds code (tests failing)
  # M3 = SpecialEuclidean(3)
  # M2 = SpecialEuclidean(2)

  # e3 = identity_element(M3, wTp)
  # e2 = identity_element(M2)

  # wRpψ_2  = Rotations.RotZ( TU.convert(Euler,  TU.SO3(wTp.parts[2])).Y )[1:2,1:2]
  # wTp_2  = ProductRepr(wTp.parts[1][1:2],   wRpψ_2)
  # wTqhat = Manifolds.compose(M2, wTp_2, exp(M2, e2, X))

  # wRqψ_2  = Rotations.RotZ( TU.convert(Euler,  TU.SO3(wTq.parts[2])).Y )[1:2,1:2]
  # wTq_2  = ProductRepr(wTq.parts[1][1:2],   wRqψ_2)
  # qhatTq = Manifolds.compose(M2, inv(M2, wTqhat), wTq_2)

  # #TODO allocate for vee! see Manifolds #412, fix for AD
  # Xc = zeros(3)
  # vee!(M2, Xc, e2, log(M2, e2, qhatTq))
  # return Xc

  # Old YPR coordinate code, < v"0.16"
  # wXjhat = SE2(wXi[[1;2;6]]) * SE2(meas[1:3])
  # jXjhat = SE2(wXj[[1;2;6]]) \ wXjhat
  # return se2vee(jXjhat)

"""
    $TYPEDEF

Serialization type of Pose3Pose3XYYaw.
"""
mutable struct PackedPose3Pose3XYYaw <: IncrementalInference.PackedInferenceType
  Z::String
  PackedPose3Pose3XYYaw() = new()
  PackedPose3Pose3XYYaw(Z::String) = new(Z)
end

function convert(::Type{<:Pose3Pose3XYYaw}, d::PackedPose3Pose3XYYaw)
  return Pose3Pose3XYYaw( convert(SamplableBelief, d.Z))
end

function convert(::Type{PackedPose3Pose3XYYaw}, d::Pose3Pose3XYYaw)
  return PackedPose3Pose3XYYaw( convert(PackedSamplableBelief, d.Z))
end

function compare(a::Pose3Pose3XYYaw, b::Pose3Pose3XYYaw; tol::Float64=1e-10)
  TP = true
  TP = TP && compareDensity(a.Z, b.Z)
  TP = TP && norm(collect(a.partial)-collect(b.partial)) < tol
  return TP
end

##==============================================================================
##
##==============================================================================
#TODO what is this, can it be removed? Moved here from above

"""
Converter: PriorPose3ZRP::Dict{String, Any} -> PriorPose3ZRP

DevNotes
- FIXME drop _evalType approach, use convert(SamplableBelief, obj) instead?
"""
function convert(::Type{<:PriorPose3ZRP}, fact::Dict{String, Any})
    rp = fact["measurement"][1]
    z = fact["measurement"][2]
    # FIXME drop _evalType
    rp = convert(_evalType(rp["distType"]), rp)
    z = convert(_evalType(z["distType"]), z)
    return PriorPose3ZRP(rp, z)
end

"""
Converter: PriorPose3ZRP::Dict{String, Any} -> PriorPose3ZRP
"""
function convert(::Type{Dict{String, Any}}, fact::PriorPose3ZRP)
    pf = Dict{String, Any}(
        "measurement" => [
            convert(Dict{String, Any}, fact.rp),
            convert(Dict{String, Any}, fact.z)
        ],
        "factorType" => "PriorPose3ZRP"
    )
    return pf
end

"""
    $SIGNATURES

Converter: Dict{String, Any} -> Pose3Pose3XYYaw
"""
function convert(::Type{Dict{String, Any}}, fact::Pose3Pose3XYYaw)
    pf = Dict{String, Any}(
        "measurement" => [
            convert(Dict{String, Any}, fact.xy),
            convert(Dict{String, Any}, fact.yaw)
        ],
        "factorType" => "Pose3Pose3XYYaw"
    )
    return pf
end

"""
    $SIGNATURES

Converter: Pose3Pose3XYYaw -> Dict{String, Any}

DevNotes
- FIXME stop using _evalType, see DFG #590
"""
function convert(::Type{<:Pose3Pose3XYYaw}, fact::Dict{String, Any})
    xy = fact["measurement"][1]
    yaw = fact["measurement"][2]
    xy = convert(_evalType(xy["distType"]), xy)
    yaw = convert(_evalType(yaw["distType"]), yaw)
    return PriorPose3ZRP(xy, yaw)
end


text:
module GtkSourceWidget

export GtkSourceLanguage, GtkSourceLanguageManager, GtkSourceBuffer,
       GtkSourceView, GtkSourceCompletionItem,
       GtkSourceStyleSchemeManager, GtkSourceStyleScheme

export @GtkSourceLanguage, @GtkSourceLanguageManager, @GtkSourceBuffer,
       @GtkSourceView, @GtkSourceCompletionItem,
       @GtkSourceStyleSchemeManager, @GtkSourceStyleScheme

export scheme, language, show_line_numbers!, auto_indent!, style_scheme, style_scheme!,
       max_undo_levels, max_undo_levels!, undo!, redo!, canundo, canredo, undomanager,
       highlight_current_line!, highlight_matching_brackets

using Gtk

import ..Gtk: suffix

const GObject = Gtk.GObject

if Gtk.gtk_version == 3
    if OS_NAME == :Windows
        const libgtksourceview = "libgtksourceview-3.0-0"
	else
        const libgtksourceview = "libgtksourceview-3.0"
    end
else
    error("Unsupported Gtk version $gtk_version")
end

### GtkSourceLanguage

Gtk.@Gtype GtkSourceLanguage libgtksourceview gtk_source_language

### GtkSourceLanguageManager

Gtk.@Gtype GtkSourceLanguageManager libgtksourceview gtk_source_language_manager
function GtkSourceLanguageManagerLeaf(default=true)
  if default
    GtkSourceLanguageManagerLeaf(
      ccall((:gtk_source_language_manager_get_default,libgtksourceview),Ptr{GObject},()))
  else
    GtkSourceLanguageManagerLeaf(
      ccall((:gtk_source_language_manager_new,libgtksourceview),Ptr{GObject},()))
  end
end

language(manager::GtkSourceLanguageManager, id::String) = @GtkSourceLanguage(
    ccall((:gtk_source_language_manager_get_language,libgtksourceview),Ptr{GObject},
          (Ptr{GObject},Ptr{Uint8}),manager,bytestring(id)))

### GtkSourceStyleScheme

Gtk.@Gtype GtkSourceStyleScheme libgtksourceview gtk_source_style_scheme

### GtkSourceStyleSchemeManager

Gtk.@Gtype GtkSourceStyleSchemeManager libgtksourceview gtk_source_style_scheme_manager
function GtkSourceStyleSchemeManagerLeaf(default=true)
  if default
    GtkSourceStyleSchemeManagerLeaf(
      ccall((:gtk_source_style_scheme_manager_get_default,libgtksourceview),Ptr{GObject},()))
  else
    GtkSourceStyleSchemeManagerLeaf(
      ccall((:gtk_source_style_scheme_manager_get_new,libgtksourceview),Ptr{GObject},()))
  end
end

style_scheme(manager::GtkSourceStyleSchemeManager, scheme_id::String) = @GtkSourceStyleScheme(
    ccall((:gtk_source_style_scheme_manager_get_scheme,libgtksourceview),Ptr{GObject},
          (Ptr{GObject},Ptr{Uint8}),manager,bytestring(scheme_id)))

### GtkSourceUndoManager

### This is a hack!!!
type GtkSourceUndoManagerI
  handle::Ptr{Void}
end

undo!(manager::GtkSourceUndoManagerI) =
  ccall((:gtk_source_undo_manager_undo,libgtksourceview),Void,
        (Ptr{Void},),manager.handle)

redo!(manager::GtkSourceUndoManagerI) =
  ccall((:gtk_source_undo_manager_redo,libgtksourceview),Void,
        (Ptr{Void},),manager.handle)

canundo(manager::GtkSourceUndoManagerI) = bool(
  ccall((:gtk_source_undo_manager_can_undo,libgtksourceview),Cint,
        (Ptr{Void},),manager.handle))

canredo(manager::GtkSourceUndoManagerI) = bool(
  ccall((:gtk_source_undo_manager_can_redo,libgtksourceview),Cint,
        (Ptr{Void},),manager.handle))

### GtkSourceBuffer

Gtk.@Gtype GtkSourceBuffer libgtksourceview gtk_source_buffer
GtkSourceBufferLeaf() = GtkSourceBufferLeaf(
     ccall((:gtk_source_buffer_new,libgtksourceview),Ptr{GObject}, (Ptr{Void},), C_NULL) )

GtkSourceBufferLeaf(lang::GtkSourceLanguage) = GtkSourceBufferLeaf(
     ccall((:gtk_source_buffer_new_with_language,libgtksourceview),Ptr{GObject},
           (Ptr{GObject},), lang) )

highlight_syntax(buffer::GtkSourceBuffer, highlight::Bool) =
  ccall((:gtk_source_buffer_set_highlight_syntax,libgtksourceview),Ptr{GObject},
        (Ptr{GObject},Cint),buffer,int32(highlight))

highlight_matching_brackets(buffer::GtkSourceBuffer, highlight::Bool) =
  ccall((:gtk_source_buffer_set_highlight_matching_brackets,libgtksourceview),Ptr{GObject},
        (Ptr{GObject},Cint),buffer,int32(highlight))

style_scheme!(buffer::GtkSourceBuffer, scheme::GtkSourceStyleScheme) =
  ccall((:gtk_source_buffer_set_style_scheme,libgtksourceview),Void,
        (Ptr{GObject},Ptr{GObject}),buffer,scheme)

max_undo_levels(buffer::GtkSourceBuffer) =
  ccall((:gtk_source_buffer_get_max_undo_levels,libgtksourceview),Cint,
        (Ptr{GObject},),buffer)

max_undo_levels!(buffer::GtkSourceBuffer, levels::Integer) =
  ccall((:gtk_source_buffer_set_max_undo_levels,libgtksourceview),Void,
        (Ptr{GObject},Cint),buffer,levels)

undo!(buffer::GtkSourceBuffer) =
  ccall((:gtk_source_buffer_undo,libgtksourceview),Void,
        (Ptr{GObject},),buffer)

redo!(buffer::GtkSourceBuffer) =
  ccall((:gtk_source_buffer_redo,libgtksourceview),Void,
        (Ptr{GObject},),buffer)

canundo(buffer::GtkSourceBuffer) = bool(
  ccall((:gtk_source_buffer_can_undo,libgtksourceview),Cint,
        (Ptr{GObject},),buffer))

canredo(buffer::GtkSourceBuffer) = bool(
  ccall((:gtk_source_buffer_can_redo,libgtksourceview),Cint,
        (Ptr{GObject},),buffer))

undomanager(buffer::GtkSourceBuffer) = GtkSourceUndoManagerI(
  ccall((:gtk_source_buffer_get_undo_manager,libgtksourceview),Ptr{Void},
        (Ptr{GObject},),buffer))

### GtkSourceView

Gtk.@Gtype GtkSourceView libgtksourceview gtk_source_view
GtkSourceViewLeaf(buffer=@GtkSourceBuffer()) = @GtkSourceView(
    ccall((:gtk_source_view_new_with_buffer,libgtksourceview),Ptr{GObject},(Ptr{GObject},),buffer))

show_line_numbers!(view::GtkSourceView, show::Bool) =
  ccall((:gtk_source_view_set_show_line_numbers,libgtksourceview),Ptr{GObject},
        (Ptr{GObject},Cint),view,int32(show))

auto_indent!(view::GtkSourceView, auto::Bool) =
  ccall((:gtk_source_view_set_auto_indent,libgtksourceview),Ptr{GObject},
        (Ptr{GObject},Cint),view,int32(auto))

highlight_current_line!(view::GtkSourceView, hl::Bool) =
  ccall((:gtk_source_view_set_highlight_current_line,libgtksourceview),Ptr{GObject},
        (Ptr{GObject},Cint),view,int32(hl))

### GtkSourceCompletionContext

baremodule GtkSourceCompletionActivation
    const GTK_SOURCE_COMPLETION_ACTIVATION_NONE = 0
    const GTK_SOURCE_COMPLETION_ACTIVATION_INTERACTIVE = 1
    const GTK_SOURCE_COMPLETION_ACTIVATION_USER_REQUESTED = 2
end

Gtk.@Gtype GtkSourceCompletionContext libgtksourceview gtk_source_completion_context

#function add_proposals(context::GtkSourceCompletionContext, provider::GtkSourceCompletionProvider,
#                       proposals::GList, finished::Bool)
#  ccall((:gtk_source_completion_context_add_proposals,libgtksourceview),Void,
#        (Ptr{GObject},Ptr{GObject}, Ptr{GList},Cint),context, provider, &proposals, finished)
#end

#getiter(context::GtkSourceCompletionContext, iter::GtkTextIter) =
#   ccall((:gtk_source_completion_context_get_iter,libgtksourceview),Void,
#        (Ptr{GObject},Ptr{Void}),context, iter)

getactivation(context::GtkSourceCompletionContext) =
   ccall((:gtk_source_completion_context_get_activation,libgtksourceview),Cint,
        (Ptr{GObject},),context)

### GtkSourceCompletionItem

Gtk.@Gtype GtkSourceCompletionItem libgtksourceview gtk_source_completion_item
GtkSourceCompletionItemLeaf(label::String, text::String) = GtkSourceCompletionItemLeaf(
    ccall((:gtk_source_completion_item_new,libgtksourceview),Ptr{GObject},
          (Ptr{Uint8},Ptr{Uint8},Ptr{Void},Ptr{Uint8}),
           bytestring(label),bytestring(text),C_NULL,C_NULL))

end # module


text:
using NeuralQuantum
using LinearAlgebra, SparseArrays
using Test

@testset "KLocalOperator" begin
mat1 = [0.0 0.0; 0.1 0.0]
mat2 = [0.5 0.1; 0.1 0.0]
matsum = mat1 + mat2

sts = [1]
hilb_dims = [2]

op = KLocalOperatorRow(sts, hilb_dims, mat1)
op2 = KLocalOperatorRow(sts, hilb_dims, mat2)

ops = KLocalOperatorSum(op)
ops2 = ops + op2
@test length(NeuralQuantum.operators(ops)) == 1
@test first(NeuralQuantum.operators(ops2)).mat == matsum

# Check that index works for a single site
check = sparse(zeros(size(matsum)))
v = NAryState(2, 1)
for i=1:spacedimension(v)
    set_index!(v, i)
    diffs = row_valdiff_index(ops2, v)
    for (mel,j)=diffs
        check[i,j] += mel
    end
end
@test check == matsum

# check that the reconstructed matrix is fine
check = sparse(zeros(size(matsum)))
v = NAryState(Float64, 2, 1)
for i=1:spacedimension(v)
    set_index!(v, i)
    for (mel, changes) = row_valdiff(ops2, v)
        set_index!(v, i)
        for (id,val) = changes
            setat!(v, id, val)
        end
        j = index(v)
        check[i,j] += mel
    end
end
@test check == matsum

# check that by kroneckering times identity it's fine
ms = kron(Matrix(I, 2, 2), matsum)
#ms = kron(matsum, Matrix(I, 2, 2))
check = sparse(zeros(size(ms)))
v = NAryState(Float64, 2, 2)
for i=1:spacedimension(v)
    set_index!(v, i)
    for (mel, changes) = row_valdiff(ops2, v)
        set_index!(v, i)
        for (id,val)=changes
            setat!(v, id, val)
        end
        j = index(v)
        check[i,j] += mel
    end
end
@test check == ms

mat12 = kron(mat1, mat2)
op12 = KLocalOperatorRow([1,2], [2,2], mat12)
check = sparse(zeros(size(mat12)))
v = NAryState(Float64, 2, 2)
for i=1:spacedimension(v)
    set_index!(v, i)
    for (mel, changes) = row_valdiff(op12, v)
        set_index!(v, i)
        for (id,val)=changes
            setat!(v, id, val)
        end
        j = index(v)
        check[i,j] += mel
    end
end
@test check == mat12

op3 = KLocalOperatorRow([2], hilb_dims, mat2)
m3 = kron(mat2, Matrix(I, 2, 2))
ms = kron(Matrix(I, 2, 2), matsum)

mtot = m3 #ms + m3
opstot = op3 #ops2 + op3

check = sparse(zeros(size(mtot)))
v = NAryState(Float64, 2, 2)
for i=1:spacedimension(v)
    set_index!(v, i)
    for (mel, changes) = row_valdiff(opstot, v)
        set_index!(v, i)
        for (id,val)=changes
            setat!(v, id, val)
        end
        j = index(v)
        check[i,j] += mel
    end
end
@test check == m3

end


text:
module RocketCompleteObservableTest

using Test
using Rocket

include("../test_helpers.jl")

@testset "CompletedObservable" begin

    println("Testing: completed")

    struct DummyScheduler <: Rocket.AbstractScheduler end

    @testset begin
        @test completed()    == CompletedObservable{Any, AsapScheduler}(AsapScheduler())
        @test completed(Int) == CompletedObservable{Int, AsapScheduler}(AsapScheduler())
        @test completed(Int) == completed(Int)
        @test completed(Int) != completed(Float64)

        @test completed(Int; scheduler = DummyScheduler()) == CompletedObservable{Int, DummyScheduler}(DummyScheduler())
    end

    @testset begin
        source = completed(Int)
        io = IOBuffer()

        show(io, source)

        printed = String(take!(io))

        @test occursin("CompletedObservable", printed)
        @test occursin(string(eltype(source)), printed)
    end

    run_testset([
        (
            source = completed(),
            values = @ts(c)
        )
    ])

end

end


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

module NetworkWatcherClient

using Random
using Dates
using HTTP
using Swagger
import Swagger: field_name, property_type, hasproperty, validate_property, SwaggerApi, SwaggerModel
import Base: convert, propertynames

include("modelincludes.jl")

include("api_NetworkWatchersApi.jl")
include("api_PacketCapturesApi.jl")

# export models
export convert, ConnectivityDestination
export convert, ConnectivityHop
export convert, ConnectivityInformation
export convert, ConnectivityIssue
export convert, ConnectivityParameters
export convert, ConnectivitySource
export convert, EffectiveNetworkSecurityRule
export convert, FlowLogInformation
export convert, FlowLogProperties
export convert, FlowLogStatusParameters
export convert, IssueContext
export convert, NetworkInterfaceAssociation
export convert, NetworkWatcherListResult
export convert, NetworkWatcherPropertiesFormat
export convert, NextHopParameters
export convert, NextHopResult
export convert, PacketCapture
export convert, PacketCaptureFilter
export convert, PacketCaptureListResult
export convert, PacketCaptureParameters
export convert, PacketCaptureQueryStatusResult
export convert, PacketCaptureResult
export convert, PacketCaptureStorageLocation
export convert, QueryTroubleshootingParameters
export convert, Resource
export convert, RetentionPolicyParameters
export convert, SecurityGroupNetworkInterface
export convert, SecurityGroupViewParameters
export convert, SecurityGroupViewResult
export convert, SecurityRuleAssociations
export convert, SubResource
export convert, SubnetAssociation
export convert, Topology
export convert, TopologyAssociation
export convert, TopologyParameters
export convert, TopologyResource
export convert, TroubleshootingDetails
export convert, TroubleshootingParameters
export convert, TroubleshootingProperties
export convert, TroubleshootingRecommendedActions
export convert, TroubleshootingResult
export convert, VerificationIPFlowParameters
export convert, VerificationIPFlowResult
export convert, NetworkWatcher
export convert, PacketCaptureResultProperties
export convert, SecurityRule

# export operations
export convert, NetworkWatchersApi, PacketCapturesApi

export check_required, field_name, property_type, hasproperty, propertynames, validate_property, convert

end


text:
#!/usr/local/bin/julia

using ArgParse

function transcribe(DNAstring::String)
	RNAstring = replace(DNAstring, Pair('T','U'))
end

function main(args)
	# Argument parsing
	configs = ArgParseSettings()

	add_arg_group!(configs, "Options:")
	@add_arg_table! configs begin
		"--input", "-i"
			help	 = "Input filename"
			action	 = :store_arg
			arg_type = String
		"--output", "-o"
			help	 = "Output filename"
			action	 = :store_arg
			arg_type = String
		end
	# Store arguments to variables
	parsed_args = parse_args(args, configs)
	infile      = parsed_args["input"]
	outfile     = parsed_args["output"]

	# Read file and count nucleotides
	DNAstring = open(f->read(f, String), infile)
	@show RNAstring = transcribe(DNAstring)
	open(f->write(f, "$RNAstring"), outfile, "w+")

end

main(ARGS)


text:
module Sparse23
export PreLapl2,PreLapl3
function PreLapl2(size::Int)
    I(i::Int64,j::Int64)=(j-1)*size+i
    #I(i,j)=(j-1)*size+i
    nc= 5*(size-2)^2+ 16*(size-2)+ 12
    row=Array{Int64}(nc)
    col=Array{Int64}(nc)
    v=Array{Float64}(nc)
    h=1./(size-1)
    size2=size*size
    h2=h*h
    cd=-4.0/h2
    hd=1.0/h2
    count=1
    for j=1:size
        for i=1:size
            l=I(i,j)
            row[count]=l
            col[count]=l
            v[count]=cd
            count+=1
            for ii1 =0:2:2
                i1=ii1-1
                if i+i1>0 && i+i1<=size
                    row[count]=l
                    col[count]=I(i+i1,j)
                    v[count]=hd
                    count+=1
                end
                if j+i1>0 && j+i1<=size
                    row[count]=l
                    col[count]=I(i,j+i1)
                    v[count]=hd
                    count+=1
                end
            end

        end
    end

    M=sparse(row,col,v)
    return M,size2,count-1
end
function PreLapl3(size)
    #const size2=size*size
    I(i::Int64,j::Int64,k::Int64)=(k-1)*size*size+(j-1)*size+i
    nc= 7*(size-2)^3 + 36*(size-2)^2 + 60*(size-2)+ 8*4
    row=Array{Int64}(nc)
    col=Array{Int64}(nc)
    v=Array{Float64}(nc)
    h=1./(size-1)
    h2=h*h
    cd=-6.0/h2
    hd=1.0/h2
    count=1
    for k=1:size
        for j=1:size
            for i=1:size
                l=I(i,j,k)
                row[count]=l
                col[count]=l
                v[count]=cd
                count+=1
                for ii1 =0:2:2
                    i1=ii1-1
                    if i+i1>0 && i+i1<=size
                        row[count]=l
                        col[count]=I(i+i1,j,k)
                        v[count]=hd
                        count+=1
                    end
                    if j+i1>0 && j+i1<=size
                        row[count]=l
                        col[count]=I(i,j+i1,k)
                        v[count]=hd
                        count+=1
                    end
                    if k+i1>0 && k+i1<=size
                        row[count]=l
                        col[count]=I(i,j,k+i1)
                        v[count]=hd
                        count+=1
                    end
                end
            end
        end
    end

    M=sparse(row,col,v)
    return M,size^3,count-1
end
end

max_stars_repo_name: wolfv/BenchmarksPythonJuliaAndCo

max_issues_repo_name: wolfv/BenchmarksPythonJuliaAndCo

max_forks_repo_name: wolfv/BenchmarksPythonJuliaAndCo


text:
@testset "IsOnSide Tests" begin
    model = ALifeBenchmark.GebModel()
    @test ALifeBenchmark._is_on_side(ALifeBenchmark.ToTheLeft(), model, (1, -1), (0, 0), 0) == true
    @test ALifeBenchmark._is_on_side(ALifeBenchmark.ToTheLeft(), model, (1, -1), (0, 0), 90) == false
    @test ALifeBenchmark._is_on_side(ALifeBenchmark.ToTheLeft(), model, (1, -1), (0, 0), 180) == false
    @test ALifeBenchmark._is_on_side(ALifeBenchmark.ToTheLeft(), model, (1, -1), (0, 0), 270) == true

    @test ALifeBenchmark._is_on_side(ALifeBenchmark.ToTheLeft(), model, (1, -1), (1, 0), 0) == true
    @test ALifeBenchmark._is_on_side(ALifeBenchmark.ToTheLeft(), model, (1, -1), (1, 0), 90) == true
    @test ALifeBenchmark._is_on_side(ALifeBenchmark.ToTheLeft(), model, (1, -1), (1, 0), 180) == false
    @test ALifeBenchmark._is_on_side(ALifeBenchmark.ToTheLeft(), model, (1, -1), (1, 0), 270) == true

    @test ALifeBenchmark._is_on_side(ALifeBenchmark.ToTheRight(), model, (1, -1), (0, 0), 0) == false
    @test ALifeBenchmark._is_on_side(ALifeBenchmark.ToTheRight(), model, (1, -1), (0, 0), 90) == true
    @test ALifeBenchmark._is_on_side(ALifeBenchmark.ToTheRight(), model, (1, -1), (0, 0), 180) == true
    @test ALifeBenchmark._is_on_side(ALifeBenchmark.ToTheRight(), model, (1, -1), (0, 0), 270) == false

    @test ALifeBenchmark._is_on_side(ALifeBenchmark.ToTheRight(), model, (1, -1), (1, 0), 0) == false
    @test ALifeBenchmark._is_on_side(ALifeBenchmark.ToTheRight(), model, (1, -1), (1, 0), 90) == false
    @test ALifeBenchmark._is_on_side(ALifeBenchmark.ToTheRight(), model, (1, -1), (1, 0), 180) == true
    @test ALifeBenchmark._is_on_side(ALifeBenchmark.ToTheRight(), model, (1, -1), (1, 0), 270) == false
end

@testset "Neighbors Tests" begin
    # the model we build:

    """
    ##_____
    _____#_
    ___#___
    ___#_#_
    _#_____
    _______
    ___#___
    """

    @assert ALifeBenchmark.INFLUENCE_RADIUS == 2
    @assert ALifeBenchmark.MIN_ORGANISMS == 0

    model = ALifeBenchmark.GebModel(size=7)

    ALifeBenchmark.kill!(model, model.grid[1, 2])
    ALifeBenchmark.kill!(model, model.grid[1, 3])
    ALifeBenchmark.kill!(model, model.grid[1, 4])
    ALifeBenchmark.kill!(model, model.grid[1, 5])
    ALifeBenchmark.kill!(model, model.grid[1, 6])
    ALifeBenchmark.kill!(model, model.grid[1, 7])

    ALifeBenchmark.kill!(model, model.grid[2, 2])
    ALifeBenchmark.kill!(model, model.grid[2, 3])
    ALifeBenchmark.kill!(model, model.grid[2, 4])
    ALifeBenchmark.kill!(model, model.grid[2, 6])
    ALifeBenchmark.kill!(model, model.grid[2, 7])

    ALifeBenchmark.kill!(model, model.grid[3, 1])
    ALifeBenchmark.kill!(model, model.grid[3, 2])
    ALifeBenchmark.kill!(model, model.grid[3, 3])
    ALifeBenchmark.kill!(model, model.grid[3, 4])
    ALifeBenchmark.kill!(model, model.grid[3, 5])
    ALifeBenchmark.kill!(model, model.grid[3, 6])
    ALifeBenchmark.kill!(model, model.grid[3, 7])

    ALifeBenchmark.kill!(model, model.grid[4, 1])
    ALifeBenchmark.kill!(model, model.grid[4, 2])
    ALifeBenchmark.kill!(model, model.grid[4, 5])
    ALifeBenchmark.kill!(model, model.grid[4, 6])

    ALifeBenchmark.kill!(model, model.grid[5, 1])
    ALifeBenchmark.kill!(model, model.grid[5, 2])
    ALifeBenchmark.kill!(model, model.grid[5, 3])
    ALifeBenchmark.kill!(model, model.grid[5, 4])
    ALifeBenchmark.kill!(model, model.grid[5, 5])
    ALifeBenchmark.kill!(model, model.grid[5, 6])
    ALifeBenchmark.kill!(model, model.grid[5, 7])

    ALifeBenchmark.kill!(model, model.grid[6, 1])
    ALifeBenchmark.kill!(model, model.grid[6, 3])
    ALifeBenchmark.kill!(model, model.grid[6, 5])
    ALifeBenchmark.kill!(model, model.grid[6, 6])
    ALifeBenchmark.kill!(model, model.grid[6, 7])

    ALifeBenchmark.kill!(model, model.grid[7, 1])
    ALifeBenchmark.kill!(model, model.grid[7, 2])
    ALifeBenchmark.kill!(model, model.grid[7, 3])
    ALifeBenchmark.kill!(model, model.grid[7, 4])
    ALifeBenchmark.kill!(model, model.grid[7, 5])
    ALifeBenchmark.kill!(model, model.grid[7, 6])
    ALifeBenchmark.kill!(model, model.grid[7, 7])

    @test length(model.organisms) == 8

    model.grid[4, 4].direction = 90

    all = ALifeBenchmark._get_neighbors(ALifeBenchmark.BothSides(), model, model.grid[4, 4])

    @test length(all) == 4
    @test model.grid[2, 5] in all
    @test model.grid[4, 3] in all
    @test model.grid[6, 2] in all
    @test model.grid[6, 4] in all

    all = ALifeBenchmark._get_neighbors(ALifeBenchmark.BothSides(), model, model.grid[1, 1])

    @test length(all) == 2
    @test model.grid[2, 1] in all
    @test model.grid[6, 2] in all

    left = ALifeBenchmark._get_neighbors(ALifeBenchmark.ToTheLeft(), model, model.grid[4, 4])

    @test length(left) == 2
    @test model.grid[4, 3] in left
    @test model.grid[2, 5] in left

    right = ALifeBenchmark._get_neighbors(ALifeBenchmark.ToTheRight(), model, model.grid[4, 4])

    @test length(right) == 2
    @test model.grid[6, 2] in right
    @test model.grid[6, 4] in right

    model.grid[4, 4].direction = 40

    left = ALifeBenchmark._get_neighbors(ALifeBenchmark.ToTheLeft(), model, model.grid[4, 4])

    @test length(left) == 3
    @test model.grid[2, 5] in left
    @test model.grid[4, 3] in left
    @test model.grid[6, 2] in left

    right = ALifeBenchmark._get_neighbors(ALifeBenchmark.ToTheRight(), model, model.grid[4, 4])

    @test length(right) == 1
    @test model.grid[6, 4] in right

    model.grid[1, 1].direction = 220

    left = ALifeBenchmark._get_neighbors(ALifeBenchmark.ToTheLeft(), model, model.grid[1, 1])

    @test length(left) == 1
    @test model.grid[2, 1] in left

    right = ALifeBenchmark._get_neighbors(ALifeBenchmark.ToTheRight(), model, model.grid[1, 1])

    @test length(right) == 1
    @test model.grid[6, 2] in right
end

@testset "Inputs Test" begin
    # the model we build:

    """
    ##_____
    _____#_
    ___#___
    ___#_#_
    _#_____
    _______
    ___#___
    """

    model = ALifeBenchmark.GebModel(size=7)

    ALifeBenchmark.kill!(model, model.grid[1, 2])
    ALifeBenchmark.kill!(model, model.grid[1, 3])
    ALifeBenchmark.kill!(model, model.grid[1, 4])
    ALifeBenchmark.kill!(model, model.grid[1, 5])
    ALifeBenchmark.kill!(model, model.grid[1, 6])
    ALifeBenchmark.kill!(model, model.grid[1, 7])

    ALifeBenchmark.kill!(model, model.grid[2, 2])
    ALifeBenchmark.kill!(model, model.grid[2, 3])
    ALifeBenchmark.kill!(model, model.grid[2, 4])
    ALifeBenchmark.kill!(model, model.grid[2, 6])
    ALifeBenchmark.kill!(model, model.grid[2, 7])

    ALifeBenchmark.kill!(model, model.grid[3, 1])
    ALifeBenchmark.kill!(model, model.grid[3, 2])
    ALifeBenchmark.kill!(model, model.grid[3, 3])
    ALifeBenchmark.kill!(model, model.grid[3, 4])
    ALifeBenchmark.kill!(model, model.grid[3, 5])
    ALifeBenchmark.kill!(model, model.grid[3, 6])
    ALifeBenchmark.kill!(model, model.grid[3, 7])

    ALifeBenchmark.kill!(model, model.grid[4, 1])
    ALifeBenchmark.kill!(model, model.grid[4, 2])
    ALifeBenchmark.kill!(model, model.grid[4, 5])
    ALifeBenchmark.kill!(model, model.grid[4, 6])

    ALifeBenchmark.kill!(model, model.grid[5, 1])
    ALifeBenchmark.kill!(model, model.grid[5, 2])
    ALifeBenchmark.kill!(model, model.grid[5, 3])
    ALifeBenchmark.kill!(model, model.grid[5, 4])
    ALifeBenchmark.kill!(model, model.grid[5, 5])
    ALifeBenchmark.kill!(model, model.grid[5, 6])
    ALifeBenchmark.kill!(model, model.grid[5, 7])

    ALifeBenchmark.kill!(model, model.grid[6, 1])
    ALifeBenchmark.kill!(model, model.grid[6, 3])
    ALifeBenchmark.kill!(model, model.grid[6, 5])
    ALifeBenchmark.kill!(model, model.grid[6, 6])
    ALifeBenchmark.kill!(model, model.grid[6, 7])

    ALifeBenchmark.kill!(model, model.grid[7, 1])
    ALifeBenchmark.kill!(model, model.grid[7, 2])
    ALifeBenchmark.kill!(model, model.grid[7, 3])
    ALifeBenchmark.kill!(model, model.grid[7, 4])
    ALifeBenchmark.kill!(model, model.grid[7, 5])
    ALifeBenchmark.kill!(model, model.grid[7, 6])
    ALifeBenchmark.kill!(model, model.grid[7, 7])

    @test length(model.organisms) == 8

    model.grid[4, 4].direction = 90

    all = ALifeBenchmark._get_neighbors(ALifeBenchmark.BothSides(), model, model.grid[4, 4])

    @test length(all) == 4
    @test model.grid[2, 5] in all
    @test model.grid[4, 3] in all
    @test model.grid[6, 2] in all
    @test model.grid[6, 4] in all

    all = ALifeBenchmark._get_neighbors(ALifeBenchmark.BothSides(), model, model.grid[1, 1])

    @test length(all) == 2
    @test model.grid[2, 1] in all
    @test model.grid[6, 2] in all

    left = ALifeBenchmark._get_neighbors(ALifeBenchmark.ToTheLeft(), model, model.grid[4, 4])

    @test length(left) == 2
    @test model.grid[4, 3] in left
    @test model.grid[2, 5] in left

    right = ALifeBenchmark._get_neighbors(ALifeBenchmark.ToTheRight(), model, model.grid[4, 4])

    @test length(right) == 2
    @test model.grid[6, 2] in right
    @test model.grid[6, 4] in right

    model.grid[4, 4].direction = 40

    left = ALifeBenchmark._get_neighbors(ALifeBenchmark.ToTheLeft(), model, model.grid[4, 4])

    @test length(left) == 3
    @test model.grid[2, 5] in left
    @test model.grid[4, 3] in left
    @test model.grid[6, 2] in left

    right = ALifeBenchmark._get_neighbors(ALifeBenchmark.ToTheRight(), model, model.grid[4, 4])

    @test length(right) == 1
    @test model.grid[6, 4] in right

    model.grid[1, 1].direction = 220

    left = ALifeBenchmark._get_neighbors(ALifeBenchmark.ToTheLeft(), model, model.grid[1, 1])

    @test length(left) == 1
    @test model.grid[2, 1] in left

    right = ALifeBenchmark._get_neighbors(ALifeBenchmark.ToTheRight(), model, model.grid[1, 1])

    @test length(right) == 1
    @test model.grid[6, 2] in right
end

max_stars_repo_name: tochsner/ALifeBenchmark

max_issues_repo_name: tochsner/ALifeBenchmark

max_forks_repo_name: tochsner/ALifeBenchmark


text:
using Turing
using Test

@model testassume begin
  x ~ Bernoulli(1; :static = true)
  y ~ Bernoulli(x / 2; :param = true)
  1 ~ Normal(0, 1; :static = true)
  2 ~ Normal(0, 1; :param = true)
  y, x
end

s = SMC(1000)

res = sample(testassume, s)

@test reduce(&, res[:x].value) == 1 # check that x is always 1

@test mean(res[:y].value) ≈ 0.5 atol=0.1 # check that the mean of y is between 0.4 and 0.6


text:
using Base.Test
using ForwardNets

net = ForwardNet{Float32}()
push!(net, Variable(:A, Float32[0]))
push!(net, Variable(:B, Float32, 2))
push!(net, Variable, :C, Float32[1])
push!(net, Variable, :D, 3, :LAST)
@test lastindex(net) == 4

A = net[:A]
B = net[2]

@test name(A) == :A
@test name(B) == :B
@test output(A) == [0.0]
@test size(output(B)) == (2,)

push!(net, Affine, :affine, :A, 1)
push!(net, Affine, :A, 1)
affine = net[:affine]
@test name(affine) == :affine
@test size(output(affine)) == (1,)

A.tensor[1] = 1.0f0
@test affine.input[1] == 1.0f0
affine.W[1] = 2.0f0
affine.b[1] = 3.0f0
affine.output[1] = NaN
forward!(affine)
@test affine.output[1] == 5.0f0

push!(net, Concatenator, :concat, [:A, :C])
concat = net[:concat]
@test size(output(concat)) == (2,)
output(A)[1] = 1.0f0
output(net[:C])[1] = 2.0f0
forward!(concat)
@test concat.output == [1.0f0, 2.0f0]

push!(net, Reshaper, :reshaper, :concat, (1,2))
reshaper = net[:reshaper]
@test size(output(reshaper)) == (1,2)
forward!(reshaper)
@test output(reshaper) == [1.0f0, 2.0f0]'

push!(net, TanH, :tanh, :A)
push!(net, ReLU, :relu, :A)
push!(net, SoftPlus, :softplus, :A)
_tanh = net[:tanh]
_relu = net[:relu]
_softplus = net[:softplus]

output(A)[1] = -2.0f0
forward!(_tanh)
@test isapprox(output(_tanh)[1], tanh(-2.0))

output(A)[1] = -2.0f0
forward!(_relu)
@test isapprox(output(_relu)[1], relu(-2.0))

output(A)[1] = -2.0f0
forward!(_softplus)
@test isapprox(output(_softplus)[1], softplus(-2.0))

push!(net, LSTM, :lstm, :D, 3)
lstm = net[:lstm]
@test name(lstm) == :lstm
lstm.state[1] = NaN
zero!(lstm)
@test lstm.state[1] == 0.0f0
forward!(lstm)

push!(net, Variable, :output, :affine, :LAST)

pass = calc_forwardpass(net, [:A], [:output])
output(A)[1] = 2.0f0
forward!(pass)
@test output(net[:output])[1] == convert(Float32, 2*2 + 3)


text:
@doc raw"""
    LocalLevelExplanatory(y::Vector{Fl}, X::Matrix{Fl}) where Fl

A local level model with explanatory variables is defined by:
```math
\begin{gather*}
    \begin{aligned}
        y_{t} &=  \mu_{t} + X_{1,t} \cdot \beta_{1,t} + \dots + X_{n,t} \cdot \beta_{n,t} + \varepsilon_{t} \quad &\varepsilon_{t} \sim \mathcal{N}(0, \sigma^2_{\varepsilon})\\
        \mu_{t+1} &= \mu_{t} + \xi_{t} &\xi_{t} \sim \mathcal{N}(0, \sigma^2_{\xi})\\
        \beta_{1,t+1} &= \beta_{1,t} &\tau_{1, t} \sim \mathcal{N}(0, \sigma^2_{\tau_{1}})\\
        \dots &= \dots\\
        \beta_{n,t+1} &= \beta_{n,t} &\tau_{n, t} \sim \mathcal{N}(0, \sigma^2_{\tau_{n}})\\\\
    \end{aligned}
\end{gather*}
```

# Example
```jldoctest
julia> model = LocalLevelExplanatory(rand(100), rand(100, 1))
LocalLevelExplanatory
```
"""
mutable struct LocalLevelExplanatory <: StateSpaceModel
    hyperparameters::HyperParameters
    system::LinearUnivariateTimeVariant
    results::Results
    exogenous::Matrix

    function LocalLevelExplanatory(y::Vector{Fl}, X::Matrix{Fl}) where Fl

        @assert length(y) == size(X, 1)

        num_observations = size(X, 1)
        num_exogenous = size(X, 2)
        m = num_exogenous + 1

        # Define system matrices
        Z = [vcat(ones(Fl, 1), X[t, :]) for t in 1:num_observations]
        T = [Matrix{Fl}(I, m, m) for _ in 1:num_observations]
        R = [vcat(one(Fl), zeros(Fl, m-1, 1)) for _ in 1:num_observations]
        d = [zero(Fl) for _ in 1:num_observations]
        c = [zeros(m) for _ in 1:num_observations]
        H = [one(Fl) for _ in 1:num_observations]
        Q = [ones(Fl, 1, 1) for _ in 1:num_observations]

        system = LinearUnivariateTimeVariant{Fl}(y, Z, T, R, d, c, H, Q)

        # Define hyperparameters names
        names = [["sigma2_ε", "sigma2_η"];["β_$i" for i in 1:num_exogenous]]
        hyperparameters = HyperParameters{Fl}(names)

        return new(hyperparameters, system, Results{Fl}(), X)
    end
end

# Obligatory methods
function default_filter(model::LocalLevelExplanatory)
    Fl = typeof_model_elements(model)
    a1 = zeros(Fl, num_states(model))
    P1 = Fl(1e6) .* Matrix{Fl}(I, num_states(model), num_states(model))
    steadystate_tol = Fl(1e-5)
    return UnivariateKalmanFilter(a1, P1, num_states(model), steadystate_tol)
end

function get_beta_name(model::LocalLevelExplanatory, i::Int)
    return model.hyperparameters.names[i + 2]
end

function initial_hyperparameters!(model::LocalLevelExplanatory)
    Fl = typeof_model_elements(model)
    observed_variance = variance_of_valid_observations(model.system.y)
    initial_hyperparameters = Dict{String,Fl}(
        "sigma2_ε" => observed_variance, "sigma2_η" => observed_variance
    )
    # This is an heuristic for a good approximation
    initial_exogenous = model.exogenous \ model.system.y
    for i in axes(model.exogenous, 2)
        initial_hyperparameters[get_beta_name(model, i)] = initial_exogenous[i]
    end
    set_initial_hyperparameters!(model, initial_hyperparameters)
    return model
end

function constrain_hyperparameters!(model::LocalLevelExplanatory)
    for i in axes(model.exogenous, 2)
        constrain_identity!(model, get_beta_name(model, i))
    end
    constrain_variance!(model, "sigma2_ε")
    constrain_variance!(model, "sigma2_η")
    return model
end

function unconstrain_hyperparameters!(model::LocalLevelExplanatory)
    for i in axes(model.exogenous, 2)
        unconstrain_identity!(model, get_beta_name(model, i))
    end
    unconstrain_variance!(model, "sigma2_ε")
    unconstrain_variance!(model, "sigma2_η")
    return model
end

function fill_model_system!(model::LocalLevelExplanatory)
    H = get_constrained_value(model, "sigma2_ε")
    fill_H_in_time(model, H)
    for t in 1:length(model.system.Q)
        model.system.Q[t][1] = get_constrained_value(model, "sigma2_η")
    end
    return model
end

function fill_H_in_time(model::LocalLevelExplanatory, H::Fl) where Fl
    return fill_system_matrice_with_value_in_time(model.system.H, H)
end

function reinstantiate(::LocalLevelExplanatory, y::Vector{Fl}, X::Matrix{Fl}) where Fl
    return LocalLevelExplanatory(y, X)
end

has_exogenous(::LocalLevelExplanatory) = true


text:
module TestSimplicialSets
using Test

using SparseArrays, StaticArrays

using Catlab.CategoricalAlgebra.CSets
using CombinatorialSpaces.SimplicialSets

""" Check that the semi-simplicial identities hold in dimension `n`.
"""
function is_semi_simplicial(s::AbstractACSet, n::Int)
  all(∂(n-1, i, s, ∂(n, j, s)) == ∂(n-1, j-1, s, ∂(n, i, s))
      for i in 0:n for j in (i+1):n)
end

const Point2D = SVector{2,Float64}
const Point3D = SVector{3,Float64}

# 1D simplicial sets
####################

s = DeltaSet1D()
add_vertices!(s, 4)
add_sorted_edge!(s, 2, 1)
add_sorted_edges!(s, [2,4], [3,3])
@test src(s) == [1,2,3]
@test tgt(s) == [2,3,4]
@test ∂(1, 0, s) == [2,3,4]
@test ∂(1, 1, s) == [1,2,3]
@test ∂(0, s, E(1))::V == V(2)
@test ∂(1, s, E([1,3]))::V == V([1,3])
@test coface(0, s, V(4))::E == E([3])

# 1D oriented simplicial sets
#----------------------------

s = OrientedDeltaSet1D{Bool}()
add_vertices!(s, 4)
add_edges!(s, [1,2,3], [2,3,4], edge_orientation=[true,false,true])
@test ∂(1, s, 1) == [-1,1,0,0]
@test ∂(1, s, 2) == [0,1,-1,0]

# Boundary operator, dense vectors.
vvec = ∂(1, s, 1, Vector{Int})
@test !issparse(vvec)
@test vvec == [-1,1,0,0]
vvec = ∂(1, s, [1,-1,1])
@test !issparse(vvec)
@test vvec == [-1,0,0,1]
@test ∂(s, EChain([1,-1,1]))::VChain == VChain(vvec)

# Boundary operator, sparse vectors.
vvec = ∂(1, s, 1, SparseVector{Int})
@test issparse(vvec)
@test vvec == [-1,1,0,0]
vvec = ∂(1, s, sparsevec([1,-1,1]))
@test issparse(vvec)
@test vvec == [-1,0,0,1]
@test ∂(s, EChain(sparsevec([1,-1,1]))) == VChain(vvec)
B = ∂(1, s)
@test issparse(B)
@test B*[1,-1,1] == [-1,0,0,1]

# Exterior derivative.
@test d(s, VForm([1,1,1,4]))::EForm == EForm([0,0,3])
@test d(s, VForm([4,1,0,0])) == EForm([-3,1,0])
@test d(0, s) == B'

# Consistent orientation.
s = OrientedDeltaSet1D{Bool}()
add_vertices!(s, 10)
add_edges!(s, 1:4, 2:5)
add_edges!(s, 6:9, 7:10)
@test orient_component!(s, 1, true)
@test orientation(s, E(1:4)) == trues(4)
@test orient_component!(s, 8, true)
@test orientation(s, E(1:8)) == trues(8)

s[:edge_orientation] = rand(Bool, 8)
@test orient!(s)
@test orientation(s, E(1:8)) == trues(8)

# 1D embedded simplicial sets
#----------------------------

s = EmbeddedDeltaSet1D{Bool,Point2D}()
add_vertices!(s, 2, point=[Point2D(-1, 0), Point2D(+1, 0)])
add_edge!(s, 1, 2, edge_orientation=true)
@test volume(1, s, 1) ≈ 2
@test volume(s, E(1)) ≈ 2

# 2D simplicial sets
####################

s = DeltaSet2D()
add_vertices!(s, 3)
glue_triangle!(s, 1, 2, 3)
@test is_semi_simplicial(s, 2)
@test ntriangles(s) == 1
@test map(i -> ∂(2, i, s, 1), (0,1,2)) == (2,3,1)
@test triangle_vertices(s, 1) == [1,2,3]

s′ = DeltaSet2D()
add_vertices!(s′, 3)
glue_sorted_triangle!(s′, 2, 3, 1)
@test s′ == s

# Triangulated commutative square.
s = DeltaSet2D()
add_vertices!(s, 4)
glue_triangle!(s, 1, 2, 3)
glue_triangle!(s, 1, 4, 3)
@test ntriangles(s) == 2
@test triangles(s) == 1:2
@test ne(s) == 5
@test sort(map(Pair, src(s), tgt(s))) == [1=>2, 1=>3, 1=>4, 2=>3, 4=>3]

# 2D oriented simplicial sets
#----------------------------

# Triangle with matching edge orientations.
s = OrientedDeltaSet2D{Bool}()
add_vertices!(s, 3)
add_sorted_edges!(s, [1,2,3], [2,3,1], edge_orientation=[true,true,false])
glue_triangle!(s, 1, 2, 3)
@test orient_component!(s, 1, true)
@test orientation(s, Tri(1)) == true
@test ∂(2, s, 1) == [1,1,1]
@test d(1, s, [45,3,34]) == [82]

# Triangulated square with consistent orientation.
s = OrientedDeltaSet2D{Bool}()
add_vertices!(s, 4)
glue_triangle!(s, 1, 2, 3)
glue_triangle!(s, 1, 3, 4)
s[:edge_orientation] = true
@test orient!(s)
@test orientation(s, Tri(1:2)) == trues(2)
@test ∂(2, s, 1) == [1,1,-1,0,0]
@test ∂(s, TriChain([1,1]))::EChain == EChain([1,1,0,1,-1])
@test d(s, EForm([45,3,34,0,0]))::TriForm == TriForm([14, 34]) # == [45+3-34, 34]
@test d(s, EForm([45,3,34,17,5])) == TriForm([14, 46]) # == [45+3-34, 34+17-5]
@test d(1, s) == ∂(2, s)'

# 2D embedded simplicial sets
#----------------------------

# Standard 2-simplex in ℝ³.
s = EmbeddedDeltaSet2D{Bool,Point3D}()
add_vertices!(s, 3, point=[Point3D(1,0,0), Point3D(0,1,0), Point3D(0,0,1)])
glue_triangle!(s, 1, 2, 3, tri_orientation=true)
@test volume(s, Tri(1)) ≈ sqrt(3)/2

# Euclidean geometry
####################

std_simplex_volume(n::Int) = sqrt(n+1) / factorial(n)

p1, p2 = Point2D(1,0), Point2D(0,1)
@test volume([p1, p2]) ≈ std_simplex_volume(1)

p1, p2, p3 = Point3D(1,0,0), Point3D(0,1,0), Point3D(0,0,1)
@test volume([p1, p2, p3]) ≈ std_simplex_volume(2)

p1, p2, p3, p4 = SVector(1,0,0,0), SVector(0,1,0,0), SVector(0,0,1,0), SVector(0,0,0,1)
@test volume([p1, p2, p3, p4]) ≈ std_simplex_volume(3)

end


text:
@testset "Gather" begin
    w = randn(Float32, 10,10)
    wh = randn(Float32, 10,5,4,3)

    cuw = cu(w)
    cuwh = cu(wh)

    ind = rand(1:10, 3,5)

    @test (gather(cuw, todevice([3,5,7])) |> collect) == hcat(map(i->w[:, i], [3,5,7])...)
    @test (gather(cuw, todevice(ind)) |> collect) ==
        cat(map(j-> hcat(map(i->w[:, i], ind[:,j])...), 1:5)...; dims=3)
    @test (gather(cuwh, todevice([(5,3,3) (2,1,2); (5,4,1) (4,2,1)])) |> collect) == begin
        a = wh[:, 5, 3, 3]
        b = wh[:, 2, 1, 2]
        c = wh[:, 5, 4, 1]
        d = wh[:, 4, 2, 1]
        A = hcat(a,c)
        B = hcat(b,d)
        Z = cat(A, B; dims=3)
    end

    ca = cu(randn(5,  30))
    cb = todevice(OneHotArray(30, ones(Int, 20)))

    fa = zeros(Float32, size(ca))
    fa[:, 1] .= 20
    pca_grad = gradient(ca) do pca
        z = pca * cb
      sum(z)
    end
    @test collect(pca_grad[1]) == fa
end


text:
using FreeTypeAbstraction: hadvance, leftinkbound, inkwidth, get_extent, ascender, descender

one_attribute_per_char(attribute, string) = (attribute for char in string)

function one_attribute_per_char(font::NativeFont, string)
    return (find_font_for_char(char, font) for char in string)
end

function attribute_per_char(string, attribute)
    n_words = 0
    if attribute isa AbstractVector
        if length(attribute) == length(string)
            return attribute
        else
            n_words = length(split(string, r"\s+"))
            if length(attribute) == n_words
                i = 1
                return map(collect(string)) do char
                    f = attribute[i]
                    char == "\n" && (i += 1)
                    return f
                end
            end
        end
    else
        return one_attribute_per_char(attribute, string)
    end
    error("A vector of attributes with $(length(attribute)) elements was given but this fits neither the length of '$string' ($(length(string))) nor the number of words ($(n_words))")
end

"""
    layout_text(
        string::AbstractString, textsize::Union{AbstractVector, Number},
        font, align, rotation, justification, lineheight
    )

Compute a GlyphCollection for a `string` given textsize, font, align, rotation, model, justification, and lineheight.
"""
function layout_text(
        string::AbstractString, textsize::Union{AbstractVector, Number},
        font, align, rotation, justification, lineheight, color, strokecolor, strokewidth
    )

    ft_font = to_font(font)
    rscale = to_textsize(textsize)
    rot = to_rotation(rotation)

    fontperchar = attribute_per_char(string, ft_font)
    textsizeperchar = attribute_per_char(string, rscale)

    glyphcollection = glyph_collection(string, fontperchar, textsizeperchar, align[1],
        align[2], lineheight, justification, rot, color, strokecolor, strokewidth)

    return glyphcollection
end

"""
    glyph_collection(str::AbstractString, font_per_char, fontscale_px, halign, valign, lineheight_factor, justification, rotation, color)

Calculate the positions for each glyph in a string given a certain font, font size, alignment, etc.
This layout in text coordinates, relative to the anchor point [0,0] can then be translated and
rotated to wherever it is needed in the plot.
"""
function glyph_collection(str::AbstractString, font_per_char, fontscale_px, halign, valign,
        lineheight_factor, justification, rotation, color, strokecolor, strokewidth)

    isempty(str) && return GlyphCollection(
        [], [], Point3f[],FreeTypeAbstraction.FontExtent{Float32}[],
        Vec2f[], Float32[], RGBAf[], RGBAf[], Float32[])

    # collect information about every character in the string
    charinfos = broadcast((c for c in str), font_per_char, fontscale_px) do char, font, scale
        # TODO: scale as SVector not Number
        unscaled_extent = get_extent(font, char)
        lineheight = Float32(font.height / font.units_per_EM * lineheight_factor * scale)
        unscaled_hi_bb = height_insensitive_boundingbox(unscaled_extent, font)
        hi_bb = Rect2f(
            Makie.origin(unscaled_hi_bb) * scale,
            widths(unscaled_hi_bb) * scale)
        (char = char, font = font, scale = scale, hadvance = hadvance(unscaled_extent) * scale,
            hi_bb = hi_bb, lineheight = lineheight, extent = unscaled_extent)
    end

    # split the character info vector into lines after every \n
    lineinfos = let
        last_line_start = 1
        lineinfos = typeof(view(charinfos, last_line_start:last_line_start))[]
        for (i, ci) in enumerate(charinfos)
            if ci.char == '\n' || i == length(charinfos)
                push!(lineinfos, view(charinfos, last_line_start:i))
                last_line_start = i+1
            end
        end
        lineinfos
    end

    # calculate the x positions of each character in each line
    xs = map(lineinfos) do line
        cumsum([
            0f0;
            [l.hadvance for l in line[1:end-1]]
        ])
    end

    # calculate linewidths as the last origin plus hadvance for each line
    linewidths = map(lineinfos, xs) do line, xx
        nchars = length(line)
        # if the last and not the only character is \n, take the previous one
        # to compute the width
        i = (nchars > 1 && line[end].char == '\n') ? nchars - 1 : nchars
        xx[i] + line[i].hadvance
    end

    # the maximum width is needed for justification
    maxwidth = maximum(linewidths)

    # how much each line differs from the maximum width for justification correction
    width_differences = maxwidth .- linewidths

    # shift all x values by the justification amount needed for each line
    # if justification is automatic it depends on alignment
    float_justification = if justification === automatic
        if halign == :left || halign == 0
            0.0f0
        elseif halign == :right || halign == 1
            1.0f0
        elseif halign == :center || halign == 0.5
            0.5f0
        else
            0.5f0
        end
    elseif justification == :left
        0.0f0
    elseif justification == :right
        1.0f0
    elseif justification == :center
        0.5f0
    else
        Float32(justification)
    end

    xs_justified = map(xs, width_differences) do xsgroup, wd
        xsgroup .+ wd * float_justification
    end

    # each character carries a "lineheight" metric given its font and scale and a lineheight scaling factor
    # make each line's height the maximum of these values in the line
    lineheights = map(lineinfos) do line
        maximum(l -> l.lineheight, line)
    end

    # compute y values by adding up lineheights in negative y direction
    ys = cumsum([0.0; -lineheights[2:end]])

    # compute x values after left/center/right alignment
    halign = if halign isa Number
        Float32(halign)
    elseif halign == :left
        0.0f0
    elseif halign == :center
        0.5f0
    elseif halign == :right
        1.0f0
    else
        error("Invalid halign $halign. Valid values are <:Number, :left, :center and :right.")
    end
    xs_aligned = [xsgroup .- halign * maxwidth for xsgroup in xs_justified]

    # for y alignment, we need the largest ascender of the first line
    # and the largest descender of the last line
    first_line_ascender = maximum(lineinfos[1]) do l
        ascender(l.font) * l.scale
    end

    last_line_descender = minimum(lineinfos[end]) do l
        descender(l.font) * l.scale
    end

    # compute the height of all lines together
    overall_height = first_line_ascender - ys[end] - last_line_descender

    # compute y values after top/center/bottom/baseline alignment
    ys_aligned = if valign == :baseline
        ys .- first_line_ascender .+ overall_height .+ last_line_descender
    else
        va = if valign isa Number
            Float32(valign)
        elseif valign == :top
            1f0
        elseif valign == :bottom
            0f0
        elseif valign == :center
            0.5f0
        else
            error("Invalid valign $valign. Valid values are <:Number, :bottom, :baseline, :top, and :center.")
        end

        ys .- first_line_ascender .+ (1 - va) .* overall_height
    end

    # compute the origins for each character by rotating each character around the common origin
    # which is the alignment anchor and now [0, 0]
    # use 3D coordinates already because later they will be required in that format anyway
    charorigins = [Ref(rotation) .* Point3f.(xsgroup, y, 0) for (xsgroup, y) in zip(xs_aligned, ys_aligned)]

    # return a GlyphCollection, which contains each character's origin, height-insensitive
    # boundingbox and horizontal advance value
    # these values should be enough to draw characters correctly,
    # compute boundingboxes without relayouting and maybe implement
    # interactive features that need to know where characters begin and end
    per_char(attr) = collect(attribute_per_char(str, attr)) # attribute_per_char returns generators
    return GlyphCollection(
        [x.char for x in charinfos],
        [x.font for x in charinfos],
        reduce(vcat, charorigins),
        [x.extent for x in charinfos],
        [Vec2f(x.scale) for x in charinfos],
        per_char(rotation), # rotations is used as one rotation per string above. TODO, allow one rotation per char
        per_char(color),
        per_char(strokecolor),
        per_char(strokewidth)
    )
end

function preprojected_glyph_arrays(
        position::VecTypes, glyphcollection::Makie.GlyphCollection,
        space::Symbol, projview, resolution, offset::VecTypes, transfunc
    )
    offset = to_ndim(Point3f, offset, 0)
    pos3f0 = to_ndim(Point3f, position, 0)

    if space == :data
        positions = apply_transform(transfunc, Point3f[pos3f0 + offset + o for o in glyphcollection.origins])
    elseif space == :screen
        projected = Makie.project(projview, resolution, apply_transform(transfunc, pos3f0))
        positions = Point3f[to_ndim(Point3f, projected, 0) + offset + o for o in glyphcollection.origins]
    else
        error("Unknown space $space, only :data or :screen allowed")
    end
    text_quads(positions, glyphcollection.glyphs, glyphcollection.fonts, glyphcollection.scales)
end

function preprojected_glyph_arrays(
        position::VecTypes, glyphcollection::Makie.GlyphCollection,
        space::Symbol, projview, resolution, offsets::Vector, transfunc
    )

    offsets = to_ndim.(Point3f, offsets, 0)
    pos3f0 = to_ndim(Point3f, position, 0)

    if space == :data
        positions = apply_transform(transfunc, [pos3f0 + offset + o for (o, offset) in zip(glyphcollection.origins, offsets)])
    elseif space == :screen
        projected = Makie.project(projview, resolution, apply_transform(transfunc, pos3f0))
        positions = Point3f[to_ndim(Point3f, projected, 0) + offset + o for (o, offset) in zip(glyphcollection.origins, offsets)]
    else
        error("Unknown space $space, only :data or :screen allowed")
    end

    text_quads(positions, string, font, textsize)
end

function preprojected_glyph_arrays(
        positions::AbstractVector, glyphcollections::AbstractVector{<:GlyphCollection}, space::Symbol, projview, resolution, offset, transfunc
    )

    if offset isa VecTypes
        offset = [to_ndim(Point3f, offset, 0)]
    end

    if space == :data
        allpos = broadcast(positions, glyphcollections, offset) do pos, glyphcollection, offs
            p = to_ndim(Point3f, pos, 0)
            apply_transform(
                transfunc,
                Point3f[p .+ to_ndim(Point3f, offs, 0) .+ o for o in glyphcollection.origins]
            )
        end
    elseif space == :screen
        allpos = broadcast(positions, glyphcollections, offset) do pos, glyphcollection, offs
            projected = to_ndim(
                Point3f,
                Makie.project(
                    projview,
                    resolution,
                    apply_transform(transfunc, to_ndim(Point3f, pos, 0))
                ),
                0)

            return Point3f[projected .+ to_ndim(Point3f, offs, 0) + o
                        for o in glyphcollection.origins]
        end
    else
        error("Unknown space $space, only :data or :screen allowed")
    end

    text_quads(
        allpos,
        [x.glyphs for x in glyphcollections],
        [x.fonts for x in glyphcollections],
        [x.scales for x in glyphcollections])
end

function text_quads(positions, glyphs::AbstractVector, fonts::AbstractVector, textsizes::ScalarOrVector{<:Vec2})

    atlas = get_texture_atlas()
    offsets = Vec2f[]
    uv = Vec4f[]
    scales = Vec2f[]
    pad = GLYPH_PADDING[] / PIXELSIZE_IN_ATLAS[]
    broadcast_foreach(positions, glyphs, fonts, textsizes) do offs, c, font, pixelsize
    # for (c, font, pixelsize) in zipx(glyphs, fonts, textsizes)
        push!(uv, glyph_uv_width!(atlas, c, font))
        glyph_bb, extent = FreeTypeAbstraction.metrics_bb(c, font, pixelsize)

        push!(scales, widths(glyph_bb) .+ pixelsize * 2pad)
        push!(offsets, minimum(glyph_bb) .- pixelsize * pad)
    end
    return positions, offsets, uv, scales
end

function text_quads(positions, glyphs, fonts, textsizes::Vector{<:ScalarOrVector})

    atlas = get_texture_atlas()
    offsets = Vec2f[]
    uv = Vec4f[]
    scales = Vec2f[]
    pad = GLYPH_PADDING[] / PIXELSIZE_IN_ATLAS[]

    broadcast_foreach(positions, glyphs, fonts, textsizes) do positions, glyphs, fonts, textsizes
        broadcast_foreach(positions, glyphs, fonts, textsizes) do offs, c, font, pixelsize
            push!(uv, glyph_uv_width!(atlas, c, font))
            glyph_bb, extent = FreeTypeAbstraction.metrics_bb(c, font, pixelsize)
            push!(scales, widths(glyph_bb) .+ pixelsize * 2pad)
            push!(offsets, minimum(glyph_bb) .- pixelsize * pad)
        end
    end

    return reduce(vcat, positions, init = Point3f[]), offsets, uv, scales
end

# function to concatenate vectors with a value between every pair
function padded_vcat(arrs::AbstractVector{T}, fillvalue) where T <: AbstractVector{S} where S
    n = sum(length.(arrs))
    arr = fill(convert(S, fillvalue), n + length(arrs) - 1)

    counter = 1
    @inbounds for a in arrs
        for v in a
            arr[counter] = v
            counter += 1
        end
        counter += 1
    end
    arr
end

function alignment2num(x::Symbol)
    (x == :center) && return 0.5f0
    (x in (:left, :bottom)) && return 0.0f0
    (x in (:right, :top)) && return 1.0f0
    return 0.0f0 # 0 default, or better to error?
end


text:
# Julia wrapper for header: /usr/include/scip/pub_nodesel.h
# Automatically generated using Clang.jl wrap_c

function SCIPnodeselGetName(nodesel)
    ccall((:SCIPnodeselGetName, libscip), Cstring, (Ptr{SCIP_NODESEL},), nodesel)
end

function SCIPnodeselGetDesc(nodesel)
    ccall((:SCIPnodeselGetDesc, libscip), Cstring, (Ptr{SCIP_NODESEL},), nodesel)
end

function SCIPnodeselGetStdPriority(nodesel)
    ccall((:SCIPnodeselGetStdPriority, libscip), Cint, (Ptr{SCIP_NODESEL},), nodesel)
end

function SCIPnodeselGetMemsavePriority(nodesel)
    ccall((:SCIPnodeselGetMemsavePriority, libscip), Cint, (Ptr{SCIP_NODESEL},), nodesel)
end

function SCIPnodeselGetData(nodesel)
    ccall((:SCIPnodeselGetData, libscip), Ptr{SCIP_NODESELDATA}, (Ptr{SCIP_NODESEL},), nodesel)
end

function SCIPnodeselSetData(nodesel, nodeseldata)
    ccall((:SCIPnodeselSetData, libscip), Cvoid, (Ptr{SCIP_NODESEL}, Ptr{SCIP_NODESELDATA}), nodesel, nodeseldata)
end

function SCIPnodeselIsInitialized(nodesel)
    ccall((:SCIPnodeselIsInitialized, libscip), UInt32, (Ptr{SCIP_NODESEL},), nodesel)
end

function SCIPnodeselGetSetupTime(nodesel)
    ccall((:SCIPnodeselGetSetupTime, libscip), Cdouble, (Ptr{SCIP_NODESEL},), nodesel)
end

function SCIPnodeselGetTime(nodesel)
    ccall((:SCIPnodeselGetTime, libscip), Cdouble, (Ptr{SCIP_NODESEL},), nodesel)
end


text:
function levMar(z::Array{T,1}, alpha::Array{T,1}, c)
    n :: UInt64 = length(z);
    maxiter :: UInt64 = 1000000;
    mu :: Float64 = 200;
    v :: UInt64 = 2;

    H = Array{T}(8*n,8*n);

    resid_old = residual(z, alpha, c);
    H,d =  hessianApprox(z, alpha, c );

    for j = 1:maxiter

        alpha_old = alpha
        z_old = z

        if isinf( mu ) || isnan( mu )
            @printf "mu too large or too small: %e\n" mu
            break;
        end

        s = (im * imag(H) - diagm(diag(H))*mu)\d;

        z_cand = z + s[1:length(z)];
        alpha_cand = alpha + s[length(z)+1:2*length(z)];
        resid_cand = residual(z_cand, alpha_cand, c);

        # this should be positive
        #LL =  real(dot(s , ( mu * s + d )));

        gain = (resid_old - resid_cand)

        if gain[1] > 0
            v = 2;

            mu = mu * 1/2;
            z = z_cand;
            alpha = alpha_cand;
            resid_old = residual(z, alpha, c);

            H,d =  hessianApprox( z, alpha, c );

        else
            mu = mu * v; v = 2*v;
        end

        if mod(j,10000) == 0
            @printf "iter: %d\tresid: %1.15e\tmu: %e\tv: %e\n" j resid_old[1] mu v
        end
    end

    @printf "resid: %e\tmu: %e\tv: %e\n" resid_old[1] mu v
    return z, alpha;
end


text:
mutable struct Audio <: AbstractResource
    ptr::Ptr{SDL.Mix_Chunk}
    filename::String
    channels::Set{Int32}

    function Audio(ptr::Ptr{SDL.Mix_Chunk}, filename::String)
        self = new(ptr, filename, Set{Int32}())
        finalizer(destroy!, self)
        return self
    end
end

function Audio(resources::Resources, filename::String)
    if filename in keys(resources)
        @debug("resource already loaded", filename)
        return resources[filename]::Audio
    end

    self = Audio(load(query(filename)), filename)
    resources[filename] = self
    return self
end

function destroy!(a::Audio)
    SDL.Mix_FreeChunk(a.ptr)
    a.ptr = C_NULL
    return nothing
end

load(f::File{format"WAV"}) = SDL.Mix_LoadWAV(f.filename)
load(f::File{format"OGG"}) = SDL.Mix_LoadWAV(f.filename)
load(f::File{format"MP3"}) = SDL.Mix_LoadWAV(f.filename)

function play!(audio::Audio; repeat::Int=0, channel::Int=-1, volume::Int=100)
    channel = SDL.Mix_PlayChannel(convert(Int32, channel)::Int32, audio.ptr, convert(Int32, repeat)::Int32)
    if channel == -1
        @warn("could not play audio sample", audio.filename, audio.ptr)
        return audio
    end
    SDL.Mix_Volume(channel, convert(Int32, volume)::Int32)
    push!(audio.channels, channel)
    return audio
end

function stop!(audio::Audio)
    for channel in audio.channels
        # Only halt channels where the last loaded chunk was `audio`
        SDL.Mix_GetChunk(channel) == audio.ptr && SDL.Mix_HaltChannel(channel)
    end
    empty!(audio.channels)
    return audio
end

allocate_audiochannels!(n::Int) = SDL.Mix_AllocateChannels(convert(Int32, n))


text:
"""
    struct TemplateArgument <: Any
Hold a pointer to a `clang::TemplateArgument` object.
"""
struct TemplateArgument
    ptr::CXTemplateArgument
end

Base.unsafe_convert(::Type{CXTemplateArgument}, x::TemplateArgument) = x.ptr
Base.cconvert(::Type{CXTemplateArgument}, x::TemplateArgument) = x


text:
####
# Matrix memory layout traits
#
# if MemoryLayout(A) returns BandedColumnMajor, you must override
# pointer and leadingdimension
# in addition to the banded matrix interface
####

struct BandedColumns{ML} <: AbstractBandedLayout
    layout::ML
end
struct BandedRows{ML} <: AbstractBandedLayout
    layout::ML
end

const BandedColumnMajor = BandedColumns{<:AbstractColumnMajor}
const BandedRowMajor = BandedRows{<:AbstractColumnMajor}
BandedColumnMajor() = BandedColumns(DenseColumnMajor())
BandedRowMajor() = Bandeds(DenseRowMajor())

transposelayout(M::BandedColumns) = BandedRows(M.layout)
transposelayout(M::BandedRows) = BandedColumns(M.layout)
conjlayout(::Type{<:Complex}, M::AbstractBandedLayout) = ConjLayout(M)

# Here we override broadcasting for banded matrices.
# The design is to to exploit the broadcast machinery so that
# banded matrices that conform to the banded matrix interface but are not
# <: AbstractBandedMatrix can get access to fast copyto!, lmul!, rmul!, axpy!, etc.
# using broadcast variants (B .= A, B .= 2.0 .* A, etc.)

struct BandedStyle <: AbstractArrayStyle{2} end
BandedStyle(::Val{2}) = BandedStyle()
BroadcastStyle(::Type{<:AbstractBandedMatrix}) = BandedStyle()
BroadcastStyle(::DefaultArrayStyle{2}, ::BandedStyle) = DefaultArrayStyle{2}()
BroadcastStyle(::BandedStyle, ::DefaultArrayStyle{2}) = DefaultArrayStyle{2}()

size(bc::Broadcasted{BandedStyle}) = length.(axes(bc))

####
# Default to standard Array broadcast
#
# This is because, for example, exp.(B) is not banded
####

copyto!(dest::AbstractArray, bc::Broadcasted{BandedStyle}) =
   copyto!(dest, Broadcasted{DefaultArrayStyle{2}}(bc.f, bc.args, bc.axes))
##
# copyto!
##

copyto!(dest::AbstractMatrix, src::AbstractBandedMatrix) =  (dest .= src)

function checkbroadcastband(dest, src::AbstractMatrix)
    (size(src,1) ≤ bandwidth(src,1)+1 && size(src,2) ≤ bandwidth(src,2)+1) ||
        (size(dest,1) ≤ bandwidth(dest,1)+1 && size(dest,2) ≤ bandwidth(dest,2)+1) || throw(BandError(dest,size(dest,2)-1))
    size(dest) == size(src) || throw(DimensionMismatch())
end

function _banded_broadcast!(dest::AbstractMatrix, f, src::AbstractMatrix{T}, _1, _2) where T
    z = f(zero(T))
    iszero(z) || checkbroadcastband(dest, src)
    m,n = size(dest)

    d_l, d_u = bandwidths(dest)
    s_l, s_u = bandwidths(src)
    (d_l ≥ min(s_l,m-1) && d_u ≥ min(s_u,n-1)) || throw(BandError(dest))

    for j=1:n
        for k = max(1,j-d_u):min(j-s_u-1,m)
            inbands_setindex!(dest, z, k, j)
        end
        for k = max(1,j-s_u):min(j+s_l,m)
            inbands_setindex!(dest, f(inbands_getindex(src, k, j)), k, j)
        end
        for k = max(1,j+s_l+1):min(j+d_l,m)
            inbands_setindex!(dest, z, k, j)
        end
    end
    dest
end

function _banded_broadcast!(dest::AbstractMatrix, f, (src,x)::Tuple{AbstractMatrix{T},Number}, _1, _2) where T
    z = f(zero(T), x)
    iszero(z) || checkbroadcastband(dest, src)
    m,n = size(dest)

    d_l, d_u = bandwidths(dest)
    s_l, s_u = bandwidths(src)
    (d_l ≥ min(s_l,m-1) && d_u ≥ min(s_u,n-1)) || throw(BandError(dest))

    for j=1:n
        for k = max(1,j-d_u):min(j-s_u-1,m)
            inbands_setindex!(dest, z, k, j)
        end
        for k = max(1,j-s_u):min(j+s_l,m)
            inbands_setindex!(dest, f(inbands_getindex(src, k, j), x), k, j)
        end
        for k = max(1,j+s_l+1):min(j+d_l,m)
            inbands_setindex!(dest, z, k, j)
        end
    end
    dest
end

function _banded_broadcast!(dest::AbstractMatrix, f, (x,src)::Tuple{Number,AbstractMatrix{T}}, _1, _2) where T
    z = f(x, zero(T))
    iszero(z) || checkbroadcastband(dest, src)
    m,n = size(dest)

    d_l, d_u = bandwidths(dest)
    s_l, s_u = bandwidths(src)
    (d_l ≥ min(s_l,m-1) && d_u ≥ min(s_u,n-1)) || throw(BandError(dest))

    for j=1:n
        for k = max(1,j-d_u):min(j-s_u-1,m)
            inbands_setindex!(dest, z, k, j)
        end
        for k = max(1,j-s_u):min(j+s_l,m)
            inbands_setindex!(dest, f(x, inbands_getindex(src, k, j)), k, j)
        end
        for k = max(1,j+s_l+1):min(j+d_l,m)
            inbands_setindex!(dest, z, k, j)
        end
    end
    dest
end

function _banded_broadcast!(dest::AbstractMatrix, f, (A,B)::Tuple{AbstractMatrix{T},AbstractMatrix{V}}, _1, _2) where {T,V}
    z = f(zero(T), zero(V))
    iszero(z) || checkbroadcastband(dest, (A,B))
    m,n = size(dest)

    d_l, d_u = bandwidths(dest)
    A_l, A_u = bandwidths(A)
    B_l, B_u = bandwidths(B)
    l, u = max(A_l,B_l), max(A_u,B_u)
    (d_l ≥ min(l,m-1) && d_u ≥ min(u,n-1)) || throw(BandError(dest))

    for j=1:n
        for k = max(1,j-d_u):min(j-u-1,m)
            inbands_setindex!(dest, z, k, j)
        end
        for k = max(1,j-A_u):min(j-B_u-1,m)
            inbands_setindex!(dest, f(inbands_getindex(A, k, j), zero(V)), k, j)
        end
        for k = max(1,j-B_u):min(j-A_u-1,m)
            inbands_setindex!(dest, f(zero(T), inbands_getindex(B, k, j)), k, j)
        end
        for k = max(1,j-min(A_u,B_u)):min(j+min(A_l,B_l),m)
            inbands_setindex!(dest, f(inbands_getindex(A, k, j), inbands_getindex(B, k, j)), k, j)
        end
        for k = max(1,j+B_l+1):min(j+A_l,m)
            inbands_setindex!(dest, f(inbands_getindex(A, k, j), zero(V)), k, j)
        end
        for k = max(1,j+A_l+1):min(j+B_l,m)
            inbands_setindex!(dest, f(zero(T), inbands_getindex(B, k, j)), k, j)
        end
        for k = max(1,j+l+1):min(j+d_l,m)
            inbands_setindex!(dest, z, k, j)
        end
    end
    dest
end

function checkzerobands(dest, f, A::AbstractMatrix)
    m,n = size(A)
    d_l, d_u = bandwidths(dest)
    l, u = bandwidths(A)

    for j = 1:n
        for k = max(1,j-u) : min(j-d_u-1,n)
            iszero(f(A[k,j])) || throw(BandError(dest,b))
        end
        for k = max(1,j+d_l+1) : min(j+l,n)
            iszero(f(A[k,j])) || throw(BandError(dest,b))
        end
    end
end

function checkzerobands(dest, f, (A,B)::Tuple{AbstractMatrix,AbstractMatrix})
    m,n = size(A)
    d_l, d_u = bandwidths(dest)
    A_l, A_u = bandwidths(A)
    B_l, B_u = bandwidths(B)
    l, u = max(A_l,B_l), max(A_u,B_u)

    for j = 1:n
        for k = max(1,j-u) : min(j-d_u-1,n)
            iszero(f(A[k,j], B[k,j])) || throw(BandError(dest,b))
        end
        for k = max(1,j+d_l+1) : min(j+l,n)
            iszero(f(A[k,j], B[k,j])) || throw(BandError(dest,b))
        end
    end
end

function _banded_broadcast!(dest::AbstractMatrix, f, A::AbstractMatrix{T}, ::BandedColumns, ::BandedColumns) where T
    z = f(zero(T))
    iszero(z) || checkbroadcastband(dest, A)

    A_l,A_u = bandwidths(A)
    d_l,d_u = bandwidths(dest)
    m,n = size(A)
    data_d,data_A = bandeddata(dest), bandeddata(A)

    if (A_l,A_u) == (d_l,d_u)
        data_d .= f.(data_A)
    else
        checkzerobands(dest, f, A)
        fill!(view(data_d,1:(d_u-A_u),:), z)
        fill!(view(data_d,d_u+A_l+2:size(data_d,1),:), z)
        view(data_d,max(d_u-A_u+1,1):min(d_u+A_l+1,size(data_d,1)),:) .=
            f.(view(data_A,max(1,A_u-d_u+1):min(A_u+d_l+1,size(data_A,1)),:))
    end

    dest
end

function _banded_broadcast!(dest::AbstractMatrix, f, (A,B)::Tuple{AbstractMatrix,AbstractMatrix}, ::BandedColumns, ::Tuple{<:BandedColumns,<:BandedColumns})
    z = f(zero(eltype(A)), zero(eltype(B)))
    iszero(z) || checkbroadcastband(dest, A)
    iszero(z) || checkbroadcastband(dest, B)

    A_l,A_u = bandwidths(A)
    B_l,B_u = bandwidths(B)
    d_l,d_u = bandwidths(dest)
    m,n = size(A)
    data_d,data_A, data_B = bandeddata(dest), bandeddata(A), bandeddata(B)

    if (d_l,d_u) == (A_l,A_u) == (B_l,B_u)
        data_d .= f.(data_A,data_B)
    else
        max_l,max_u = max(A_l,B_l,d_l),max(A_u,B_u,d_u)
        min_l,min_u = min(A_l,B_l,d_l),min(A_u,B_u,d_u)
        checkzerobands(dest, f, (A,B))

        # fill extra bands in dest
        fill!(view(data_d,1:d_u-max(A_u,B_u),:), z)
        fill!(view(data_d,d_u+max(A_l,B_l)+2:size(data_d,1),:), z)

        # construct where B upper is zero
        data_d_u_A = view(data_d,d_u-max(A_u,B_u)+1:d_u-B_u, :)
        data_A_u_A = view(data_A, 1:A_u-B_u, :)
        data_d_u_A .= f.(data_A_u_A, zero(eltype(B)))

        # construct where A upper is zero
        data_d_u_B = view(data_d,max(1,d_u-max(A_u,B_u)+1):d_u-A_u, :)
        data_B_u_B = view(data_B, 1:B_u-A_u, :)
        data_d_u_B .= f.(zero(eltype(A)), data_B_u_B)

        # construct where A and B are non-zero
        data_d̃ = view(data_d, d_u-min_u+1 : d_u+min_l+1, :)
        data_Ã = view(data_A, A_u-min_u+1 : A_u+min_l+1, :)
        data_B̃ = view(data_B, B_u-min_u+1 : B_u+min_l+1, :)
        data_d̃ .= f.(data_Ã,data_B̃)

        # construct where A lower is zero
        data_d_l_B = view(data_d, d_u+min_l+2 : d_u+min(d_l,B_l)+1, :)
        data_B_l_B = view(data_B, B_u+min_l+2 : B_u+min(d_l,B_l)+1, :)
        data_d_l_B .= f.(zero(eltype(A)), data_B_l_B)

        # construct where B lower is zero
        data_d_l_A = view(data_d, d_u+min_l+2 : d_u+min(d_l,A_l)+1, :)
        data_A_l_A = view(data_A, A_u+min_l+2 : A_u+min(d_l,A_l)+1, :)
        data_d_l_A .= f.(data_A_l_A, zero(eltype(B)))
    end

    dest
end

function _banded_broadcast!(dest::AbstractMatrix, f, (src,x)::Tuple{AbstractMatrix{T},Number}, ::BandedColumns, ::BandedColumns) where T
    z = f(zero(T),x)
    iszero(z) || checkbroadcastband(dest, src)

    l,u = bandwidths(src)
    λ,μ = bandwidths(dest)
    m,n = size(src)
    data_d,data_s = bandeddata(dest), bandeddata(src)
    if (l,u) == (λ,μ)
        data_d .= f.(data_s, x)
    elseif μ > u && λ > l
        fill!(view(data_d,1:(μ-u),:), z)
        fill!(view(data_d,μ+l+2:μ+λ+1,:), z)
        view(data_d,μ-u+1:μ+l+1,:) .= f.(data_s,x)
    elseif μ > u
        fill!(view(data_d,1:(μ-u),:), z)
        for b = λ+1:l
            any(!iszero, view(data_s,u+b+1,1:min(m-b,n))) && throw(BandError(dest,b))
        end
        view(data_d,μ-u+1:μ+λ+1,:) .= f.(view(data_s,1:u+λ+1,:),x)
    elseif λ > l
        for b = μ+1:u
            any(!iszero, view(data_s,u-b+1,b+1:n)) && throw(BandError(dest,b))
        end
        fill!(view(data_d,μ+l+2:μ+λ+1,:), z)
        view(data_d,1:μ+l+1,:) .= f.(view(data_s,u-μ+1:u+l+1,:),x)
    else # μ < u && λ < l
        for b = μ+1:u
            any(!iszero, view(data_s,u-b+1,b+1:n)) && throw(BandError(dest,b))
        end
        for b = λ+1:l
            any(!iszero, view(data_s,u+b+1,1:min(m-b,n))) && throw(BandError(dest,b))
        end
        data_d .= f.(view(data_s,u-μ+1:u+λ+1,:),x)
    end

    dest
end

function _banded_broadcast!(dest::AbstractMatrix, f, (x, src)::Tuple{Number,AbstractMatrix{T}}, ::BandedColumns, ::BandedColumns) where T
    z = f(x, zero(T))
    iszero(z) || checkbroadcastband(dest, src)

    l,u = bandwidths(src)
    λ,μ = bandwidths(dest)
    m,n = size(src)
    data_d,data_s = bandeddata(dest), bandeddata(src)
    if (l,u) == (λ,μ)
        data_d .= f.(x, data_s)
    elseif μ > u && λ > l
        fill!(view(data_d,1:(μ-u),:), z)
        fill!(view(data_d,μ+l+2:μ+λ+1,:), z)
        view(data_d,μ-u+1:μ+l+1,:) .= f.(x, data_s)
    elseif μ > u
        fill!(view(data_d,1:(μ-u),:), z)
        for b = λ+1:l
            any(!iszero, view(data_s,u+b+1,1:min(m-b,n))) && throw(BandError(dest,b))
        end
        view(data_d,μ-u+1:μ+λ+1,:) .= f.(x, view(data_s,1:u+λ+1,:))
    elseif λ > l
        for b = μ+1:u
            any(!iszero, view(data_s,u-b+1,b+1:n)) && throw(BandError(dest,b))
        end
        fill!(view(data_d,μ+l+2:μ+λ+1,:), z)
        view(data_d,1:μ+l+1,:) .= f.(x, view(data_s,u-μ+1:u+l+1,:))
    else # μ < u && λ < l
        for b = μ+1:u
            any(!iszero, view(data_s,u-b+1,b+1:n)) && throw(BandError(dest,b))
        end
        for b = λ+1:l
            any(!iszero, view(data_s,u+b+1,1:min(m-b,n))) && throw(BandError(dest,b))
        end
        data_d .= f.(x, view(data_s,u-μ+1:u+λ+1,:))
    end

    dest
end

function copyto!(dest::AbstractArray, bc::Broadcasted{BandedStyle, <:Any, <:Any, <:Tuple{<:AbstractMatrix}})
    (A,) = bc.args
    _banded_broadcast!(dest, bc.f, A, MemoryLayout(dest), MemoryLayout(A))
end

function copyto!(dest::AbstractArray, bc::Broadcasted{BandedStyle, <:Any, <:Any, <:Tuple{<:AbstractMatrix,<:Number}})
    (A,x) = bc.args
    _banded_broadcast!(dest, bc.f, (A, x), MemoryLayout(dest), MemoryLayout(A))
end

function copyto!(dest::AbstractArray, bc::Broadcasted{BandedStyle, <:Any, <:Any, <:Tuple{<:Number,<:AbstractMatrix}})
    (x,A) = bc.args
    _banded_broadcast!(dest, bc.f, (x,A), MemoryLayout(dest), MemoryLayout(A))
end

function copyto!(dest::AbstractArray, bc::Broadcasted{BandedStyle, <:Any, <:Any, <:Tuple{<:AbstractMatrix,<:AbstractMatrix}})
    _banded_broadcast!(dest, bc.f, bc.args, MemoryLayout(dest), MemoryLayout.(bc.args))
end

_bandwidths(::Number) = (-720,-720)
_bandwidths(A) = bandwidths(A)

_band_eval_args() = ()
_band_eval_args(a::Number, b...) = (a, _band_eval_args(b...)...)
_band_eval_args(a::AbstractArray{T}, b...) where T = (zero(T), _band_eval_args(b...)...)
_band_eval_args(a::Broadcasted, b...) = (zero(mapreduce(eltype, promote_type, a.args)), _band_eval_args(b...)...)

function bandwidths(bc::Broadcasted{BandedStyle})
    if iszero(bc.f(_band_eval_args(bc.args...)...))
        max.(_bandwidths.(bc.args)...)
    else
        (a,b) = size(bc)
        (a-1,b-1)
    end
end

similar(bc::Broadcasted{BandedStyle}, ::Type{T}) where T = BandedMatrix{T}(undef, size(bc), _bandwidths(bc))

##
# lmul!/rmul!
##

function _banded_lmul!(α, A::AbstractMatrix, _)
    for j=1:size(A,2), k=colrange(A,j)
        inbands_setindex!(A, α*inbands_getindex(A,k,j), k,j)
    end
    A
end

function _banded_rmul!(A::AbstractMatrix, a, _)
    for j=1:size(Α,2), k=colrange(A,j)
        inbands_setindex!(A, inbands_getindex(A,k,j)*α, k,j)
    end
    A
end

function _banded_lmul!(α::Number, A::AbstractMatrix, ::BandedColumns)
    lmul!(α, bandeddata(A))
    A
end

function _banded_rmul!(A::AbstractMatrix, α::Number, ::BandedColumns)
    rmul!(bandeddata(A), α)
    A
end

banded_lmul!(α, A::AbstractMatrix) = _banded_lmul!(α, A, MemoryLayout(A))
banded_rmul!(A::AbstractMatrix, α) = _banded_rmul!(A, α, MemoryLayout(A))

lmul!(α::Number, A::AbstractBandedMatrix) = banded_lmul!(α, A)
rmul!(A::AbstractBandedMatrix, α::Number) = banded_rmul!(A, α)

##
# axpy!
##

# these are the routines of the banded interface of other AbstractMatrices
banded_axpy!(a::Number, X::AbstractMatrix, Y::AbstractMatrix) = _banded_axpy!(a, X, Y, MemoryLayout(X), MemoryLayout(Y))
_banded_axpy!(a::Number, X::AbstractMatrix, Y::AbstractMatrix, ::BandedColumns, ::BandedColumns) =
    banded_generic_axpy!(a, X, Y)
_banded_axpy!(a::Number, X::AbstractMatrix, Y::AbstractMatrix, notbandedX, notbandedY) =
    banded_dense_axpy!(a, X, Y)

# additions and subtractions
@propagate_inbounds function banded_generic_axpy!(a::Number, X::AbstractMatrix, Y::AbstractMatrix)
    n,m = size(X)
    if (n,m) ≠ size(Y)
        throw(BoundsError())
    end
    Xl, Xu = bandwidths(X)
    Yl, Yu = bandwidths(Y)

    @boundscheck if Xl > Yl
        # test that all entries are zero in extra bands
        for j=1:size(X,2),k=max(1,j+Yl+1):min(j+Xl,n)
            if inbands_getindex(X, k, j) ≠ 0
                throw(BandError(X, (k,j)))
            end
        end
    end
    @boundscheck if Xu > Yu
        # test that all entries are zero in extra bands
        for j=1:size(X,2),k=max(1,j-Xu):min(j-Yu-1,n)
            if inbands_getindex(X, k, j) ≠ 0
                throw(BandError(X, (k,j)))
            end
        end
    end

    l = min(Xl,Yl)
    u = min(Xu,Yu)

    @inbounds for j=1:m,k=max(1,j-u):min(n,j+l)
        inbands_setindex!(Y, a*inbands_getindex(X,k,j) + inbands_getindex(Y,k,j) ,k, j)
    end
    Y
end

function banded_dense_axpy!(a::Number, X::AbstractMatrix, Y::AbstractMatrix)
    if size(X) != size(Y)
        throw(DimensionMismatch("+"))
    end
    @inbounds for j=1:size(X,2),k=colrange(X,j)
        Y[k,j] += a*inbands_getindex(X,k,j)
    end
    Y
end

function copyto!(dest::AbstractArray{T}, bc::Broadcasted{BandedStyle, <:Any, typeof(+),
                                                        <:Tuple{<:Broadcasted{BandedStyle,<:Any,typeof(*),<:Tuple{<:Number,<:AbstractMatrix}},
                                                        <:AbstractMatrix}}) where T
    αA,B = bc.args
    α,A = αA.args
    dest ≡ B || (dest .= B)
    banded_axpy!(α, A, dest)
end

function similar(bc::Broadcasted{BandedStyle, <:Any, typeof(+),
                        <:Tuple{<:Broadcasted{BandedStyle,<:Any,typeof(*),<:Tuple{<:Number,<:AbstractMatrix}},
                        <:AbstractMatrix}}, ::Type{T}) where T
    αA,B = bc.args
    α,A = αA.args
    n,m = size(A)
    (n,m) == size(B) || throw(DimensionMismatch())
    Al,Au = bandwidths(A)
    Bl,Bu = bandwidths(B)
    similar(A, T, n, m, max(Al,Bl), max(Au,Bu))
end

axpy!(α, A::AbstractBandedMatrix, dest::AbstractMatrix) = banded_axpy!(α, A, dest)


text:
using FastTransforms, Libdl, LinearAlgebra, Test

include("specialfunctionstests.jl")

include("chebyshevtests.jl")

include("quadraturetests.jl")

if find_library(FastTransforms.libfasttransforms) ≡ FastTransforms.libfasttransforms
    include("libfasttransformstests.jl")
else
    error("FastTransforms is not properly installed. Please run Pkg.build(\"FastTransforms\") ",
          "and restart Julia.")
end

include("nuffttests.jl")

include("fftBigFloattests.jl")
include("paduatests.jl")

include("gaunttests.jl")

include("hermitetests.jl")

include("toeplitztests.jl")


text:
#
# This file is part of the Actors.jl Julia package,
# MIT license, part of https://github.com/JuliaActors
#

"Connection to a supervisor."
struct Super{L} <: Connection
    lk::L
end

"""
    Child{L,T}(lk::L, start, info::T)

Connection to a supervised actor or task.

# Fields
- `lk::L`: Link or Task,
- `start::Any`: callable object for restarting it,
- `init::Any`: callable object for initialization (this is used
    for remote actors),
- `name::Union{Nothing,Symbol}`: registered actor name, `nothing`
    if not registered,
- `info::T`: named tuple with information about restart
    strategies, timeout, pollint ...
"""
mutable struct Child{L,T} <: Connection
    lk::L
    start::Any
    init::Any
    name::Union{Nothing,Symbol}
    info::T
end

"Connection to a peer actor"
struct Peer{L} <: Connection
    lk::L
end

"Connection to a monitor"
struct Monitor{L} <: Connection
    lk::L
end

"Connection to a monitored actor or task"
struct Monitored{L} <: Connection
    lk::L
    action::Any
end

"""
    connect(lk::Link)

Create a connection between the calling actor and
the actor represented by `lk`.

Connected actors will send each other [`Exit`](@ref)
signals. A connected actor will exit with the signaled reason
unless it is `:normal`.

**Note:**
- An actor can be made `:sticky` with [`trapExit`](@ref) and then will not exit.
- If this is called from the `Main` scope, `lk` is
connected to the `Actors._ROOT` actor.
"""
function connect(lk::L) where L<:Link
    try
        act = task_local_storage("_ACT")
        if act.self != lk
            push!(act.conn, Peer(lk))
            unique!(act.conn)
            send(lk, Connect(Peer(act.self)))
        end
    catch exc
        if exc isa KeyError
            send(_ROOT, Connect(Peer(lk)))
            send(lk, Connect(Peer(_ROOT)))
        else
            rethrow()
        end
    end
end

function _monitortask(t::Task, m::Link; timeout::Real=5.0, pollint::Real=0.1)
    res = timedwait(()->t.state!=:runnable, timeout; pollint)
    res == :ok ?
        t.state == :done ?
            send(m, Down(t, :normal, nothing)) :
            send(m, Down(t, t.exception, t)) :
        send(m, Down(t, res, nothing))
end

"""
```
monitor(lk::Link, onsignal...)
monitor(t::Task, onsignal...; timeout::Real=5.0, pollint::Real=0.1)
```
Start monitoring the actor represented by `lk` or the
task `t` and execute `onsignal...` if it sends [`Down`](@ref)
or if it fails.
# Parameters
- `onsignal...`: action to take on `Down` signal:
    - if empty, it gives a warning;
    - if it is one argument `f`, it executes with
      `f(msg.reason)`;
    - if `f, args...`, it gets executed with
      `f(args..., msg.reason)`.
- `timeout::Real=5.0`: how many seconds should a task
    be monitored? After that a [`Down`](@ref) with
    reason `:timed_out` is sent.
- `pollint::Real=0.1`: polling interval in seconds for
    task monitoring.
"""
function monitor(lk::L, onsignal...) where L<:Link
    onsignal = isempty(onsignal) ? nothing :
        length(onsignal) == 1 ? first(onsignal) :
            Bhv(first(onsignal), onsignal[2:end]...)
    try
        act = task_local_storage("_ACT")
        send(lk, Connect(Monitor(act.self)))
        !isnothing(onsignal) && push!(act.conn, Monitored(lk, onsignal))
    catch exc
        if exc isa KeyError
            send(lk, Connect(Monitor(_ROOT)))
            !isnothing(onsignal) && send(_ROOT, Connect(Monitored(lk, onsignal)))
        else
            rethrow()
        end
    end
    return :ok
end
function monitor(t::Task, onsignal...; timeout::Real=5.0, pollint::Real=0.1)
    mt = Ref{Task}()
    onsignal = isempty(onsignal) ? nothing :
        length(onsignal) == 1 ? first(onsignal) :
            Bhv(first(onsignal), onsignal[2:end]...)
    try
        act = task_local_storage("_ACT")
        mt[] = @async _monitortask(t, act.self; timeout, pollint)
        !isnothing(onsignal) && push!(act.conn, Monitored(t, onsignal))
    catch exc
        if exc isa KeyError
            mt[] = @async _monitortask(t, _ROOT; timeout, pollint)
            !isnothing(onsignal) && send(_ROOT, Connect(Monitored(t, onsignal)))
        else
            rethrow()
        end
    end
    # return :ok
    return mt
end

"""
    disconnect(lk::Link)

Remove the connection between the calling actor and the
actor represented by `lk`.

**Note:** If this is called from the `Main` scope, `lk`
is disconnected from the `_ROOT` actor.
"""
function disconnect(lk::L) where L<:Link
    try
        act = task_local_storage("_ACT")
        filter!(c->c.lk!=lk, act.conn)
        send(lk, Connect(act.self, true))
    catch exc
        if exc isa KeyError
            send(_ROOT, Connect(lk, true))
            send(lk, Connect(_ROOT, true))
        else
            rethrow()
        end
    end
end

"""
    demonitor(lk::Link)

Remove the monitoring for the given link `lk`.
"""
demonitor = disconnect