text:
# TSP & Simulated Annealing

# Import Packages and Files

using Plots
using Distances

include("sumLen.jl")
include("plotPath.jl")

# Constants

n = 20                              # Number of Cities
temperature = Float64(100 * n)      # Starting Temperature
iter = 100                          # Iteration Times

# Randomizing Coordinates

city = rand(n, 2) * 100 .+ 1

# Interation Notes

l = 1                               # Interation Times
len = []                            # Sum of Distance

plot()
plotPath(city)                      # Plot the Path

# Iteration

while true

    global n, temperature, iter, city, cityNew, l, len

    for ii = 1: iter

        len1 = sumLen(city)         # Sum of Distance before Exchange

        cityNew = copy(city)        # Exchange Coordinates

        while true

            p =  Int64.(floor.(n * rand(2, 1) .+ 1))

            if p[1] != p[2]

                cityNew[p[1], :] = city[p[2], :]
                cityNew[p[2], :] = city[p[1], :]

                break

            end

        end

        len2 = sumLen(cityNew)      # Sum of Distance after Exchange

        deltaE = len2 - len1        # Energy difference

        if (deltaE < 0) || (exp(- deltaE / temperature) > rand())

            city = cityNew          # Accept

        end

    end

    len = [len; sumLen(city)]       # New Length
    l += 1
    temperature *= 0.99             # Lower Temperature

    if temperature < 0.001

        break                       # Stop

    end

end

# Output

plotPath(city)                      # Plot Result
println("min = $(len[end])")

max_stars_repo_name: mizu-bai/Try-Julia

max_issues_repo_name: mizu-bai/Data-Science-Demos

max_forks_repo_name: mizu-bai/Data-Science-Demos


text:
abstract type Contour end

struct CircularContour <: Contour
    c::Number    # center
    r::Real      # radius
    nodes::AbstractArray
    weights::AbstractArray
end

struct RectangularContour <: Contour
    bottom_left::Complex    # first corner
    top_right::Complex      # second corner
    nodes::AbstractArray
    weights::AbstractArray
    RectangularContour(bl,tr, n, w) = (real(bl) < real(tr) && imag(bl) < imag(tr)) ? new(bl,tr, n, w) : error("Invalid corners")
end

### TODO - need in_contour method for CustomContour
struct CustomContour <: Contour
    nodes::AbstractArray
    weights::AbstractArray
end

length(contour::Contour) = 1

function circular_contour_trapezoidal(c, r, N=16)
    θ = LinRange(π/N, 2*π-π/N, N)
    nodes = [r*exp(θ[i]*im)+c for i in 1:N]
    weights = [r*exp(θ[i]*im)/N for i in 1:N]
    CircularContour(c, r, nodes, weights)
end

function circular_contour_gauss(c, r, N=16)
    if ( N % 2 != 0) error("Number of nodes must be multiple of 2") end
    n = Integer(N//2)
    nodes, weights = zeros(ComplexF64, N), zeros(ComplexF64, N)
    gq_nodes, gq_w = gausslegendre(n)
    gq_nodes .= (pi/2.0) .* (gq_nodes .+ 1.0)
    nodes[1:n] = [r*exp(gq_nodes[i]*im)+c for i in 1:n]
    nodes[n+1:2n] = [r*exp((gq_nodes[i]+pi)*im)+c for i in 1:n]
    weights[1:n] = [r*exp(gq_nodes[i]*im)*gq_w[i]/4.0 for i in 1:n]
    weights[n+1:2n] = [r*exp((gq_nodes[i]+pi)*im)*gq_w[i]/4.0 for i in 1:n]
    CircularContour(c, r, nodes, weights)
end

# nodes in clockwise order: top, right, bottom, left,
function rectangular_contour_gauss(bottom_left, top_right, N=16)
    if ( N % 4 != 0) error("Number of nodes must be multiple of 4") end
    n = Integer(N//4)
    ### TODO - This is a bug if given real coordinates!
    nodes, weights = zeros(typeof(bottom_left), N), zeros(typeof(bottom_left), N)
    gq_nodes, gq_w = gausslegendre(n)
    top_len, side_len = ((real(top_right) - real(bottom_left))), ((imag(top_right) - imag(bottom_left)))
    nodes[1:n] .= (gq_nodes .+ 1) .* ( (real(top_right) - real(bottom_left))/2 ) .+ (imag(top_right)*im + real(bottom_left))
    nodes[n+1:2n] .= (gq_nodes .+ 1) .* ( im*(imag(top_right) - imag(bottom_left))/2 ) .+ (imag(bottom_left)*im + real(top_right))
    nodes[2n+1:3n] .= reverse(gq_nodes .+ 1) .* ( (real(top_right) - real(bottom_left))/2 ) .+ (imag(bottom_left)*im + real(bottom_left))
    nodes[3n+1:4n] .= reverse(gq_nodes .+ 1) .* ( im*(imag(top_right) - imag(bottom_left))/2 ) .+ (imag(bottom_left)*im + real(bottom_left))
    weights[1:n] .=  gq_w .* top_len
    weights[n+1:2n] .= -im .* gq_w .* side_len
    weights[2n+1:3n] .= -gq_w * top_len
    weights[3n+1:4n] .= im .* gq_w .* side_len
    RectangularContour(bottom_left, top_right, nodes, weights./(-4.0*pi*im))
end

# nodes in clockwise order: top, right, bottom, left,
function rectangular_contour_trapezoidal(bottom_left, top_right, N=16)
    bl, tr = bottom_left, top_right
    if ( N % 4 != 0) error("Number of nodes must be multiple of 4") end
    n = Integer(N//4)
    ### TODO - This is a bug if given real coordinates!
    nodes, weights = zeros(typeof(bl), N), zeros(typeof(bl), N)
    nodes[1:n] .= LinRange(real(bl), real(tr), n+1)[1:n] .+ imag(tr)*im
    nodes[n+1:2n] .= LinRange(imag(tr), imag(bl), n+1)[1:n] .* im .+ real(tr)
    nodes[2n+1:3n] .= LinRange(real(tr), real(bl), n+1)[1:n] .+ imag(bl)*im
    nodes[3n+1:4n] .= LinRange(imag(bl), imag(tr), n+1)[1:n] .* im .+ real(bl)
    top_len, side_len = ((real(tr) - real(bl))), ((imag(tr) - imag(bl)))
    weights[1] = im*side_len/(2n) + top_len/(2n)
    weights[2:n] .= top_len/n
    weights[n+1] = top_len/(2n) - im*side_len/(2n)
    weights[n+2:2n] .= -im*side_len/n
    weights[2n+1] = -im*side_len/(2n) - top_len/(2n)
    weights[2n+2:3n] .= -top_len/n
    weights[3n+1] = -top_len/(2n) + im*side_len/(2n)
    weights[3n+2:4n] .= im*side_len/n
    RectangularContour(bottom_left, top_right, nodes, weights./(-2.0*pi*im))
end

function in_contour(λ, c::Number, r::Real)
    abs.(λ .- c) .<= r
end

# takes single complex number or an array
function in_contour(λ, contour::CircularContour)
    abs.(λ .- contour.c) .<= contour.r
end

# takes single complex number or an array
function in_contour(λ, contour::RectangularContour)
    (real.(contour.bottom_left) .< real.(λ) .< real.(contour.top_right)) .& (imag.(contour.bottom_left) .< imag.(λ) .< imag.(contour.top_right))
end

function rational_func(z, contour)
    S = 0.0+0.0im
    for i=1:size(contour.nodes,1)
        S += contour.weights[i]  / (contour.nodes[i] - z)
    end
    S
end

ext: jl


text:
################################################################
#                 Face-to-face interactions
################################################################

"""
    VisibleFace

Index of an interfacing facet and its view factor

# Fields
- `id` : Index of the interfacing mesh
- `f`  : View factor from mesh i to mesh j
- `d̂`  : Normal vector from mesh i to mesh j
"""
struct VisibleFace
    id::Int64
    f::Float64
    d̂::SVector{3, Float64}
end

"""
    getViewFactor(mᵢ, mⱼ) -> fᵢⱼ, d̂ᵢⱼ

View factor from mesh i to mesh j, assuming Lambertian emission
"""
# function getViewFactor(mᵢ, mⱼ)
#     d⃗ᵢⱼ = mⱼ.center - mᵢ.center  # vector from mesh i to mesh j
#     d̂ᵢⱼ = normalize(d⃗ᵢⱼ)
#     dᵢⱼ = norm(d⃗ᵢⱼ)

#     cosθᵢ = mᵢ.normal ⋅ d̂ᵢⱼ
#     cosθⱼ = mⱼ.normal ⋅ (-d̂ᵢⱼ)

#     fᵢⱼ = getViewFactor(cosθᵢ, cosθⱼ, dᵢⱼ, mⱼ.area)
#     fᵢⱼ, d̂ᵢⱼ
# end

# getViewFactor(cosθᵢ, cosθⱼ, dᵢⱼ, aⱼ) = cosθᵢ * cosθⱼ / (π * dᵢⱼ^2) * aⱼ

"""
    Flux{T1, T2, T3}

Energy flux from/to a mesh

# Fields
- `sun`  : F_sun
- `scat` : F_scat
- `rad`  : F_rad
"""
# mutable struct Flux{T1, T2, T3}
#     sun::T1
#     scat::T2
#     rad::T3
# end

################################################################
#                  Triangular surface mesh
################################################################

"""
    SMesh{T1, T2, T3}

Triangular surface mesh of a polyhedral shape model.

Note that the mesh normal indicates outward the polyhedron.

# Fields
- `A` : Position of 1st vertex
- `B` : Position of 2nd vertex
- `C` : Position of 3rd vertex

- `center` : Position of mesh center
- `normal` : Normal vector to mesh
- `area`   : Area of mesh

- `viewfactors` : 1-D array of `ViewFactor`
- `flux`        :
- `Tz`          : Temperature profile in depth direction
- `df`          : Photon recoil force
"""
struct SMesh{T1, T2, T3, T4, T5, T6}
    A::T1
    B::T1
    C::T1

    center::T1
    normal::T1
    area::T2

    visiblefaces::T3
    flux::T4
    Tz::T5
    df::T6
end

function Base.show(io::IO, smesh::SMesh)
    println(io, "Surface mesh")
    println("------------")

    println("Vertices")
    println("    A : ", smesh.A)
    println("    B : ", smesh.B)
    println("    C : ", smesh.C)

    println("Center : ", smesh.center)
    println("Normal : ", smesh.normal)
    println("Area   : ", smesh.area)

    length(smesh.visiblefaces) != 0 && println("Visible faces")
    length(smesh.visiblefaces) != 0 && println(smesh.visiblefaces.id)
    length(smesh.visiblefaces) != 0 && println(smesh.visiblefaces.f)

    length(smesh.visiblefaces) == 0 && println("No visible faces")
end

SMesh(A, B, C) = SMesh([A, B, C])
SMesh(vs) = SMesh(vs[1], vs[2], vs[3], getcenter(vs), getnormal(vs), getarea(vs), StructArray(VisibleFace[]), Flux(0.,0.,0.), Float64[], zeros(3))

getmeshes(nodes, faces) = StructArray([SMesh(nodes[face]) for face in faces])

################################################################
#                      Mesh properites
################################################################

# getcenter(vs) = getcenter(vs[1], vs[2], vs[3])
# getcenter(v1, v2, v3) = (v1 + v2 + v3) / 3

# getnormal(vs) = getnormal(vs[1], vs[2], vs[3])
# getnormal(v1, v2, v3) = normalize((v2 - v1) × (v3 - v2))

# getarea(vs) = getarea(vs[1], vs[2], vs[3])
# getarea(v1, v2, v3) = norm((v2 - v1) × (v3 - v2)) * 0.5

# getcenters(meshes) = [m.center for m in meshes]
# getnormals(meshes) = [m.normal for m in meshes]
# getareas(meshes) = [m.area for m in meshes]

################################################################
#                           Orinet3D
################################################################

isAbove(mesh::SMesh, D) = isAbove(mesh.A, mesh.B, mesh.C, D)
isBelow(mesh::SMesh, D) = isBelow(mesh.A, mesh.B, mesh.C, D)

isAbove(obs::SMesh, tar::SMesh) = isAbove(obs.A, obs.B, obs.C, tar.center)
isBelow(obs::SMesh, tar::SMesh) = isBelow(obs.A, obs.B, obs.C, tar.center)

# function isAbove(A, B, C, D)
#     G = SA_F64[
#         A[1]-D[1] A[2]-D[2] A[3]-D[3]
#         B[1]-D[1] B[2]-D[2] B[3]-D[3]
#         C[1]-D[1] C[2]-D[2] C[3]-D[3]
#     ]

#     det(G) < 0 ? true : false
# end

# function isBelow(A, B, C, D)
#     G = SA_F64[
#         A[1]-D[1] A[2]-D[2] A[3]-D[3]
#         B[1]-D[1] B[2]-D[2] B[3]-D[3]
#         C[1]-D[1] C[2]-D[2] C[3]-D[3]
#     ]

#     det(G) > 0 ? true : false
# end

isFace(obs::SMesh, tar::SMesh) = isFace(obs.center, tar)
isFace(obs::AbstractVector, tar::SMesh) = (tar.center - obs) ⋅ tar.normal < 0 ? true : false

# ################################################################
# #                           Raycast
# ################################################################

# ## Viewd from an observor's mesh/position
# raycast(mesh, R, obs::SMesh) = raycast(mesh, R, obs.center)
# raycast(mesh, R, obs::AbstractVector) = raycast(mesh.A - obs, mesh.B - obs, mesh.C - obs, R)

# ## Viewd from the origin
# raycast(mesh, R) = raycast(mesh.A, mesh.B, mesh.C, R)

# function raycast(A, B, C, R)
#     E1 = B - A
#     E2 = C - A
#     T  = - A

#     P = R × E2
#     Q = T × E1

#     P_dot_E1 = P ⋅ E1

#     u = (P ⋅ T)  / P_dot_E1
#     v = (Q ⋅ R)  / P_dot_E1
#     t = (Q ⋅ E2) / P_dot_E1  # Distance to triangle (if t < 0, the ray hits from the back)

#     0 ≤ u ≤ 1 && 0 ≤ v ≤ 1 && 0 ≤ u + v ≤ 1 && t > 0 ? true : false
# end

"""
    findVisibleFaces!(obs::SMesh, meshes)

Find faces directly seen from the observer on the face

# Parameters
- `obs`    : Mesh where the observer stands
- `meshes` : Array of SMesh instances
"""
function findVisibleFaces!(obs::SMesh, meshes)
    ids = Int64[]
    for i in eachindex(meshes)
        tar = meshes[i]
        isAbove(obs, tar) && isFace(obs, tar) && push!(ids, i)
    end

    for i in copy(ids)
        tar_i = meshes[i]
        Rᵢ = tar_i.center - obs.center
        dᵢ = norm(Rᵢ)      # distance to i-th mesh
        for j in copy(ids)
            i == j && continue

            tar_j = meshes[j]
            Rⱼ = tar_j.center - obs.center
            dⱼ = norm(Rⱼ)  # distance to j-th mesh

            raycast(tar_j, Rᵢ, obs) && (dᵢ < dⱼ ? filter!(x->x≠j, ids) : filter!(x->x≠i, ids))
        end
    end

    for id in ids
        f, d̂ = getViewFactor(obs, meshes[id])
        push!(obs.visiblefaces, VisibleFace(id, f, d̂))
    end
end

"""
    findVisibleFaces!(meshes)

Find faces directly seen from the observer on each face

# Parameters
- `meshes` : Array of SMesh instances
"""
function findVisibleFaces!(meshes)
    for obs in meshes
        findVisibleFaces!(obs, meshes)
    end
end

"""
Return true if the observing mesh is illuminated by the direct sunlight, false if not
"""
function isIlluminated(obs::SMesh, r̂☉, meshes)
    obs.normal ⋅ r̂☉ < 0 && return false
    for id in obs.visiblefaces.id
        raycast(meshes[id], r̂☉, obs) && return false
    end
    return true
end

"""
    isAboveHorizon(mesh) -> Bool

The mesh is above its local horizon or not
"""
isAboveHorizon(smesh) = length(smesh.visiblefaces) == 0

# function getIlluminatedFaces(r̂☉, meshes::Vector{SMesh})
#     illuminated = Int64[]
#     for i in eachindex(meshes)
#         obs = meshes[i]
#         Ψ = obs.normal ⋅ r̂☉  # cosine of the Sun illumination angle
#         Ψ > 0 && isIlluminated(obs, r̂☉, meshes) && push!(illuminated, i)
#     end
#     illuminated
# end

# function getIlluminatedFaces_PSEUDOCONVEX(r̂☉, meshes::Vector{SMesh})
#     illuminated = Int64[]
#     for i in eachindex(meshes)
#         obs = meshes[i]
#         Ψ = obs.normal ⋅ r̂☉  # cosine of the Sun illumination angle
#         Ψ > 0 && push!(illuminated, i)
#     end
#     illuminated
# end

################################################################
#                    Solid angle of a mesh
################################################################

"""
    getSolidAngle(mesh::SMesh, observer) -> Ω

Solid angle of a triangular mesh,
equal to area of the corresponding spherical triangle
"""
function getSolidAngle(mesh::SMesh, obs::AbstractVector)

    ## Vectors from observer to mesh vertices
    A = mesh.A - obs
    B = mesh.B - obs
    C = mesh.C - obs

    AOB = getangle(A, B)
    BOC = getangle(B, C)
    COA = getangle(C, A)

    Ω = getSphericalExcess(AOB, BOC, COA)
end

"""
    getSphericalExcess(a, b, c) -> E

Area of a spherical triangle
c.f. L'Huilier's Theorem

# Arguments
- `a`, `b`, `c` : side length of a spherical traiangle
"""
# function getSphericalExcess(a, b, c)
#     s = (a + b + c) * 0.5  # semiperimeter

#     E = tan(s*0.5)
#     E *= tan((s - a)*0.5)
#     E *= tan((s - b)*0.5)
#     E *= tan((s - c)*0.5)
#     E = sqrt(E)
#     E = 4 * atan(E)
# end

# getangle(v1, v2) = acos(normalize(v1) ⋅ normalize(v2))

max_stars_repo_name: MasanoriKanamaru/Astroshaper

max_issues_repo_name: MasanoriKanamaru/Astroshaper

max_forks_repo_name: MasanoriKanamaru/Astroshaper


text:
__precompile__()

module Libz

export ZlibInflateInputStream, ZlibDeflateInputStream,
       ZlibInflateOutputStream, ZlibDeflateOutputStream,
       adler32, crc32

using BufferedStreams, Compat

include("lowlevel.jl")
include("state.jl")
include("source.jl")
include("sink.jl")
include("checksums.jl")

function deflate(data::Vector{UInt8})
    return read(ZlibDeflateInputStream(data))
end

const compress = deflate

function inflate(data::Vector{UInt8})
    return read(ZlibInflateInputStream(data))
end

const decompress = inflate

end # module Libz


text:
function sortedintersectmapping(A::Array, B::Array)
    #Compute intersect of two sorted and unique array.
    #return the mapping from each array to the intersect
    temp_index_A = 1
    temp_index_B = 1
    Amap = Array{Int64,1}()
    Bmap = Array{Int64,1}()

    while (temp_index_A <= length(A)) & (temp_index_B <= length(B))
        if A[temp_index_A] == B[temp_index_B]
            push!(Amap, temp_index_A)
            push!(Bmap, temp_index_B)
            temp_index_A += 1
            temp_index_B += 1
        elseif A[temp_index_A] < B[temp_index_B]
            temp_index_A += 1
        else
            temp_index_B += 1
        end
    end

    return Amap,Bmap
end

########################################################
# D4M: Dynamic Distributed Dimensional Data Model
# Architect: Dr. Jeremy Kepner (kepner@ll.mit.edu)
# Software Engineer: Alexander Chen (alexc89@mit.edu)
########################################################


text:
f = open("input05.txt", "r")
    l = readlines(f)
close(f)

coordinates = Array{Int}(undef, length(l), 4)

for (i, line) in enumerate(l)
    (s1, s2) = split(line, "->")
    x1 = parse(Int, split(s1, ",")[1])
    y1 = parse(Int, split(s1, ",")[2])
    x2 = parse(Int, split(s2, ",")[1])
    y2 = parse(Int, split(s2, ",")[2])
    coordinates[i,:] = [x1, y1, x2, y2]
end

max_coord = maximum(coordinates)

vent_map = zeros((max_coord+1, max_coord+1))

coordinates += ones(size(coordinates))
coordinates = trunc.(Int, coordinates)
for row in eachrow(coordinates)
    if row[1] == row[3]
        if row[2] > row[4]
            plus = ones(size(vent_map[row[4]:row[2],row[1]:row[3]]))
            vent_map[row[4]:row[2],row[1]:row[3]] += plus
        elseif row[4] > row[2]
            plus = ones(size(vent_map[row[2]:row[4],row[1]:row[3]]))
            vent_map[row[2]:row[4],row[1]:row[3]] += plus
        end
    elseif row[2] == row[4]
        if row[3] > row[1]
            plus = ones(size(vent_map[row[2]:row[4],row[1]:row[3]]))
            vent_map[row[2]:row[4],row[1]:row[3]] += plus
        elseif row[1] > row[3]
            plus = ones(size(vent_map[row[2]:row[4],row[3]:row[1]]))
            vent_map[row[2]:row[4],row[3]:row[1]] += plus
        end
    end
end
counter = 0
for i in vent_map
    if i >= 2
        global counter += 1
    end
end
println("Result 1: $counter")

for row in eachrow(coordinates)
    if row[1] != row[3] && row[2] != row[4]
        if row[1] > row[3]
            x = collect(row[1]:-1:row[3])
        else
            x = collect(row[1]:row[3])
        end
        if row[2] > row[4]
            y = collect(row[2]:-1:row[4])
        else
            y = collect(row[2]:row[4])
        end
        for (i, j) in zip(y, x)
            vent_map[i, j] += 1
        end
    end
end
counter = 0
for i in vent_map
    if i >= 2
        global counter += 1
    end
end
println("Result 2: $counter")

max_stars_repo_name: jung-benjamin/advent-of-code

max_issues_repo_name: jung-benjamin/advent-of-code

max_forks_repo_name: jung-benjamin/advent-of-code


text:
using MPI, Test
MPI.Init()

@test MPI.ERRORS_ARE_FATAL != MPI.ERRORS_RETURN
@test MPI.get_errorhandler(MPI.COMM_SELF) == MPI.ERRORS_RETURN
@test_throws MPI.MPIError MPI.Send(rand(10), 2, 0, MPI.COMM_SELF)

MPI.set_errorhandler!(MPI.COMM_SELF, MPI.ERRORS_ARE_FATAL)
@test MPI.get_errorhandler(MPI.COMM_SELF) == MPI.ERRORS_ARE_FATAL


text:
sz_values = [1]
n_values  = [1, 9]
k_values  = [1, 9]
m_values  = [1, 9]

testset_name_suffix = "(main)"

include("_matmul.jl")


text:
# Use baremodule to shave off a few KB from the serialized `.ji` file
baremodule Enzyme_jll
using Base
using Base: UUID
import JLLWrappers

JLLWrappers.@generate_main_file_header("Enzyme")
JLLWrappers.@generate_main_file("Enzyme", UUID("7cc45869-7501-5eee-bdea-0790c847d4ef"))
end  # module Enzyme_jll


text:
#! /usr/bin/env julia

println("Start test 'tests/label.jl'")

include("../src/DCellC.jl")
using DCellC

label1 = Label()
label2 = Label([(1,2), (500, 33)])
label3 = Label(rand(1:500, 2, 20))

println("Test label.jl: Construction of labels works")

push!(label1, (1, 88))
deleteat!(label3, 18)
println("Test label.jl: Pushing and deleting in labels works")

for (x,y) in label2
  a = x*y
end
println("Test label.jl: Iterating over labels works")

lname = tempname()

lblsave(lname, label3)
label4 = lblload(lname)

@assert label4.data == label3.data
println("Test label.jl: Writing and loading labels works")

lblc = crop(label2, 450, 25, 75, 10)
@assert lblc.data[1] == (51, 9)
println("Test label.jl: Cropping labels works")

println("Test label.jl completed")

max_stars_repo_name: tscode/DCellC

max_issues_repo_name: tscode/DCellC


text:
@testset "Test Line-Search Stopping" begin
  lsatx = OneDAtX(0.0)

  pb = ADNLPModel(x -> 0.0, ones(1)) #NLPModels of size 1

  @test pb.meta.nvar == 1
  @test unconstrained(pb)

  # Create the stopping object to test
  stop = NLPStopping(pb, lsatx, max_iter = 10, optimality_check = armijo)
  stop_without_check = NLPStopping(pb, lsatx, max_iter = 10)
  @test stop_without_check.meta.optimality_check == KKT
  @test stop.meta.optimality_check == armijo

  meta = StoppingMeta(max_iter = 10, optimality_check = (x, y) -> armijo(x, y))
  stop_meta = NLPStopping(pb, meta, lsatx)
  stop_meta_src = NLPStopping(pb, meta, StopRemoteControl(), lsatx)

  @test stop_meta_src.stop_remote.cheap_check == stop.stop_remote.cheap_check
  @test stop_meta.stop_remote.cheap_check == stop.stop_remote.cheap_check

  # We tests different functions of stopping
  #This is no longer true as NaN is the _init_field for the quantities
  #OK = update_and_start!(stop, x = 1.0, g₀ = NaN, f₀ = NaN, fx = NaN)
  #@test OK == true
  #@test status(stop) == :DomainError
  #@test stop.current_state.x == 1.0

  reinit!(stop)
  @test stop.meta.domainerror == false
  update!(lsatx, g₀ = 0.0, f₀ = 0.0, fx = 10.0)
  @test (stop.current_state.g₀ == lsatx.g₀) && (lsatx.g₀ == 0.0)
  @test (stop.current_state.f₀ == lsatx.f₀) && (lsatx.f₀ == 0.0)
  @test (stop.current_state.fx == lsatx.fx) && (lsatx.fx == 10.0)
  @test start!(stop) == false
  @test status(stop) == :Unknown
  #
  @test update_and_stop!(stop, fx = -10.0) == true
  @test status(stop) == :Optimal

  reinit!(stop)
  @test stop.meta.optimal == false
  update!(stop.current_state, fx = 10.0)
  # Check if _tired_check works
  @test isnan(stop.meta.start_time) #default time value is NaN
  start!(stop) #start initializes the start_time
  @test !isnan(stop.meta.start_time)
  @test !stop!(stop) #shall we stop?Not yet
  #If we check stop! without a given start_time:
  stop.meta.start_time = NaN
  @test !(stop!(stop))
  @test stop.meta.tired == false
  @test status(stop) == :Unknown

  # we can check _tired_check for max evals with NLPStopping

  # Check if _unbounded_check! works
  update!(stop.current_state, x = 1e100)
  @test stop!(stop)

  reinit!(stop, rstate = true, x = 1.0)
  @test stop.current_state.x == 1.0
  @test isnan(stop.current_state.fx)

  ## _optimality_check! and _null_test are tested with NLP
  try
    armijo(stop.pb, stop.current_state)
    @test false #nothing entries in the stop
  catch
    @test true
  end
  try
    wolfe(stop.pb, stop.current_state)
    @test false #nothing entries in the stop
  catch
    @test true
  end
  try
    armijo_wolfe(stop.pb, stop.current_state)
    @test false #nothing entries in the stop
  catch
    @test true
  end
  update!(stop.current_state, f₀ = 1.0, fx = 0.0, g₀ = 1.0, gx = 0.0)
  @test wolfe(stop.pb, stop.current_state) == 0.0
  @test armijo_wolfe(stop.pb, stop.current_state) == 0.0

  #@test shamanskii_stop(stop.pb, stop.current_state) == 0.0 #specific LineModel
  @test goldstein(stop.pb, stop.current_state) >= 0.0

  stop.meta.optimality_check = (x, y) -> 0.0

  #stop.pb = ADNLPModel(x -> 0.0, [1.0]) #Can't do that
  #stop.meta.max_f = -1
  #reinit!(stop.current_state, 0.0)
  #@test stop.current_state.fx == nothing
  #@test stop!(stop) == true
  #@test stop.current_state.fx == nothing
  #@test stop.meta.resources == true

  #We now check the tol_check_neg function
  #stop.meta.optimality_check = (x,y) -> y.fx
  #stop.current_state.fx = 0.0
  #@test stop.current_state.fx == 0.0
  #stop.meta.tol_check = (a,b,c) -> 1.0
  #@test Stopping._null_test(stop, Stopping._optimality_check!(stop))
  #stop.meta.tol_check_neg = (a,b,c) -> 0.5
  #@test !(Stopping._null_test(stop, Stopping._optimality_check!(stop)))

end


text:
# Copyright (c) 2021, Eric Sabo
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.

include("linearcode.jl")

abstract type AbstractGolayCode <: AbstractLinearCode end

max_stars_repo_name: esabo/CodingTheory

max_issues_repo_name: esabo/CodingTheory

max_forks_repo_name: esabo/CodingTheory


text:
# From Makie examples

@recipe(CorrPlot) do scene
    Theme(
        link = :x,  # need custom linking for y
        legend = false,
        margin = 1,
        fillcolor = theme(scene, :color),
        linecolor = theme(scene, :color),
        # indices = reshape(1:n^2, n, n)',
        title = "",
    )
end

AbstractPlotting.convert_arguments(::Type{<: CorrPlot}, x) = (x,)

function AbstractPlotting.plot!(scene::Scene, ::Type{CorrPlot}, attributes::Attributes, mat)
    n = size(mat, 2)
    C = cor(mat)
    plotgrid = broadcast(1:n, (1:n)') do i, j
        vi = view(mat, :, i)
        vj = view(mat, :, j)
        s = Scene(scene, Reactive.value(pixelarea(scene)))
        if i == j # histograms are on the diagonal
            histogram!(s, vi)
        elseif i > j
            scatter!(s, vj, vi)
        else
            scatter!(s, vj, vi)
        end
        s
    end
    grid!(scene, plotgrid)
    scene
end


text:
module Zoo

# Stdlib requirements
using Statistics, Random

using ..Utils: Actualizer, ForwardLoss

# Use Flux for the actual modeling
using Flux
import nGraph

# Like Flux's Chain, but not type stable.
struct UnstableChain
    x::Vector{Any}
end
Flux.@functor UnstableChain

function (U::UnstableChain)(x)
    for f in U.x
        x = f(x)
    end
    return x
end

include("densenet.jl")
include("inception.jl")
include("resnet.jl")
include("transformer.jl")
include("vgg.jl")
include("dlrm.jl")

end

max_stars_repo_name: darchr/AutoTM

max_issues_repo_name: darchr/AutoTM

max_forks_repo_name: darchr/AutoTM


text:
import Crayons
import Highlights

function Highlights.Format.render(io::IO, ::MIME"text/ansi", tokens::Highlights.Format.TokenIterator)
    for (str, id, style) in tokens
        fg = style.fg.active ? map(Int, (style.fg.r, style.fg.g, style.fg.b)) : :nothing
        bg = style.bg.active ? map(Int, (style.bg.r, style.bg.g, style.bg.b)) : :nothing
        crayon = Crayons.Crayon(
            foreground = fg,
            background = bg,
            bold       = style.bold,
            italics    = style.italic,
            underline  = style.underline,
        )
        print(io, crayon, str, inv(crayon))
    end
end

writecodehtml(filename::AbstractString, source; lexer=Highlights.Lexers.JuliaLexer, theme=Highlights.Themes.TangoTheme) = begin
    open(filename, "w") do io
        print(io, """
        <style>
            @import url(https://cdn.jsdelivr.net/gh/tonsky/FiraCode@4/distr/fira_code.css);
            pre.hljl { font-family: 'Fira Code'; font-size: x-small }
        </style>
        """)
        Highlights.stylesheet(io, MIME("text/html"), theme)
        Highlights.highlight(io, MIME("text/html"), source, lexer, theme)
   end
end

abstract type TokenColor end
struct SystemColor <: TokenColor end
struct VarColor <: TokenColor end
struct StateColor <: TokenColor end
struct NonStateColor <: TokenColor end
struct MiscColor <: TokenColor end
struct NoColor <: TokenColor end

tokencolor(c::TokenColor; color::Bool) = tokencolor(color ? c : NoColor())
tokencolor(::SystemColor) = Crayons.Box.LIGHT_MAGENTA_FG
tokencolor(::VarColor) = Crayons.Box.LIGHT_BLUE_FG
tokencolor(::StateColor) = Crayons.Box.CYAN_FG
tokencolor(::NonStateColor) = Crayons.Box.LIGHT_GREEN_FG
tokencolor(::MiscColor) = Crayons.Box.DARK_GRAY_FG
tokencolor(::NoColor) = Crayons.Box.DEFAULT_FG

# compatibility for dive() where escapes are mandatory
system_color(s) = tokencolor(SystemColor())(s)
variable_color(s) = tokencolor(VarColor())(s)
state_color(s) = tokencolor(StateColor())(s)
non_state_color(s) = tokencolor(NonStateColor())(s)
misc_color(s) = tokencolor(MiscColor())(s)


text:
"""
    FVectorvariate

Structure that subtypes `VariateForm`, indicating that a single sample
is a vector from a fiber of a vector bundle.
"""
struct FVectorvariate <: VariateForm end

"""
    FVectorSupport(space::Manifold, VectorBundleFibers)

Value support for vector bundle fiber-valued distributions (values from a fiber of a vector
bundle at a `point` from the given manifold).
For example used for tangent vector-valued distributions.
"""
struct FVectorSupport{TSpace<:VectorBundleFibers,T} <: ValueSupport
    space::TSpace
    point::T
end

"""
    FVectorDistribution{TSpace<:VectorBundleFibers, T}

An abstract distribution for vector bundle fiber-valued distributions (values from a fiber
of a vector bundle at point `x` from the given manifold).
For example used for tangent vector-valued distributions.
"""
abstract type FVectorDistribution{TSpace<:VectorBundleFibers,T} <:
              Distribution{FVectorvariate,FVectorSupport{TSpace,T}} end

"""
    MPointvariate

Structure that subtypes `VariateForm`, indicating that a single sample
is a point on a manifold.
"""
struct MPointvariate <: VariateForm end

"""
    MPointSupport(M::Manifold)

Value support for manifold-valued distributions (values from given
[`Manifold`](@ref) `M`).
"""
struct MPointSupport{TM<:Manifold} <: ValueSupport
    manifold::TM
end

"""
    MPointDistribution{TM<:Manifold}

An abstract distribution for points on manifold of type `TM`.
"""
abstract type MPointDistribution{TM<:Manifold} <:
              Distribution{MPointvariate,MPointSupport{TM}} end

"""
    support(d::FVectorDistribution)

Get the object of type `FVectorSupport` for the distribution `d`.
"""
function Distributions.support(::T) where {T<:FVectorDistribution}
    return error("support not implemented for type $T")
end

@decorator_transparent_signature normal_tvector_distribution(
    M::AbstractDecoratorManifold,
    p,
    σ,
)

@decorator_transparent_signature projected_distribution(M::AbstractDecoratorManifold, d, p)
@decorator_transparent_signature projected_distribution(M::AbstractDecoratorManifold, d)


text:
module GpSelection
    export fixMatrix, calcSigma, generateZ, generateData, Options, PriorPars, varBayes

    using Distributions
    using MatrixDepot
    using Combinatorics

    include("utils.jl")
    include("sampledata.jl")
    include("varBayes.jl")
end


text:
#################################################################################################
#
# demo 10:  Live object tracking based on color thresholding
#
# based on http://opencv-srf.blogspot.no/2010/09/object-detection-using-color-seperation.html
# We use moments to calculate position of a single red object with HSV values
#
#################################################################################################

device_index = CAP_ANY

cxx"""
void ObjectTracking(int device_index)
{
    cv::VideoCapture capture(device_index);  // capture the video from webcam

    if (!capture.isOpened())   //  if no success, exit program
    {
        std::cout << "Cannot open the web cam";
        exit(0);
    }

    cv::namedWindow("Control",  cv::WINDOW_AUTOSIZE); //create a window called "Control"
    cv::namedWindow("Original", cv::WINDOW_AUTOSIZE); //create a window called "Original"
    cv::namedWindow("Thresholded Image", cv::WINDOW_AUTOSIZE); //create a window called "Original"

    int iLowH = 170;
    int iHighH = 179;

    int iLowS = 150;
    int iHighS = 255;

    int iLowV = 60;
    int iHighV = 255;

    //For HSV codes, go to http://www.rapidtables.com/web/color/color-picker.htm

    //Create trackbars in "Control" window
    cv::createTrackbar("LowH", "Control", &iLowH, 179); //Hue (0 - 179)
    cv::createTrackbar("HighH", "Control", &iHighH, 179);

    cv::createTrackbar("LowS", "Control", &iLowS, 255); //Saturation (0 - 255)
    cv::createTrackbar("HighS", "Control", &iHighS, 255);

    cv::createTrackbar("LowV", "Control", &iLowV, 255);//Value (0 - 255)
    cv::createTrackbar("HighV", "Control", &iHighV, 255);

    int iLastX = -1;
    int iLastY = -1;

    //Capture a temporary image from the camera
    cv::Mat imgTmp;
    capture.read(imgTmp);

    //Create a black image with the size as the camera output
    cv::Mat imgLines = cv::Mat::zeros(imgTmp.size(), CV_8UC3);

    cv::Mat imgOriginal;

    while (true)
    {
        // read a new frame from video
        bool bSuccess = capture.read(imgOriginal);

        if (!bSuccess) //if not success, break loop
        {
            std::cout << "Cannot read a frame from video stream";
            break;
        }

        cv::Mat imgHSV;

        cv::cvtColor(imgOriginal, imgHSV, cv::COLOR_BGR2HSV); //Convert the captured frame from BGR to HSV

        cv::Mat imgThresholded;

        cv::inRange(imgHSV, cv::Scalar(iLowH, iLowS, iLowV), cv::Scalar(iHighH, iHighS, iHighV), imgThresholded); //Threshold the image

        //morphological opening (removes small objects from the foreground)
        cv::erode(imgThresholded, imgThresholded, cv::getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(5, 5)) );
        cv::dilate(imgThresholded, imgThresholded, cv::getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(5, 5)) );

        //Calculate the moments of the thresholded image
        cv::Moments oMoments = moments(imgThresholded);

        double dM01 = oMoments.m01;
        double dM10 = oMoments.m10;
        double dArea = oMoments.m00;

        // if the area <= 10000
        if (dArea > 10000)
        {
            //calculate the position of the object
            int posX = dM10 / dArea;
            int posY = dM01 / dArea;

            if (iLastX >= 0 && iLastY >= 0 && posX >= 0 && posY >= 0)
            {
                //Draw a red line from the previous point to the current point
                cv::line(imgLines, cv::Point(posX, posY), cv::Point(iLastX, iLastY), cv::Scalar(0,0,255), 2);
            }

            iLastX = posX;
            iLastY = posY;
        }

        imgOriginal = imgOriginal + imgLines;
        cv::imshow("Original", imgOriginal);
        cv::imshow("Thresholded Image", imgThresholded); //show the thresholded image

        //wait for 'esc' key press for 30ms. If 'esc' key is pressed, break loop
        if (cv::waitKey(30) == 27)
        {
            std::cout << "esc key is pressed by user";
            cv::destroyAllWindows();
            break;
        }
     }
}
"""

@cxx ObjectTracking(device_index)


text:
function BlockRealMatrix(arg0::Vector{Vector{jdouble}})
    return BlockRealMatrix((Vector{Vector{jdouble}},), arg0)
end

function BlockRealMatrix(arg0::jint, arg1::jint)
    return BlockRealMatrix((jint, jint), arg0, arg1)
end

function BlockRealMatrix(arg0::jint, arg1::jint, arg2::Vector{Vector{jdouble}}, arg3::jboolean)
    return BlockRealMatrix((jint, jint, Vector{Vector{jdouble}}, jboolean), arg0, arg1, arg2, arg3)
end

function add(obj::BlockRealMatrix, arg0::BlockRealMatrix)
    return jcall(obj, "add", BlockRealMatrix, (BlockRealMatrix,), arg0)
end

function add(obj::BlockRealMatrix, arg0::RealMatrix)
    return jcall(obj, "add", BlockRealMatrix, (RealMatrix,), arg0)
end

function add_to_entry(obj::BlockRealMatrix, arg0::jint, arg1::jint, arg2::jdouble)
    return jcall(obj, "addToEntry", void, (jint, jint, jdouble), arg0, arg1, arg2)
end

function copy(obj::BlockRealMatrix)
    return jcall(obj, "copy", BlockRealMatrix, ())
end

function create_blocks_layout(::Type{BlockRealMatrix}, arg0::jint, arg1::jint)
    return jcall(BlockRealMatrix, "createBlocksLayout", Vector{Vector{jdouble}}, (jint, jint), arg0, arg1)
end

function create_matrix(obj::BlockRealMatrix, arg0::jint, arg1::jint)
    return jcall(obj, "createMatrix", BlockRealMatrix, (jint, jint), arg0, arg1)
end

function get_column(obj::BlockRealMatrix, arg0::jint)
    return jcall(obj, "getColumn", Vector{jdouble}, (jint,), arg0)
end

function get_column_dimension(obj::BlockRealMatrix)
    return jcall(obj, "getColumnDimension", jint, ())
end

function get_column_matrix(obj::BlockRealMatrix, arg0::jint)
    return jcall(obj, "getColumnMatrix", BlockRealMatrix, (jint,), arg0)
end

function get_column_vector(obj::BlockRealMatrix, arg0::jint)
    return jcall(obj, "getColumnVector", RealVector, (jint,), arg0)
end

function get_data(obj::BlockRealMatrix)
    return jcall(obj, "getData", Vector{Vector{jdouble}}, ())
end

function get_entry(obj::BlockRealMatrix, arg0::jint, arg1::jint)
    return jcall(obj, "getEntry", jdouble, (jint, jint), arg0, arg1)
end

function get_frobenius_norm(obj::BlockRealMatrix)
    return jcall(obj, "getFrobeniusNorm", jdouble, ())
end

function get_norm1(obj::BlockRealMatrix)
    return jcall(obj, "getNorm1", jdouble, ())
end

function get_norm_infty(obj::BlockRealMatrix)
    return jcall(obj, "getNormInfty", jdouble, ())
end

function get_row(obj::BlockRealMatrix, arg0::jint)
    return jcall(obj, "getRow", Vector{jdouble}, (jint,), arg0)
end

function get_row_dimension(obj::BlockRealMatrix)
    return jcall(obj, "getRowDimension", jint, ())
end

function get_row_matrix(obj::BlockRealMatrix, arg0::jint)
    return jcall(obj, "getRowMatrix", BlockRealMatrix, (jint,), arg0)
end

function get_row_vector(obj::BlockRealMatrix, arg0::jint)
    return jcall(obj, "getRowVector", RealVector, (jint,), arg0)
end

function get_sub_matrix(obj::BlockRealMatrix, arg0::jint, arg1::jint, arg2::jint, arg3::jint)
    return jcall(obj, "getSubMatrix", BlockRealMatrix, (jint, jint, jint, jint), arg0, arg1, arg2, arg3)
end

function multiply(obj::BlockRealMatrix, arg0::BlockRealMatrix)
    return jcall(obj, "multiply", BlockRealMatrix, (BlockRealMatrix,), arg0)
end

function multiply(obj::BlockRealMatrix, arg0::RealMatrix)
    return jcall(obj, "multiply", BlockRealMatrix, (RealMatrix,), arg0)
end

function multiply_entry(obj::BlockRealMatrix, arg0::jint, arg1::jint, arg2::jdouble)
    return jcall(obj, "multiplyEntry", void, (jint, jint, jdouble), arg0, arg1, arg2)
end

function multiply_transposed(obj::BlockRealMatrix, arg0::BlockRealMatrix)
    return jcall(obj, "multiplyTransposed", BlockRealMatrix, (BlockRealMatrix,), arg0)
end

function multiply_transposed(obj::BlockRealMatrix, arg0::RealMatrix)
    return jcall(obj, "multiplyTransposed", BlockRealMatrix, (RealMatrix,), arg0)
end

function operate(obj::BlockRealMatrix, arg0::Vector{jdouble})
    return jcall(obj, "operate", Vector{jdouble}, (Vector{jdouble},), arg0)
end

function pre_multiply(obj::BlockRealMatrix, arg0::Vector{jdouble})
    return jcall(obj, "preMultiply", Vector{jdouble}, (Vector{jdouble},), arg0)
end

function scalar_add(obj::BlockRealMatrix, arg0::jdouble)
    return jcall(obj, "scalarAdd", BlockRealMatrix, (jdouble,), arg0)
end

function scalar_multiply(obj::BlockRealMatrix, arg0::jdouble)
    return jcall(obj, "scalarMultiply", RealMatrix, (jdouble,), arg0)
end

function set_column(obj::BlockRealMatrix, arg0::jint, arg1::Vector{jdouble})
    return jcall(obj, "setColumn", void, (jint, Vector{jdouble}), arg0, arg1)
end

function set_column_matrix(obj::BlockRealMatrix, arg0::jint, arg1::RealMatrix)
    return jcall(obj, "setColumnMatrix", void, (jint, RealMatrix), arg0, arg1)
end

function set_column_vector(obj::BlockRealMatrix, arg0::jint, arg1::RealVector)
    return jcall(obj, "setColumnVector", void, (jint, RealVector), arg0, arg1)
end

function set_entry(obj::BlockRealMatrix, arg0::jint, arg1::jint, arg2::jdouble)
    return jcall(obj, "setEntry", void, (jint, jint, jdouble), arg0, arg1, arg2)
end

function set_row(obj::BlockRealMatrix, arg0::jint, arg1::Vector{jdouble})
    return jcall(obj, "setRow", void, (jint, Vector{jdouble}), arg0, arg1)
end

function set_row_matrix(obj::BlockRealMatrix, arg0::jint, arg1::BlockRealMatrix)
    return jcall(obj, "setRowMatrix", void, (jint, BlockRealMatrix), arg0, arg1)
end

function set_row_matrix(obj::BlockRealMatrix, arg0::jint, arg1::RealMatrix)
    return jcall(obj, "setRowMatrix", void, (jint, RealMatrix), arg0, arg1)
end

function set_row_vector(obj::BlockRealMatrix, arg0::jint, arg1::RealVector)
    return jcall(obj, "setRowVector", void, (jint, RealVector), arg0, arg1)
end

function set_sub_matrix(obj::BlockRealMatrix, arg0::Vector{Vector{jdouble}}, arg1::jint, arg2::jint)
    return jcall(obj, "setSubMatrix", void, (Vector{Vector{jdouble}}, jint, jint), arg0, arg1, arg2)
end

function subtract(obj::BlockRealMatrix, arg0::BlockRealMatrix)
    return jcall(obj, "subtract", BlockRealMatrix, (BlockRealMatrix,), arg0)
end

function subtract(obj::BlockRealMatrix, arg0::RealMatrix)
    return jcall(obj, "subtract", BlockRealMatrix, (RealMatrix,), arg0)
end

function to_blocks_layout(::Type{BlockRealMatrix}, arg0::Vector{Vector{jdouble}})
    return jcall(BlockRealMatrix, "toBlocksLayout", Vector{Vector{jdouble}}, (Vector{Vector{jdouble}},), arg0)
end

function transpose(obj::BlockRealMatrix)
    return jcall(obj, "transpose", BlockRealMatrix, ())
end

function transpose_multiply(obj::BlockRealMatrix, arg0::BlockRealMatrix)
    return jcall(obj, "transposeMultiply", BlockRealMatrix, (BlockRealMatrix,), arg0)
end

function transpose_multiply(obj::BlockRealMatrix, arg0::RealMatrix)
    return jcall(obj, "transposeMultiply", BlockRealMatrix, (RealMatrix,), arg0)
end

function walk_in_optimized_order(obj::BlockRealMatrix, arg0::RealMatrixChangingVisitor)
    return jcall(obj, "walkInOptimizedOrder", jdouble, (RealMatrixChangingVisitor,), arg0)
end

function walk_in_optimized_order(obj::BlockRealMatrix, arg0::RealMatrixChangingVisitor, arg1::jint, arg2::jint, arg3::jint, arg4::jint)
    return jcall(obj, "walkInOptimizedOrder", jdouble, (RealMatrixChangingVisitor, jint, jint, jint, jint), arg0, arg1, arg2, arg3, arg4)
end

function walk_in_optimized_order(obj::BlockRealMatrix, arg0::RealMatrixPreservingVisitor)
    return jcall(obj, "walkInOptimizedOrder", jdouble, (RealMatrixPreservingVisitor,), arg0)
end

function walk_in_optimized_order(obj::BlockRealMatrix, arg0::RealMatrixPreservingVisitor, arg1::jint, arg2::jint, arg3::jint, arg4::jint)
    return jcall(obj, "walkInOptimizedOrder", jdouble, (RealMatrixPreservingVisitor, jint, jint, jint, jint), arg0, arg1, arg2, arg3, arg4)
end

function walk_in_row_order(obj::BlockRealMatrix, arg0::RealMatrixChangingVisitor)
    return jcall(obj, "walkInRowOrder", jdouble, (RealMatrixChangingVisitor,), arg0)
end

function walk_in_row_order(obj::BlockRealMatrix, arg0::RealMatrixChangingVisitor, arg1::jint, arg2::jint, arg3::jint, arg4::jint)
    return jcall(obj, "walkInRowOrder", jdouble, (RealMatrixChangingVisitor, jint, jint, jint, jint), arg0, arg1, arg2, arg3, arg4)
end

function walk_in_row_order(obj::BlockRealMatrix, arg0::RealMatrixPreservingVisitor)
    return jcall(obj, "walkInRowOrder", jdouble, (RealMatrixPreservingVisitor,), arg0)
end

function walk_in_row_order(obj::BlockRealMatrix, arg0::RealMatrixPreservingVisitor, arg1::jint, arg2::jint, arg3::jint, arg4::jint)
    return jcall(obj, "walkInRowOrder", jdouble, (RealMatrixPreservingVisitor, jint, jint, jint, jint), arg0, arg1, arg2, arg3, arg4)
end


text:
export repressilator

using LabelledArrays, DynamicalSystemsBase, DelayEmbeddings

@inline @inbounds function eom_repressilator(u, p, t)
    α, α₀, n, β = p.α, p.α₀, p.n, p.β

    # pᵢ := concentration of protein repressor i
    # mᵢ := concentration of mRNA associated with pᵢ
    m₁, m₂, m₃, p₁, p₂, p₃ = u

    ṁ₁ = -m₁ + α/(1 + p₃^n) + α₀
    ṁ₂ = -m₂ + α/(1 + p₁^n) + α₀
    ṁ₃ = -m₃ + α/(1 + p₂^n) + α₀
    ṗ₁ = -β*(p₁ - m₁)
    ṗ₂ = -β*(p₂ - m₂)
    ṗ₃ = -β*(p₃ - m₃)

    return SVector{6}(ṁ₁, ṁ₂, ṁ₃, ṗ₁, ṗ₂, ṗ₃)
end

"""
    repressilator(;u₀ = rand(6), α = 10.0, α₀ = 0.0, β = 100.0,
        n = 2) → ContinuousDynamicalSystem

A six-dimensional repressilator (or repression-driven oscillator) from Elowitz & Leibler
(2000)[^Elowitz2000]. The equations are scaled to be non-dimensional.

Used in Sun & Bollt (2014) to study the performance of the causation entropy algorithm.

[^Elowitz2000]: Elowitz, M. B., & Leibler, S. (2000). A synthetic oscillatory network of
    transcriptional regulators. Nature, 403(6767), 335-338.
[^Sun2014]: Sun, J., Cafaro, C., & Bollt, E. M. (2014). Identifying the coupling structure
    in complex systems through the optimal causation entropy principle. Entropy, 16(6),
    3416-3433.
"""
function repressilator(;u₀ = rand(6), α = 10.0, α₀ = 0.0, β = 100.0, n = 2)

    p = @LArray [α, α₀, β, n] (:α, :α₀, :β, :n)
    ContinuousDynamicalSystem(eom_repressilator, u₀, p)
end


text:
mutable struct BackwardFlatInterpolation <: Interpolation
  x_vals::Vector{Float64}
  y_vals::Vector{Float64}
  primitive::Vector{Float64}
end

function BackwardFlatInterpolation()
  x_vals = Vector{Float64}()
  y_vals = Vector{Float64}()
  primitive = Vector{Float64}()

  return BackwardFlatInterpolation(x_vals, y_vals, primitive)
end

# Backward Flat initialize #
function initialize!(interp::BackwardFlatInterpolation, x_vals::Vector{Float64}, y_vals::Vector{Float64})
  interp.x_vals = x_vals
  interp.y_vals = y_vals
  interp.primitive = zeros(length(y_vals))

  return interp
end

# BackwardFlatInterpolation update
function update!(interp::BackwardFlatInterpolation, idx::Int)
  interp.primitive[1] = 0.0
  @simd for i = 2:idx
    @inbounds dx = interp.x_vals[i] - interp.x_vals[i - 1]
    @inbounds interp.primitive[i] = interp.primitive[i - 1] + dx * interp.y_vals[i]
  end

  return interp
end

update!(interp::BackwardFlatInterpolation) = update!(interp, length(interp.x_vals))

function value(interp::BackwardFlatInterpolation, x::Float64)
  if x <= interp.x_vals[1]
    return interp.y_vals[1]
  end

  i = locate(interp, x)
  if x == interp.x_vals[i]
    return interp.y_vals[i]
  else
    return i >= length(interp.y_vals) ? 0.0 : interp.y_vals[i + 1]
  end
end

function get_primitive(interp::BackwardFlatInterpolation, x::Float64, ::Bool)
  i = locate(interp, x)
  # if i > 4
  #   println(x)
  #   println(interp.x_vals)
  #   println(interp.y_vals)
  # end
  dx = x - interp.x_vals[i]
  return interp.primitive[i] + dx * (i >= length(interp.y_vals) ? 0.0 : interp.y_vals[i + 1])
end


text:
using Distributed, JSON

@everywhere begin
    using Pkg
    Pkg.activate(".")
end

@everywhere using CellularInfo

@everywhere function transfer(traj, src, dst, k)
    #  back = filter(f -> f != src && f != dst, 1:size(traj,2))
    #  cond = traj[:,back]
    #  transferentropy(traj[:,src], traj[:,dst], cond', k, 1000)
    transferentropy(traj[:,src], traj[:,dst], k, 1000)
end

function main()
    meante = zeros(Float64, 256)
    for rule in 0:255
        @time begin
            @info "Building graph for $(rule)..."
            k = 5
            width = 101
            duration = 200 + (width ÷ 2)
            samples = 10

            N = 4*samples*width*(width - 1)
            μ = 0.0
            for _ in 1:samples
                a = convert(Array{Int}, rand(Bool, width))
                b = 1 .- a
                c = reverse(a)
                d = reverse(b)

                traja = simulate(rule, a, duration)[width ÷ 2 + 1:end,:]
                trajb = simulate(rule, b, duration)[width ÷ 2 + 1:end,:]
                trajc = simulate(rule, a, duration)[width ÷ 2 + 1:end,:]
                trajd = simulate(rule, b, duration)[width ÷ 2 + 1:end,:]

                for src in 1:width
                    μ += @distributed (+) for dst in 1:width
                        if src == dst
                            0.0
                        else
                            tea = transfer(traja, src, dst, k)
                            teb = transfer(trajb, src, dst, k)
                            tec = transfer(trajc, src, dst, k)
                            ted = transfer(trajc, src, dst, k)

                            te = (tea.p < 0.05) ? tea.value : 0.0
                            te += (teb.p < 0.05) ? teb.value : 0.0
                            te += (tec.p < 0.05) ? tec.value : 0.0
                            te += (ted.p < 0.05) ? ted.value : 0.0
                        end
                    end
                end
            end
            meante[rule + 1] = μ / N
        end
    end

    open("rand.json", "w") do handle
        JSON.print(handle, meante)
    end
end

main()

max_stars_repo_name: ELIFE-ASU/dglmoore

max_issues_repo_name: ELIFE-ASU/dglmoore

max_forks_repo_name: ELIFE-ASU/dglmoore


text:
module Bonfire

using ..Ahorn, Maple

const placements = Ahorn.PlacementDict(
    "Bonfire" => Ahorn.EntityPlacement(
        Maple.Bonfire,
        "point"
    )
)

Ahorn.editingOptions(entity::Maple.Bonfire) = Dict{String, Any}(
    "mode" => Maple.bonfire_modes
)

function bonfireSprite(entity::Maple.Bonfire)
    mode = lowercase(get(entity.data, "mode", "unlit"))

    if mode == "lit"
        return "objects/campfire/fire08.png"

    elseif mode == "smoking"
        return "objects/campfire/smoking04.png"

    else
        return "objects/campfire/fire00.png"
    end
end

function Ahorn.selection(entity::Maple.Bonfire)
    x, y = Ahorn.position(entity)
    sprite = bonfireSprite(entity)

    return Ahorn.getSpriteRectangle(sprite, x, y, jx=0.5, jy=1.0)
end

function Ahorn.render(ctx::Ahorn.Cairo.CairoContext, entity::Maple.Bonfire, room::Maple.Room)
    sprite = bonfireSprite(entity)

    Ahorn.drawSprite(ctx, sprite, 0, 0, jx=0.5, jy=1.0)
end

end


text:
module BioformatsLoader
using JavaCall
import JavaCall.JNI
using LightXML
using ImageMetadata
using AxisArrays
using URIs
using ImageCore
using Downloads
using Logging

export
    set_id!,
    OMEXMLReader,
    openbytes,
    set_series!,
    getpixeltype,
    open_img,
    bf_import,
    open_stack,
    metadata,
    arraydata,
    axisnames

include("metadata.jl")
include("omexmlreader.jl")

const scheme2importer = Dict{String, Any}()

function add_importer(importer, schemes)
    for s in schemes
        scheme2importer[s] = importer
    end
end

function open_img(oxr::OMEXMLReader, index::Int)
    sx = get_size(oxr, "X")
    sy = get_size(oxr, "Y")
    arr = openbytes(oxr, index)
    return interpret_blob!(oxr, arr, (sx, sy))
end

for F in (:open_stack, :bf_import, :metadata)
    @eval begin
        function $F(filename::String, redirect::IO)
            redirect_stdout(() -> $F(filename), redirect)
        end
        function $F(filename::String, show_output::Bool)
            if show_output
                $F(filename)
            else
                STDOLD = stdout
                local ret
                redirect_stdout()
                try
                    ret = $F(filename)
                finally
                    redirect_stdout(STDOLD)
                end
                ret
            end
        end
    end
end

function open_stack(filename::String)
    OMEXMLReader(open_stack, filename)
end

function interpret_blob!(oxr, arr, sizes)
    arr = reinterpret(getpixeltype(oxr), arr)
    if !islittleendian(oxr)
        @. arr = ntoh(arr)
    end
    return reshape(arr, sizes)
end

function open_stack(oxr::OMEXMLReader; order="CYXZT")
    image_order = get_dimension_order(oxr)
    if isinterleaved(oxr)
        image_order = replace(image_order, "XYC" => "CXY")
    end

    sizes = [get_size(oxr, d) for d in image_order]
    size_dict = Dict(zip(image_order, sizes))

    for d in image_order
        if !in(d, order)
            @assert (size_dict[d] == 1) "Non-singleton dimension \"$d\" is not present in the requested image order \"$order\""
        end
    end

    arr = openbytes(oxr, 0)

    for i in 1:(get_image_count(oxr) - 1)
        arr_nd = openbytes(oxr, i)
        append!(arr,arr_nd)
    end

    im = interpret_blob!(oxr, arr, ((size_dict[d] for d in image_order if in(d, order))...,))
    im = permutedims(im, [findfirst(c, image_order) for c in order])

    return AxisArray(im, (Symbol(d) for d in order)...)
end

"""
    bf_import(uri::AbstractString; order::AbstractString="TZYXC", squeeze::Bool=false)

Import all images and metadata in the file using Bio-Formats.

The `order` keyword argument is the output order of dimensions, allowing you to
reshuffle the dimensions of the images or skip singleton dimensions. Providing
"CYX" for `order` gives you three-dimensional images in a "channels-first" data
format but will fail with an error if any of the images in the file has a size
greater than one in the `T` or `Z` dimension.

By setting the `squeeze` keyword argument to `true` all singleton dimensions in
the images will be dropped (even if they are in the `order` argument).
"""
function bf_import(uri; kwargs...)
    u = URI(uri)
    if u.scheme in keys(scheme2importer)
        scheme2importer[u.scheme](u; kwargs...)
    else
        if length(u.scheme) > 1
            @warn "Unrecognized scheme \"$(u.scheme)\", attempting to open as file"
        end
        bf_import_file(uri; kwargs...)
    end
end

bf_import_file(uri::URI; kwargs...) = bf_import_file(uri.path; kwargs...)
function bf_import_file(filename::AbstractString; order="CYXZT", squeeze=false, gray=false)
    OMEXMLReader(filename) do oxr
        xml = get_xml(oxr)
        images = Array{ImageMeta,1}()

        metalst = get_elements_by_tagname(root(xml), "Image")
        for i = 1:length(metalst)
            set_series!(oxr, i-1)
            img = open_stack(oxr; order = order)
            if squeeze
                img = dropdims(img; dims=((i for i in 1:ndims(img) if size(img, i) == 1)...,))
            end
            if gray
                img = as_gray(img)
            end
            properties = xml_to_dict(metalst[i])
            properties[:ImportOrder] = axisnames(img)
            push!(images, ImageMeta(img, properties))
        end

        return images
    end
end

add_importer(bf_import_file, ["file"])

"""
    bf_import_http(url::AbstractString, [ filename::AbstractString ]; kwargs...)

Download and import an image using Bio-Formats.
"""
bf_import_http(url::AbstractString, args...; kwargs...) = bf_import_http(URI(url), args...; kwargs...)

function bf_import_http(url::URI; kwargs...)
    filename = basename(url.path)
    @assert (filename != "") "Could not determine filename from URL"
    bf_import_http(url, filename; kwargs...)
end

function bf_import_http(url::URI, filename::AbstractString; kwargs...)
    mktempdir() do path
        imgpath = joinpath(path, filename)
        Downloads.download(string(url), imgpath)
        bf_import_file(imgpath; kwargs...)
    end
end

add_importer(bf_import_http, ["http", "https"])

function as_gray(arr::A) where A <: AbstractArray{T} where T <: Unsigned
    map(x -> Gray(reinterpret(Normed{T, sizeof(T)*8}, x)), arr)
end
function as_gray(arr::A) where A <: AbstractArray{T} where T <: AbstractFloat
    map(Gray, arr)
end
function as_gray(arr::A) where A <: AbstractArray{Bool}
    map(Gray, arr)
end

function metadata(filename::String)
    OMEXMLReader(filename) do oxr
        xml = get_xml(oxr)
        properties = Dict{String, Any}()
        metalst = get_elements_by_tagname(root(xml), "Image")

        SizeC = get_size(oxr, "C")

        for a = attributes(metalst[1])
            push!(properties, "$(name(a))"=>value(a))
        end
        for a = attributes(find_element(metalst[1], "Pixels"))
            try
                push!(properties, "$(name(a))"=> parse(Float64, value(a)))
            catch ex
                if ex isa ArgumentError
                    push!(properties, "$(name(a))"=>  value(a))
                end
            end
        end

        for i in 1:SizeC
            for a in attributes(metalst[1]["Pixels"][1]["Channel"][i])
                if name(a)== "EmissionWavelength"
                    push!(properties, "channel_$i"=>value(a))
                end
            end
        end
        properties
    end
    properties
end

const levels = ["ALL", "DEBUG", "ERROR", "FATAL", "INFO", "OFF", "TRACE", "WARN"]
function enableLogging(level::String)
    level in levels || error("enableLogging: level argument must be one of "*join(levels,", "))
    dt = @jimport(loci.common.DebugTools)
    Bool(jcall(dt,"enableLogging",jboolean,(JString,),level))
end

get_bf_path() = joinpath(dirname(@__DIR__), "deps", "bioformats_package.jar")

function init(;memory=1024::Int,log_level::String="ERROR")
    bfpkg_path = get_bf_path()
    JavaCall.init(["-ea", "-Xmx$(memory)M", "-Djava.class.path=$bfpkg_path"])
    enableLogging(log_level) || @warn "Could not enable logging."
    nothing
end

end


text:
module VSIE
    using ..BEAST
    Mod = BEAST

    """
        singlelayer(;gamma, alpha, beta, tau)
        singlelayer(;wavenumber, alpha, beta, tau)

    Bilinear form given by:

    ```math
        α ∬_{Γ×Ω} j(x)⋅τ(y)⋅k(y) G_{γ}(x,y) + β ∬_{Γ×Ω} div j(x) τ(y) div k(y) G_{γ}(x,y)
    ```

    with ``G_{γ} = e^{-γ|x-y|} / 4π|x-y|``
    and  ``τ(y)`` contrast dyadic
    """

    function singlelayer(;
            gamma=nothing,
            wavenumber=nothing,
            alpha=nothing,
            beta=nothing,
            tau=nothing)

        if (gamma == nothing) && (wavenumber == nothing)
            error("Supply one of (not both) gamma or wavenumber")
        end

        if (gamma != nothing) && (wavenumber != nothing)
            error("Supply one of (not both) gamma or wavenumber")
        end

        if gamma == nothing
            if iszero(real(wavenumber))
                gamma = -imag(wavenumber)
            else
                gamma = im*wavenumber
            end
        end

        @assert gamma != nothing

        alpha == nothing && (alpha = -gamma)
        beta  == nothing && (beta  = -1/gamma)
        tau   == nothing && (tau   = x->1.0)

        Mod.VSIESingleLayer(gamma, alpha, beta, tau)
    end

    function singlelayer2(;
            gamma=nothing,
            wavenumber=nothing,
            alpha=nothing,
            beta=nothing,
            tau=nothing)

        if (gamma == nothing) && (wavenumber == nothing)
            error("Supply one of (not both) gamma or wavenumber")
        end

        if (gamma != nothing) && (wavenumber != nothing)
            error("Supply one of (not both) gamma or wavenumber")
        end

        if gamma == nothing
            if iszero(real(wavenumber))
                gamma = -imag(wavenumber)
            else
                gamma = im*wavenumber
            end
        end

        @assert gamma != nothing

        alpha == nothing && (alpha = -gamma)
        beta  == nothing && (beta  = -1/gamma)
        tau   == nothing && (tau   = x->1.0)

        Mod.VSIESingleLayer2(gamma, alpha, beta, tau)
    end

    """
    boundary(;gamma, alpha, tau)
    boundary(;wavenumber, alpha, tau)

    Bilinear form given by:

    ```math
        α ∬_{Γ×Ω} T_n j(x) grad G_{γ}(x,y)⋅τ(y) div k(y)
    ```

    with ``G_{γ} = e^{-γ|x-y|} / 4π|x-y|``
    and  ``τ(y)`` contrast dyadic
    """

    function boundary(;
            gamma=nothing,
            wavenumber=nothing,
            alpha=nothing,
            tau=nothing)

        if (gamma == nothing) && (wavenumber == nothing)
            error("Supply one of (not both) gamma or wavenumber")
        end

        if (gamma != nothing) && (wavenumber != nothing)
            error("Supply one of (not both) gamma or wavenumber")
        end

        if gamma == nothing
            if iszero(real(wavenumber))
                gamma = -imag(wavenumber)
            else
                gamma = im*wavenumber
            end
        end

        @assert gamma != nothing

        alpha == nothing && (alpha = 1.0)
        tau   == nothing && (tau   = x->1.0)

        Mod.VSIEBoundary(gamma, alpha, tau)
    end

    function boundaryT(;
            gamma=nothing,
            wavenumber=nothing,
            alpha=nothing,
            tau=nothing)

        if (gamma == nothing) && (wavenumber == nothing)
            error("Supply one of (not both) gamma or wavenumber")
        end

        if (gamma != nothing) && (wavenumber != nothing)
            error("Supply one of (not both) gamma or wavenumber")
        end

        if gamma == nothing
            if iszero(real(wavenumber))
                gamma = -imag(wavenumber)
            else
                gamma = im*wavenumber
            end
        end

        @assert gamma != nothing

        alpha == nothing && (alpha = 1.0)
        tau   == nothing && (tau   = x->1.0)

        Mod.VSIEBoundaryT(gamma, alpha, tau)
    end

    """
    doublelayer(;gamma, alpha, beta, tau)
    doublelayer(;wavenumber, alpha, beta, tau)

    Bilinear form given by:

    ```math
        α ∬_{Ω×Γ} j(x) ⋅ grad G_{γ}(x,y) × τ(y)⋅k(y)
    ```

    with ``G_{γ} = e^{-γ|x-y|} / 4π|x-y|``
    and  ``τ(y)`` contrast dyadic
    """

    function doublelayer(;
            gamma=nothing,
            wavenumber=nothing,
            alpha=nothing,
            beta=nothing,
            tau=nothing)

        if (gamma == nothing) && (wavenumber == nothing)
            error("Supply one of (not both) gamma or wavenumber")
        end

        if (gamma != nothing) && (wavenumber != nothing)
            error("Supply one of (not both) gamma or wavenumber")
        end

        if gamma == nothing
            if iszero(real(wavenumber))
                gamma = -imag(wavenumber)
            else
                gamma = im*wavenumber
            end
        end

        @assert gamma != nothing

        alpha == nothing && (alpha = 1.0)
        tau   == nothing && (tau   = x->1.0)

        Mod.VSIEDoubleLayer(gamma, alpha, tau)
    end

    function doublelayerT(;
            gamma=nothing,
            wavenumber=nothing,
            alpha=nothing,
            beta=nothing,
            tau=nothing)

        if (gamma == nothing) && (wavenumber == nothing)
            error("Supply one of (not both) gamma or wavenumber")
        end

        if (gamma != nothing) && (wavenumber != nothing)
            error("Supply one of (not both) gamma or wavenumber")
        end

        if gamma == nothing
            if iszero(real(wavenumber))
                gamma = -imag(wavenumber)
            else
                gamma = im*wavenumber
            end
        end

        @assert gamma != nothing

        alpha == nothing && (alpha = 1.0)
        tau   == nothing && (tau   = x->1.0)

        Mod.VSIEDoubleLayerT(gamma, alpha, tau)
    end

end


text:
using LazyJSON
using Test

using DataStructures

using JSON2

module JSON_jl
    using JSON
end
const JSON = LazyJSON

include("SplicedStrings.jl")

const parsers = [
    ("LazyJSON.jl", x->LazyJSON.parse(x)),
    ("JSON.jl", x->JSON_jl.JSON.parse(x)),
    ("JSON2.jl", x->JSON2.read(x))
]

const non_lazy_parsers = [
    ("LazyJSON.jl", x->LazyJSON.parse(x; lazy=false)),
    ("JSON.jl", x->JSON_jl.JSON.parse(x)),
    ("JSON2.jl", x->JSON2.read(x))
]

const COMPARE_JSON_JL = false

if !COMPARE_JSON_JL
    parsers = parsers[1:1]
    non_lazy_parsers = non_lazy_parsers[1:1]
end

struct Foo
    a::Int
    b
end

mutable struct Bar
    f::Foo
    v::Vector{Int}
    s::AbstractString
    s2::String
    ov::Vector{Foo}
end

struct Geometry
    _type
    coordinates
end

struct CityLot
    _type
    properties
    geometry::Geometry
end

struct Owner
    login
end

struct Repo
    id
    name
    owner::Owner
    parent
    full_name
    private::Bool
    url
    language
    pushed_at
    permissions
end

include("AbstractString.jl")

include("IOString.jl")

"""
https://tools.ietf.org/html/rfc7159#section-13
"""
rfc_example = """
    {
        "Image": {
            "Width":  800,
            "Height": 600,
            "Title":  "View from 15th Floor",
            "Thumbnail": {
                "Url":    "http://www.example.com/image/481989943",
                "Height": 125,
                "Width":  100
            },
            "Animated" : false,
            "IDs": [116, 943, 234, 38793]
        }
    }
"""

@testset "pr_3" begin
@test Int(LazyJSON.value("1:")) == 1 # FIXME Lazy Int parsing stops at
                                     #       non-digit. But maybe should error.
end

#-------------------------------------------------------------------------------
@testset "convert" begin
#-------------------------------------------------------------------------------

j = LazyJSON.value("""{
    "f": {"a": 1, "b": "foo"},
    "v": [1,2,3,4,5],
    "s": "Hello",
    "s2": "World!",
    "ov": [
        {"a": 1, "b": true},
        {"a": 2, "b": false},
        {"a": 3, "b": null}
    ]
}""", getproperty=true)

@test j isa JSON.Object || j isa JSON.PropertyDict
@test j.f.a == 1
@test j.f.b == "foo"
@test j.v == [1, 2, 3, 4, 5]           ;@test j.v isa JSON.Array
@test j.s == "Hello"                   ;@test j.s isa JSON.String
@test j.s2 == "World!"                 ;@test j.s2 isa JSON.String
@test j.ov[1].a == 1
@test j.ov[1].b == true
@test j.ov[2].a == 2
@test j.ov[2].b == false
@test j.ov[3].a == 3
@test j.ov[3].b == nothing

v = convert(Bar, j)

@test v isa Bar
@test v.f.a == 1
@test v.f.b == "foo"
@test v.v == [1, 2, 3, 4, 5]           ;@test v.v isa Vector{Int}
@test v.s == "Hello"                   ;@test v.s isa JSON.String
@test v.s2 == "World!"                 ;@test v.s2 isa Base.String
@test v.ov[1] == Foo(1, true)          ;@test v.ov[1] isa Foo
@test v.ov[2] == Foo(2, false)
@test v.ov[3] == Foo(3, nothing)

d = convert(Dict, j)

@test d isa Dict{AbstractString,Any}
@test d["f"]["a"] == 1
@test d["f"]["b"] == "foo"
@test d["v"] == [1, 2, 3, 4, 5]
@test d["s"] == "Hello"                ;@test d["s"] isa JSON.String
@test d["s2"] == "World!"              ;@test d["s2"] isa JSON.String
@test d["ov"][1]["a"] == 1
@test d["ov"][1]["b"] == true
@test d["ov"][2]["a"] == 2
@test d["ov"][2]["b"] == false
@test d["ov"][3]["a"] == 3
@test d["ov"][3]["b"] == nothing

end #testset

#-------------------------------------------------------------------------------
@testset "RFC7159 example" begin
#-------------------------------------------------------------------------------

v = JSON.parse(rfc_example)

@test v isa JSON.Object || v isa JSON.PropertyDict

x = v["Image"]["Width"]
@test x == 800
@test x isa JSON.Number

x = v["Image"]["Thumbnail"]["Url"]

@test x == "http://www.example.com/image/481989943"

@test SubString(x) == "http://www.example.com/image/481989943"

x = v["Image"]["IDs"]
@test collect(x) == [116, 943, 234, 38793]
@test length(collect(x)) == 4

v = JSON.parse(rfc_example)
x = v["Image"]["IDs"]
@test sum(x) == 40086

end # testset

#-------------------------------------------------------------------------------
@testset "RFC7159 example with trailing garbage" begin
#-------------------------------------------------------------------------------

v = JSON.parse("""{"Foo": $rfc_example, "Bar": garbage!""")
@test sum(v["Foo"]["Image"]["IDs"]) == 40086

@test_throws JSON.ParseError v["Bar"]
try
    v["Bar"]
catch e
    @test "$e" == strip("""
    JSON.ParseError: invalid value index at line 15, col 10: 'g'
    , "Bar": garbage!
             ^
    """)
end

end # testset

#-------------------------------------------------------------------------------
@testset "http://www.json.org/JSON_checker" begin
#-------------------------------------------------------------------------------

j = String(read("json_checker.json"))

for (n, f) in parsers @testset "http://www.json.org/JSON_checker.$n" begin

try

v = f(j)

@test v[1] == "JSON Test Pattern pass1"
@test v[2]["object with 1 member"][1] == "array with 1 element"
@test length(v[3]) == 0
@test v[3] isa JSON.Object || v[3] isa JSON.PropertyDict || v[3] isa Dict
@test [x for x in v[4]] == Any[]
@test v[4] isa JSON.Array || v[4] isa Array
@test v[5] == -42
@test v[6]
@test !v[7]
@test v[8] == nothing
@test v[9]["integer"] == 1234567890
@test v[9]["real"] == -9876.543210
@test v[9]["e"] == 0.123456789e-12
@test v[9]["E"] == 1.234567890E+34
@test v[9][""] == 23456789012E66
@test v[9]["zero"] == 0
@test v[9]["one"] == 1
@test v[9]["space"] == " "
@test v[9]["quote"] == "\""
@test v[9]["backslash"] == "\\"
@test v[9]["controls"] == "\b\f\n\r\t"
@test v[9]["slash"] == "/ & /"
@test v[9]["alpha"] == "abcdefghijklmnopqrstuvwyz"
@test v[9]["ALPHA"] == "ABCDEFGHIJKLMNOPQRSTUVWYZ"
@test v[9]["digit"] == "0123456789"
@test v[9]["0123456789"] == "digit"
@test v[9]["special"] == "`1~!@#\$%^&*()_+-={':[,]}|;.</>?"
@test v[9]["hex"] == "\u0123\u4567\u89AB\uCDEF\uabcd\uef4A"
@test v[9]["true"] == true
@test v[9]["false"] == false
@test v[9]["null"] == nothing
@test [x for x in v[9]["array"]] == Any[]
@test [x for x in v[9]["object"]] == Pair[]
@test v[9]["address"] == "50 St. James Street"
@test v[9]["url"] == "http://www.JSON.org/"
@test v[9]["comment"] == "// /* <!-- --"
@test v[9]["# -- --> */"] == " "
@test collect(v[9][" s p a c e d "]) == collect(1:7)
@test collect(v[9]["compact"]) == collect(1:7)
@test v[9]["jsontext"] == "{\"object with 1 member\":[\"array with 1 element\"]}"
@test v[9]["quotes"] == "" \u0022 %22 0x22 034 ""
@test v[9]["/\\\"\uCAFE\uBABE\uAB98\uFCDE\ubcda\uef4A\b\f\n\r\t`1~!@#\$%^&*()_+-=[]{}|;:',./<>?"] == "A key can be any string"
@test v[10] == 0.5
@test v[11] == 98.6
@test v[12] == 99.44
@test v[13] == 1066
@test v[14] == 1e1
@test v[15] == 0.1e1
@test v[16] == 1e-1
@test v[17] == 1e00
@test v[18] == 2e+00
@test v[19] == 2e-00
@test v[20] == "rosebud"

catch e
    @warn "$n: $e"
end

end # testset
end # for loop

end # testset

#-------------------------------------------------------------------------------
@testset "Escaped values in keys" begin
#-------------------------------------------------------------------------------

json = Vector{UInt8}(codeunits("""
    {
        "Image\t Tab": {
            "Width":  800,
            "Height": 600,
            "Title":  "View from 15th Floor",
            "Thumb\\nail": {
                "\\ud83e\\udd16 Url": "http://www.example.com/image/481989943",
                "Height": 125,
                "Width":  100
            },
            "Animated" : false,
            "IDs": [116, 943, 234, 38793]
        }
    }
"""))

v = JSON.parse(json)

x = v["Image\t Tab"]["Thumb\nail"]["🤖 Url"]

@test x == "http://www.example.com/image/481989943"

end # testset

#-------------------------------------------------------------------------------
@testset "ec2-2016-11-15.normal.json" begin
#-------------------------------------------------------------------------------

j = String(read("ec2-2016-11-15.normal.json"))

r = JSON.parse(j)
@test r["operations"
      ]["AcceptReservedInstancesExchangeQuote"
      ]["input"
      ]["shape"] |> String == "AcceptReservedInstancesExchangeQuoteRequest"

@test r["shapes"
      ]["scope"
      ]["enum"
      ][1] |> String == "Availability Zone"

end # testset

#-------------------------------------------------------------------------------
@testset "github.com/nst/JSONTestSuite" begin
#-------------------------------------------------------------------------------

for (n, jparse) in non_lazy_parsers @testset "github.com/nst/JSONTestSuite.$n" begin

@test jparse("[123.456e-789]") == Any[BigFloat("1.23456e-787")] # i_number_double_huge_neg_exp.json
@test jparse("[0.4e00669999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999969999999006]") == Any[Inf] # i_number_huge_exp.json
@test jparse("[-1e+9999]") == Any[BigFloat("-1.0e+9999")]
@test jparse("[1.5e+9999]") == Any[BigFloat("1.5e+9999")]
@test jparse("[-123123e100000]") == Any[BigFloat("-123123e100000")]
@test jparse("[123123e100000]") == Any[BigFloat("123123e100000")]
@test jparse("[123e-10000000]") == Any[BigFloat("123e-10000000")]
@test jparse("[-123123123123123123123123123123]") == Any[-123123123123123123123123123123] # i_number_too_big_neg_int.json
@test jparse("[100000000000000000000]") == Any[100000000000000000000] # i_number_too_big_pos_int.json
@test jparse("[-237462374673276894279832749832423479823246327846]") == Any[-237462374673276894279832749832423479823246327846] # i_number_very_big_negative_int.json
@test jparse("{\"\\uDFAA\":0}") == Dict("\udfaa"=>0) # i_object_key_lone_2nd_surrogate.json
@test jparse("[\"\\uDADA\"]") == Any["\udada"] # i_string_1st_surrogate_but_2nd_missing.json
@test jparse("[\"\\uD888\\u1234\"]") == Any["\ud888ሴ"] # i_string_1st_valid_surrogate_2nd_invalid.json
@test jparse("[\"日ш\xfa\"]") == Any["日ш\xfa"] # i_string_UTF-8_invalid_sequence.json
@test jparse("[\"\ud800\"]") == Any["\ud800"] # i_string_UTF8_surrogate_U+D800.json
@test jparse("[\"\\uD800\\n\"]") == Any["\ud800\n"] # i_string_incomplete_surrogate_and_escape_valid.json
@test jparse("[\"\\uDd1ea\"]") == Any["\udd1ea"] # i_string_incomplete_surrogate_pair.json
@test jparse("[\"\\uD800\\uD800\\n\"]") == Any["\ud800\ud800\n"] # i_string_incomplete_surrogates_escape_valid.json
@test jparse("[\"\\ud800\"]") == Any["\ud800"] # i_string_invalid_lonely_surrogate.json
@test jparse("[\"\\ud800abc\"]") == Any["\ud800abc"] # i_string_invalid_surrogate.json
@test jparse("[\"\xff\"]") == Any["\xff"] # i_string_invalid_utf-8.json
@test jparse("[\"\\uDd1e\\uD834\"]") == Any["\udd1e\ud834"] # i_string_inverted_surrogates_U+1D11E.json
@test jparse("[\"\xe9\"]") == Any["\xe9"] # i_string_iso_latin_1.json
@test jparse("[\"\\uDFAA\"]") == Any["\udfaa"] # i_string_lone_second_surrogate.json
@test jparse("[\"\x81\"]") == Any["\x81"] # i_string_lone_utf8_continuation_byte.json
c = String(UInt8[ 0xf4, 0xbf, 0xbf, 0xbf])
@test jparse("[\"$c\"]") == Any["$c"] # i_string_not_in_unicode_range.json
@test jparse("[\"\xc0\xaf\"]") == Any["\xc0\xaf"] # i_string_overlong_sequence_2_bytes.json
@test jparse("[\"\xfc\x83\xbf\xbf\xbf\xbf\"]") == Any["\xfc\x83\xbf\xbf\xbf\xbf"] # i_string_overlong_sequence_6_bytes.json
@test jparse("[\"\xfc\x80\x80\x80\x80\x80\"]") == Any["\xfc\x80\x80\x80\x80\x80"] # i_string_overlong_sequence_6_bytes_null.json
@test jparse("[\"\xe0\xff\"]") == Any["\xe0\xff"] # i_string_truncated-utf-8.json
@test jparse("[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]") == Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[Any[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]] # i_structure_500_nested_arrays.json
@test jparse("[[]   ]") == Any[Any[]] # y_array_arraysWithSpaces.json
@test jparse("[\"\"]") == Any[""] # y_array_empty-string.json
@test jparse("[]") == Any[] # y_array_empty.json
@test jparse("[\"a\"]") == Any["a"] # y_array_ending_with_newline.json
@test jparse("[false]") == Any[false] # y_array_false.json
@test jparse("[null, 1, \"1\", {}]") == Any[nothing, 1, "1", DataStructures.OrderedDict{SubString{String},Any}()] # y_array_heterogeneous.json
@test jparse("[null]") == Any[nothing] # y_array_null.json
@test jparse("[1\n]") == Any[1] # y_array_with_1_and_newline.json
@test jparse(" [1]") == Any[1] # y_array_with_leading_space.json
@test jparse("[1,null,null,null,2]") == Any[1, nothing, nothing, nothing, 2] # y_array_with_several_null.json
@test jparse("[2] ") == Any[2] # y_array_with_trailing_space.json
@test jparse("[123e65]") == Any[1.23e67] # y_number.json
@test jparse("[0e+1]") == Any[0.0] # y_number_0e+1.json
@test jparse("[0e1]") == Any[0.0] # y_number_0e1.json
@test jparse("[ 4]") == Any[4] # y_number_after_space.json
#@test jparse("[-0.000000000000000000000000000000000000000000000000000000000000000000000000000001]\n") == Any[BigFloat("-0.000000000000000000000000000000000000000000000000000000000000000000000000000001")] # y_number_double_close_to_zero.json
@test jparse("[20e1]") == Any[200.0] # y_number_int_with_exp.json
@test jparse("[-0]") == Any[-0.0] # y_number_minus_zero.json
@test jparse("[-123]") == Any[-123] # y_number_negative_int.json
@test jparse("[-1]") == Any[-1] # y_number_negative_one.json
@test jparse("[-0]") == Any[-0.0] # y_number_negative_zero.json
@test jparse("[1E22]") == Any[1.0e22] # y_number_real_capital_e.json
@test jparse("[1E-2]") == Any[0.01] # y_number_real_capital_e_neg_exp.json
@test jparse("[1E+2]") == Any[100.0] # y_number_real_capital_e_pos_exp.json
@test jparse("[123e45]") == Any[1.23e47] # y_number_real_exponent.json
@test jparse("[123.456e78]") == Any[1.23456e80] # y_number_real_fraction_exponent.json
@test jparse("[1e-2]") == Any[0.01] # y_number_real_neg_exp.json
@test jparse("[1e+2]") == Any[100.0] # y_number_real_pos_exponent.json
@test jparse("[123]") == Any[123] # y_number_simple_int.json
@test jparse("[123.456789]") == Any[123.456789] # y_number_simple_real.json
@test jparse("{\"asd\":\"sdf\", \"dfg\":\"fgh\"}") == DataStructures.OrderedDict{SubString{String},Any}("asd"=>"sdf","dfg"=>"fgh") # y_object.json
@test jparse("{\"asd\":\"sdf\"}") == DataStructures.OrderedDict{SubString{String},Any}("asd"=>"sdf") # y_object_basic.json
@test jparse("{\"a\":\"b\",\"a\":\"c\"}") == DataStructures.OrderedDict{SubString{String},Any}("a"=>"c") # y_object_duplicated_key.json
@test jparse("{\"a\":\"b\",\"a\":\"b\"}") == DataStructures.OrderedDict{SubString{String},Any}("a"=>"b") # y_object_duplicated_key_and_value.json
@test jparse("{}") == DataStructures.OrderedDict{SubString{String},Any}() # y_object_empty.json
@test jparse("{\"\":0}") == DataStructures.OrderedDict{SubString{String},Any}(""=>0) # y_object_empty_key.json
@test jparse("{\"foo\\u0000bar\": 42}") == DataStructures.OrderedDict{SubString{String},Any}("foo\0bar"=>42) # y_object_escaped_null_in_key.json
@test jparse("{ \"min\": -1.0e+28, \"max\": 1.0e+28 }") == DataStructures.OrderedDict{SubString{String},Any}("min"=>-1.0e28,"max"=>1.0e28) # y_object_extreme_numbers.json
@test jparse("{\"x\":[{\"id\": \"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"}], \"id\": \"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"}") == DataStructures.OrderedDict{SubString{String},Any}("x"=>Any[DataStructures.OrderedDict{SubString{String},Any}("id"=>"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")],"id"=>"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx") # y_object_long_strings.json
@test jparse("{\"a\":[]}") == DataStructures.OrderedDict{SubString{String},Any}("a"=>Any[]) # y_object_simple.json
@test jparse("{\"title\":\"\\u041f\\u043e\\u043b\\u0442\\u043e\\u0440\\u0430 \\u0417\\u0435\\u043c\\u043b\\u0435\\u043a\\u043e\\u043f\\u0430\" }") == DataStructures.OrderedDict{SubString{String},Any}("title"=>"Полтора Землекопа") # y_object_string_unicode.json
@test jparse("{\n\"a\": \"b\"\n}") == DataStructures.OrderedDict{SubString{String},Any}("a"=>"b") # y_object_with_newlines.json
@test jparse("[\"\\u0060\\u012a\\u12AB\"]") == Any["`Īካ"] # y_string_1_2_3_bytes_UTF-8_sequences.json
@test jparse("[\"\\uD801\\udc37\"]") == Any["𐐷"] # y_string_accepted_surrogate_pair.json
@test jparse("[\"\\ud83d\\ude39\\ud83d\\udc8d\"]") == Any["😹💍"] # y_string_accepted_surrogate_pairs.json
@test jparse("[\"\\\"\\\\\\/\\b\\f\\n\\r\\t\"]") == Any["\"\\/\b\f\n\r\t"] # y_string_allowed_escapes.json
@test jparse("[\"\\\\u0000\"]") == Any["\\u0000"] # y_string_backslash_and_u_escaped_zero.json
@test jparse("[\"\\\"\"]") == Any["\""] # y_string_backslash_doublequotes.json
@test jparse("[\"a/*b*/c/*d//e\"]") == Any["a/*b*/c/*d//e"] # y_string_comments.json
@test jparse("[\"\\\\a\"]") == Any["\\a"] # y_string_double_escape_a.json
@test jparse("[\"\\\\n\"]") == Any["\\n"] # y_string_double_escape_n.json
@test jparse("[\"\\u0012\"]") == Any["\x12"] # y_string_escaped_control_character.json
@test jparse("[\"\\uFFFF\"]") == Any["\uffff"] # y_string_escaped_noncharacter.json
@test jparse("[\"asd\"]") == Any["asd"] # y_string_in_array.json
@test jparse("[ \"asd\"]") == Any["asd"] # y_string_in_array_with_leading_space.json
@test jparse("[\"\\uDBFF\\uDFFF\"]") == Any["\U10ffff"] # y_string_last_surrogates_1_and_2.json
@test jparse("[\"new\\u00A0line\"]") == Any["new line"] # y_string_nbsp_uescaped.json
@test jparse("[\"\U10ffff\"]") == Any["\U10ffff"] # y_string_nonCharacterInUTF-8_U+10FFFF.json
@test jparse("[\"\U1bfff\"]") == Any["\U1bfff"] # y_string_nonCharacterInUTF-8_U+1FFFF.json
@test jparse("[\"\uffff\"]") == Any["\uffff"] # y_string_nonCharacterInUTF-8_U+FFFF.json
@test jparse("[\"\\u0000\"]") == Any["\0"] # y_string_null_escape.json
@test jparse("[\"\\u002c\"]") == Any[","] # y_string_one-byte-utf-8.json
@test jparse("[\"π\"]") == Any["π"] # y_string_pi.json
@test jparse("[\"asd \"]") == Any["asd "] # y_string_simple_ascii.json
@test jparse("\" \"") == " "  # y_string_space.json
@test jparse("[\"\\uD834\\uDd1e\"]") == Any["𝄞"] # y_string_surrogates_U+1D11E_MUSICAL_SYMBOL_G_CLEF.json
@test jparse("[\"\\u0821\"]") == Any["ࠡ"] # y_string_three-byte-utf-8.json
@test jparse("[\"\\u0123\"]") == Any["ģ"] # y_string_two-byte-utf-8.json
@test jparse("[\"\u2028\"]") == Any["\u2028"] # y_string_u+2028_line_sep.json
@test jparse("[\"\u2029\"]") == Any["\u2029"] # y_string_u+2029_par_sep.json
@test jparse("[\"\\u0061\\u30af\\u30EA\\u30b9\"]") == Any["aクリス"] # y_string_uEscape.json
@test jparse("[\"new\\u000Aline\"]") == Any["new\nline"] # y_string_uescaped_newline.json
@test jparse("[\"\x7f\"]") == Any["\x7f"] # y_string_unescaped_char_delete.json
@test jparse("[\"\\uA66D\"]") == Any["ꙭ"] # y_string_unicode.json
@test jparse("[\"\\u005C\"]") == Any["\\"] # y_string_unicodeEscapedBackslash.json
@test jparse("[\"⍂㈴⍂\"]") == Any["⍂㈴⍂"] # y_string_unicode_2.json
@test jparse("[\"\\uDBFF\\uDFFE\"]") == Any["\U10fffe"] # y_string_unicode_U+10FFFE_nonchar.json
@test jparse("[\"\\uD83F\\uDFFE\"]") == Any["\U1fffe"] # y_string_unicode_U+1FFFE_nonchar.json
@test jparse("[\"\\u200B\"]") == Any["\u200b"] # y_string_unicode_U+200B_ZERO_WIDTH_SPACE.json
@test jparse("[\"\\u2064\"]") == Any["\u2064"] # y_string_unicode_U+2064_invisible_plus.json
@test jparse("[\"\\uFDD0\"]") == Any["\ufdd0"] # y_string_unicode_U+FDD0_nonchar.json
@test jparse("[\"\\uFFFE\"]") == Any["\ufffe"] # y_string_unicode_U+FFFE_nonchar.json
@test jparse("[\"\\u0022\"]") == Any["\""] # y_string_unicode_escaped_double_quote.json
@test jparse("[\"€𝄞\"]") == Any["€𝄞"] # y_string_utf8.json
@test jparse("[\"a\x7fa\"]") == Any["a\x7fa"] # y_string_with_del_character.json
@test jparse("false") == false # y_structure_lonely_false.json
@test jparse("42") == 42 # y_structure_lonely_int.json
@test jparse("-0.1") == -0.1 # y_structure_lonely_negative_real.json
@test jparse("null") == nothing # y_structure_lonely_null.json
@test jparse("\"asd\"") == "asd" # y_structure_lonely_string.json
@test jparse("true") == true # y_structure_lonely_true.json
@test jparse("\"\"") == "" # y_structure_string_empty.json
@test jparse("[\"a\"]\n") == Any["a"] # y_structure_trailing_newline.json
@test jparse("[true]") == Any[true] # y_structure_true_in_array.json
@test jparse(" [] ") == Any[] # y_structure_whitespace_array.json

end
end
end # testset

#-------------------------------------------------------------------------------
@testset "github.com/nst/JSONTestSuite negative" begin
#-------------------------------------------------------------------------------

    jparse(x) = LazyJSON.parse(x; lazy=false)

    d = "JSONTestSuite/test_parsing"

    for f in readdir("JSONTestSuite/test_parsing")
        class = f[1]
        if class == 'n' #&& JSON.enable_assertions
            continue # FIXME
            if f in pending_unescape || f in passing_but_sloooow
                continue
            end
            @test_throws Union{JSON.ParseError,
                               StackOverflowError,
                               InexactError} begin
                r = JSON.parse(String(read("$d/$f")); lazy=false)
            end
        end
    end

end # testset

#-------------------------------------------------------------------------------
@testset "citylots" begin
#-------------------------------------------------------------------------------

json = """{
"type": "FeatureCollection",
"features": [
{ "type": "Feature", "properties": { "MAPBLKLOT": "0001001", "BLKLOT": "0001001", "BLOCK_NUM": "0001", "LOT_NUM": "001", "FROM_ST": "0", "TO_ST": "0", "STREET": "UNKN
OWN", "ST_TYPE": null, "ODD_EVEN": "E" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ -122.422003528252475, 37.808480096967251, 0.0 ], [ -122.42207601332528
1, 37.808835019815085, 0.0 ], [ -122.421102174348633, 37.808803534992904, 0.0 ], [ -122.421062569067274, 37.808601056818148, 0.0 ], [ -122.422003528252475, 37.8084800
96967251, 0.0 ] ] ] } }
,
{ "type": "Feature", "properties": { "MAPBLKLOT": "0002001", "BLKLOT": "0002001", "BLOCK_NUM": "0002", "LOT_NUM": "001", "FROM_ST": "0", "TO_ST": "0", "STREET": "UNKN
OWN", "ST_TYPE": null, "ODD_EVEN": "E" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ -122.42082593937107, 37.808631474146033, 0.0 ], [ -122.420858049679694
, 37.808795641369592, 0.0 ], [ -122.419811958704301, 37.808761809714007, 0.0 ], [ -122.42082593937107, 37.808631474146033, 0.0 ] ] ] } }

]}"""

v = convert(Vector{CityLot}, LazyJSON.value(json, ["features"]))

@test v[1]._type == "Feature"
@test v[1].properties["MAPBLKLOT"] == "0001001"

@test v[2]._type == "Feature"
@test v[2].properties["MAPBLKLOT"] == "0002001"
@test v[2].geometry.coordinates[1][1][1] == -122.42082593937107

end # testset

#-------------------------------------------------------------------------------
@testset "GitHub.jl" begin
#-------------------------------------------------------------------------------

    gist_json = """{
      "id": 1296269,
      "owner": {
        "login": "octocat"
      },
      "parent": {
        "name": "test-parent"
      },
      "full_name": "octocat/Hello-World",
      "private": false,
      "url": "https://api.github.com/repos/octocat/Hello-World",
      "language": null,
      "pushed_at": "2011-01-26T19:06:43Z",
      "permissions": {
        "admin": false,
        "push": false,
        "pull": true
      }
    }"""

v = convert(Repo, LazyJSON.value(gist_json))

@test v.owner.login == "octocat"

s = "XXX $gist_json ~YYY"
s = SubString(s, 5, findfirst(isequal('~'), s) - 2)
@test s == gist_json
@test s isa SubString{String}

v = convert(Repo, LazyJSON.value(s))
@test v.owner.login == "octocat"

end #testset

#=
#-------------------------------------------------------------------------------
@testset "splice" begin
#-------------------------------------------------------------------------------

splice = LazyJSON.splice
value = LazyJSON.value

@test splice("1", [], 7) == "7"
@test splice("\"foo\"", [], "bar") == "\"bar\""
@test splice("[1,2,3]", [3], 4) == "[1,2,4]"
@test splice(" {\"foo\": \"bar\"}", ["foo"], 7) == " {\"foo\": 7}"

@test splice(value("1"), [], 7) == 7
@test splice(value("\"foo\""), [], "bar") == "bar"
@test splice(value("[1,2,3]"), [3], 4) == [1,2,4]
@test splice(value(" {\"foo\": \"bar\"}"), ["foo"], 7) == Dict("foo" => 7)

j = """{
    "id": 1296269,
    "owner": {
        "login": "octocat"
    },
    "parent": {
        "name": "test-parent"
    }
}"""

@test splice(j, ["owner", "login"], "foo") ==
"""{
    "id": 1296269,
    "owner": {
        "login": "foo"
    },
    "parent": {
        "name": "test-parent"
    }
}"""

@test splice(j, ["owner"], "foo") ==
"""{
    "id": 1296269,
    "owner": "foo",
    "parent": {
        "name": "test-parent"
    }
}"""

j = value(j)

@test string(splice(j, ["owner", "login"], "foo")) ==
"""{
    "id": 1296269,
    "owner": {
        "login": "foo"
    },
    "parent": {
        "name": "test-parent"
    }
}"""

a = splice(j, j.owner.login, "foo")
b = splice(j, ["owner", "login"], "foo")

@test a.id == b.id
@test Int(a.id) == Float64(b.id)
@test a.owner.login == b.owner.login
@test a.parent == b.parent
@test a.parent.name == b.parent.name
@test a == b

@test splice(j.owner, j.owner.login, "foo") == Dict("login" => "foo")

@test string(splice(j, j.parent, j.owner)) ==
"""{
    "id": 1296269,
    "owner": {
        "login": "octocat"
    },
    "parent": {
        "login": "octocat"
    }
}"""

@test string(splice(j, j.id, [1,2,3,4,5])) ==
"""{
    "id": [1,2,3,4,5],
    "owner": {
        "login": "octocat"
    },
    "parent": {
        "name": "test-parent"
    }
}"""

end #testset
=#


text:
# # Upgrade to new `|>` of Transducers.jl 0.4.39
#
# Transducers.jl 0.4.39 now interprets `|>` differently.  Consider the
# following examples:

using Transducers
using LiterateTest                                                     #src
using Test                                                             #src
using Logging                                                        # hide

@dedent old1 = with_logger(NullLogger()) do
    collect(Filter(isodd) |> Map(inv), 1:5)
end
@dedent old2 = with_logger(NullLogger()) do
    foldl(+, Filter(isodd) |> Map(inv), 1:5)
end
nothing                                                              # hide

# It is now recommended to write

@test begin
    1:5 |> Filter(isodd) |> Map(inv) |> collect
end == old1
@test begin
    foldl(+, 1:5 |> Filter(isodd) |> Map(inv))
end == old2
nothing                                                              # hide

# The last snippet can also be written as

@test begin
    1:5 |> Filter(isodd) |> Map(inv) |> sum
end == old2
nothing                                                              # hide

# Note that `|>` now is compatible with the standard function
# application definition of `|>` (i.e., `x |> f == f(x)`):

if VERSION >= v"1.3"                                                   #src
    @dedent begin
        @assert 1:5 |> Filter(isodd) |> Map(inv) === Map(inv)(Filter(isodd)(1:5))
    end
end                                                                    #src

# !!! note
#
#     Julia < 1.3 requires `collection |> xf` or `eduction(xf,
#     collection)` instead of `xf(collection)`.

# If there is no input collection; e.g.,

@dedent old3 = with_logger(NullLogger()) do
    xf = Map(last) |> Filter(isodd)
    foldl(right, GroupBy(x -> gcd(x, 6), xf, push!!), 1:10)
end
nothing                                                              # hide

# use the opposite composition `opcompose` instead:

@test begin
    xf = opcompose(Map(last), Filter(isodd))
    foldl(right, GroupBy(x -> gcd(x, 6), xf, push!!), 1:10)
end == old3
nothing                                                              # hide

# In Julia ≥ 1.5,
# [`⨟`](https://github.com/JuliaFunctional/CompositionsBase.jl) can
# also be used as the infix version of the opposite composition
#
# ```julia
# foldl(right, GroupBy(x -> gcd(x, 6), Map(last) ⨟ Filter(isodd), push!!), 1:10)
# ```

# Note that `collection |> xf` and `xf(collection)` create an
# [`eduction(xf, collection)`](@ref eduction) which is iterable.
# However, it is not recommended to use it with non-specialized
# functions.  For example, even though

ys = Int[]
for x in 1:5 |> Filter(isodd)
    push!(ys, x)
end
old4 = ys                                                              #src
nothing                                                              # hide

# works as expected, it is recommended to use

ys = Int[]
foreach(1:5 |> Filter(isodd)) do x
    push!(ys, x)
end
@test old4 == ys
nothing                                                              # hide

# when the performance is important.
#
# Transducers.jl 0.4.39 also adds [`xf'(rf)`](@ref adjoint) as the
# [reducing function transformation](@ref glossary-rfxf).  This makes
# composing reducing functions easier.  For example, it can be used to
# compute even minimum and odd maximum in one go:

rf = TeeRF(Filter(iseven)'(min), Filter(isodd)'(max))
@test begin
    foldxt(rf, Map(identity), 1:10)
end == (2, 9)

# More details can be found in the reference entries such as
# [`Transducer`](@ref), [`eduction`](@ref), [`adjoint`](@ref),
# [`reducingfunction`](@ref) and [`∘`](@ref).  To understand how those
# interfaces work coherently, see [the explanation section on
# "generalized" transducers](@ref glossary-transducer).


text:
module TestStats
	using Base.Test
	using DataArrays

	autocor(DataArray([1, 2, 3, 4, 5]))

	@assert isequal(xtabs([1, 2, 2, 2, 3]), [2 => 3, 3 => 1, 1 => 1])
end