text:
using Statistics

function agent_boundbox(true_pos, width, length, f_vec, r_vec)
    ##
    #Compute bounding box for agent using its dimensions,
    #current position, and angle of rotation
    #Order of points in bounding box:
    #(front)
    #4 - 3
    #|   |
    #1 - 2
    ##

    # halfwidth/length
    hwidth = width / 2
    hlength = length / 2

    # Indexing to make sure we only get the x/z dims
    corners = permutedims(hcat(
        true_pos .- hwidth .* r_vec .- hlength .* f_vec,
        true_pos .+ hwidth .* r_vec .- hlength .* f_vec,
        true_pos .+ hwidth .* r_vec .+ hlength .* f_vec,
        true_pos .- hwidth .* r_vec .+ hlength .* f_vec
    )[[1, 3], :])
end

function tensor_sat_test(norm::Vector{Matrix{Float32}}, corners::Vector{Matrix{Float32}})
    ##
    #Separating Axis Theorem (SAT) extended to >2D.
    #(each input ~ "a list of 2D matrices")
    ##
    dotval = norm .* corners
    mins = minimum.(dotval, dims=2)
    maxs = maximum.(dotval, dims=2)
    return mins, maxs
end

function tensor_sat_test(norm::Matrix{Float32}, corners::Matrix{Float32})
    mins, maxs = tensor_sat_test([norm], [corners])
    return mins[1][:, 1], maxs[1][:, 1]
end

function tensor_sat_test(norm::Matrix{Float32}, corners::Vector{Matrix{Float32}})
    mins, maxs = tensor_sat_test([norm], corners)
    map(x->map(i->i[:, 1], x), (mins, maxs))
end

function tensor_sat_test(norm::Vector{Matrix{Float32}}, corners::Matrix{Float32})
    mins, maxs = tensor_sat_test(norm, [corners])
    map(x->map(i->i[:, 1], x), (mins, maxs))
end

function overlaps(min1, max1, min2, max2)
    ##
    #Helper function to check projection intervals (SAT)
    ##
    return is_between_ordered(min2, min1, max1) || is_between_ordered(min1, min2, max2)
end

function is_between_ordered(val, lowerbound, upperbound)
    ##
    #Helper function to check projection intervals (SAT)
    ##
    return all(lowerbound .≤ val .≤ upperbound)
end

function generate_corners(pos::Vector{Float32}, min_coords::Vector{Float32},
                          max_coords::Vector{Float32}, θ::Float32, scale::Float32)
    ##
    #Generates corners given obj pos, extents, scale, and rotation
    ##
    px = pos[1]
    pz = pos[end]
    return permutedims(hcat(
        rotate_point(min_coords[1] * scale + px, min_coords[end] * scale + pz, px, pz, θ),
        rotate_point(max_coords[1] * scale + px, min_coords[end] * scale + pz, px, pz, θ),
        rotate_point(max_coords[1] * scale + px, max_coords[end] * scale + pz, px, pz, θ),
        rotate_point(min_coords[1] * scale + px, max_coords[end] * scale + pz, px, pz, θ)
    ))
end

function tile_corners(pos::Vector{Int}, width::Float32)
    ##
    #Generates the absolute corner coord for a tile, given grid pos and tile width
    ##
    px = pos[1] - 1f0
    pz = pos[end] - 1f0

    return [
        px - 1f0 pz - 1f0;
        px + 1f0 pz - 1f0;
        px + 1f0 pz + 1f0;
        px - 1f0 pz + 1f0;
    ] * width
end

function generate_norm(corners::Array{Float32, 2})
    ##
    #Generates both (orthogonal, 1 per axis) normal vectors
    #for rectangle given vertices *in a particular order* (see generate_corners)
    ##
    ca = cov(corners, corrected=false)
    # Multiply by -1 and swap colums to match with numpy results
    #vect = -eigen(ca).vectors
    #vect = hcat(vect[:, 2], vect[:, 1])
    vect = eigen(ca).vectors
    return permutedims(vect)
end

function find_candidate_tiles(obj_corners, tile_size)
    ##
    #Finds all of the tiles that a object could intersect with
    #Returns the norms and corners of any of those that are drivable
    ##

    # Find min / max x&y tile coordinates of object
    minx, miny = Int.(floor.(
            minimum(obj_corners, dims=1) / tile_size
    ))

    maxx, maxy = Int.(floor.(
            maximum(obj_corners, dims=1) / tile_size
    ))

    # The max number of tiles we need to check is every possible
    # combination of x and y within the ranges, so enumerate
    xr = collect(minx:maxx)
    yr = collect(miny:maxy)

    possible_tiles = [(x+1, y+1) for x in xr for y in yr]
    return possible_tiles
end

function intersects(duckie::Matrix{Float32}, objs_stacked::Vector{Matrix{Float32}},
                    duckie_norm::Matrix{Float32}, norms_stacked::Vector{Matrix{Float32}})
    ##
    #Helper function for Tensor-based OBB intersection.
    #Variable naming: SAT requires checking of the projection of all normals
    #to all sides, which is where we use tensor_sat_test (gives the mins and maxs)
    #of each projection pair. The variables are named as:
    #{x's norm + projected on + min/max}.
    ##
    duckduck_min, duckduck_max = tensor_sat_test(duckie_norm, permutedims(duckie))
    objduck_min, objduck_max = tensor_sat_test(duckie_norm, objs_stacked)
    duckobj_min, duckobj_max = tensor_sat_test(norms_stacked, permutedims(duckie))
    objobj_min, objobj_max = tensor_sat_test(norms_stacked, objs_stacked)

    # Iterate through each object we are checking against
    for idx in 1:length(objduck_min)
        # If any interval doesn't overlap, immediately know objects don't intersect
        if !overlaps(
                duckduck_min[1], duckduck_max[1], objduck_min[idx][1], objduck_max[idx][1])
            continue
        end
        if !overlaps(
                duckduck_min[2], duckduck_max[2], objduck_min[idx][2], objduck_max[idx][2])
            continue
        end
        if !overlaps(
                duckobj_min[idx][1], duckobj_max[idx][1], objobj_min[idx][1], objobj_max[idx][1])
            continue
        end
        if !overlaps(
                duckobj_min[idx][2], duckobj_max[idx][2], objobj_min[idx][2], objobj_max[idx][2])
            continue
        end
        # All projection intervals overlap, collision with an object
        return true
    end
    return false
end

function intersects_single_obj(duckie, obj, duckie_norm, norm)
    ##
    #Helper function for Single Object OBB intersection.
    #Variable naming: SAT requires checking of the projection of all normals
    #to all sides, which is where we use tensor_sat_test (gives the mins and maxs)
    #of each projection pair. The variables are named as:
    #{x's norm + projected on + min/max}.
    ##
    duckduck_min, duckduck_max = tensor_sat_test(duckie_norm, permutedims(duckie))
    objduck_min, objduck_max = tensor_sat_test(duckie_norm, obj)
    duckobj_min, duckobj_max = tensor_sat_test(norm, permutedims(duckie))
    objobj_min, objobj_max = tensor_sat_test(norm, obj)

    # If any interval doesn't overlap, immediately know objects don't intersect
    if !overlaps(
            duckduck_min[1], duckduck_max[1], objduck_min[1], objduck_max[1])
        return false
    end
    if !overlaps(
            duckduck_min[2], duckduck_max[2], objduck_min[2], objduck_max[2])
        return false
    end
    if !overlaps(
            duckobj_min[1], duckobj_max[1], objobj_min[1], objobj_max[1])
        return false
    end
    if !overlaps(
            duckobj_min[2], duckobj_max[2], objobj_min[2], objobj_max[2])
        return false
    end

    # All projection intervals overlap, collision with an object
    return true
end

function safety_circle_intersection(d::Vector{Float32}, r1::Float32, r2::Vector{Float32})
    #=
    Checks if  two circles with centers separated by d and centered
    at r1 and r2 either intesect or are enveloped (one inside of other)
    =#
    intersect = ((r1 .- r2) .^ 2 .≤ d .^ 2) .& (d .^ 2 .≤ (r1 .+ r2) .^ 2)

    enveloped = d .< abs.(r1 .- r2)

    return any(intersect) || any(enveloped)
end

function safety_circle_overlap(d, r1, r2)
    ##
    #Returns a proxy for area (see issue #24)
    #of two circles with centers separated by d
    #and centered at r1 and r2
    ##
    scores = d .- r1 .- r2
    return sum(scores[findall(s->s < 0, scores)])
end

function calculate_safety_radius(mesh, scale)
    ##
    #Returns a safety radius for an object, and scales
    #it according to the YAML file's scale param for that obj
    ##
    x, _, z = maximum(abs.([mesh.min_coords mesh.max_coords]), dims=2)
    return norm([x, z]) * scale
end

function heading_vec(θ)
    ##
    #Vector pointing in the direction the agent is looking
    ##

    x = cos(θ)
    z = -sin(θ)
    return [x, 0f0, z]
end


text:
# Practical Machine learning
# Association rule based learning - FPGrowth example
# Chapter 7

abstract FPTree

type FPEmptyNode <: FPTree end

type FPTreeNode <: FPTree
    key::Int64 # I thought Generic Types should be used here, but it is much more harder to implement than I expected
    name::Int64
    cnt::Int64
    parent::Int64
    children::Array{Int64}

    function FPTreeNode(k,v)
        node = new(k,v,1,0)
        node.children = Array(Int64,0)
        node
    end

    function FPTreeNode(k,v,p)
        node = new(k,v,1,p)
        node.children = Array(Int64,0)
        node
    end

    function FPTreeNode(k,v,p,c)
        node = new(k,v,1,p)
        if typeof(c) <: Array{Int64}
            node.children = c
        else
            node.children = Array(Int64,0)
        end
        node
    end
end

function haschild(idx,childname,N)
    length(getnode(idx,N).children) < 1 && return false
    for c in getnode(idx,N).children
        getnode(c,N).name == childname && return true
    end
    return false
end

function getchildindex(idx,childname,N)
    for c in getnode(idx,N).children
        getnode(c,N).name == childname && return c
    end
end

haschild(t) = ifelse(length(t.children) < 1,false,true)

function growchild!(idx, childlist::AbstractArray, N::AbstractArray)
    nchild = length(childlist)
    if nchild < 1 return
    else
        child_idx = length(N)
        child_name = childlist[1]
        deleteat!(childlist,1)
        n = FPTreeNode(child_idx, child_name, idx)
        filter!(x -> !isempty(x), getnode(idx,N).children)
        push!(getnode(idx,N).children, child_idx)
        push!(N, n)
    end
    growchild!(child_idx, childlist,N)
end

function climb_grow(idx, childlist, N)
    isempty(childlist) && return
    childname = childlist[1]
    if haschild(idx, childname, N)
        childindex = getchildindex(idx, childname,N)
        getnode(childindex,N).cnt += 1
        deleteat!(childlist,1)
        climb_grow(childindex, childlist, N)
    else growchild!(idx, childlist,N)
    end
end

# Climb down from tree node to root, and record the path
function climb_down!(idx, N, path)
    push!(path, idx)
    idx == 0 && return sort!(path)
    climb_down!(getnode(idx,N).parent, N, path)
end

function remove_node(idx, N)
    _N = Array(FPTree,0)
    for n in N
        n.key == idx && continue
        n.parent == idx && (n.parent = 0) # if parent node is going to be removed, set root(null) node as parent
        if !isempty(n.children)
            _children = Array(Int64, 0)
            for i in 1:length(n.children)
                if n.children[i] != idx
                    push!(_children, n.children[i])
                end
            end
            n.children = _children
        end
        push!(_N, n)
    end
    _N
end

# Get a certain node by its key
function getnode(idx::Int64,N::Array{FPTree})
    for n in N
        if n.key == idx return n
        end
    end
    throw(BoundsError())
end

function gen_tree(T)
    N = Array(FPTree,0)
    # TODO: Sort T
    # Add null node
    n0 = FPTreeNode(0,0)
    push!(N,n0)
    for t in T
        climb_grow(0,t,N)
    end
#     @show N
    N
end

function test()
    T = Array(Array{Int64,1},10)
    T[1] = [1,2]
    T[2] = [2,3,4]
    T[3] = [1,3,4,5]
    T[4] = [1,4,5]
    T[5] = [1,2,3]
    T[6] = [1,2,3,4]
    T[7] = [1]
    T[8] = [1,2,3]
    T[9] = [1,2,4]
    T[10] = [2,3,5]
    N = gen_tree(T)
end

function fp_growth!(N, minsupp_cnt)
    # get itemset
    I = filter(n->n>0,unique(sort([Int64(n.name) for n in N])))
    # get the 1-consequent item. if the item is infrequent, find the preceding frequent item
    last_nodes = []
    while true
        last = pop!(I)
        last_nodes = filter(n->n.name==last && isempty(n.children), N)
        supp = 0
        for n in last_nodes
            supp += n.cnt
        end
        supp >= minsupp_cnt && break
        isempty(I) && error("No item is frequent enough in given transactions.")
    end
    # get path with the 1-consequent
    paths = []
    for l in last_nodes
        path = Array(Int64, 0)
        climb_down!(l.key,N,path)
        isempty(path) || push!(paths, path)
    end
    # prune items not in any path
    I = unique(sort(reduce(vcat,paths)))
    remove_idx = filter(i->!(i in I), map(i->i.key,N))
    for i in remove_idx
        N = remove_node(i,N)
    end
    cond_fp_tree(N, paths, minsupp_cnt)
end

function cond_fp_tree(N, paths, minsupp_cnt)
    last_item = 0
    # update support count on each path
    for n in N # set all count but last to 0
        isempty(n.children) || (n.cnt = 0)
    end
    for path in paths
        sort!(path)
        last_item == 0 && (last_item = getnode(path[end],N).name) # update last_item when not assigned
        for i in length(path)-1:-1:1
            getnode(path[i],N).cnt += getnode(path[i+1],N).cnt
        end
        N = remove_node(path[end],N)# remove the 1-consequent in paths
    end
    # prune the items that nolonger frequent
    item_cnt = Dict{Int64, Int64}()
    for n in N # collect item count
        haskey(item_cnt,n.name) || (item_cnt[n.name] = 0)
        item_cnt[n.name] += n.cnt
    end
    for (k,v) in item_cnt
        v < minsupp_cnt && delete!(item_cnt, k)
    end
    remove_idx = [n.key for n in filter(n->!(n.name in keys(item_cnt)) && n.name != 0,N)]
    for ridx in remove_idx # prune infrequent items
        N = remove_node(ridx,N)
    end
    candidates = []
    paths = []
    leaves = filter(n->isempty(n.children), N)
    isempty(leaves) && return candidates
    for l in leaves
        path = Array(Int64, 0)
        climb_down!(l.key,N,path)
        length(path) >= 2 && push!(paths, path)
    end
    paths
#     last_item
    # Extract frequent candidate
    for path in paths
        length(path) < 2 && continue
        push!(candidates, path[end-1:end])
        pop!(path)
    end

end

N = test()
#fp_growth!(N, 2)

ext: jl


text:
# Note that this script can accept some limited command-line arguments, run
# `julia build_tarballs.jl --help` to see a usage message.
using BinaryBuilder, Pkg

name = "libaio"
version = v"0.3.112"

# Collection of sources required to complete build
sources = [
    GitSource("https://pagure.io/libaio.git", "d025927efa75a0d1b46ca3a5ef331caa2f46ee0e")
]

dependencies = Dependency[]

# Bash recipe for building across all platforms
script = raw"""
cd libaio

make -j${nproc} install prefix=${prefix}
"""

# These are the platforms we will build for by default, unless further
# platforms are passed in on the command line
platforms = filter!(p -> Sys.islinux(p), supported_platforms(;experimental=true))

# The products that we will ensure are always built
products = Product[
    LibraryProduct("libaio", :libaio)
]

# Build the tarballs, and possibly a `build.jl` as well.
build_tarballs(ARGS, name, version, sources, script, platforms, products, dependencies, julia_compat="1.6")

max_stars_repo_name: sharanry/Yggdrasil

max_issues_repo_name: sharanry/Yggdrasil

max_forks_repo_name: sharanry/Yggdrasil


text:
using FileIO
using Printf
include("julia2ims.jl")

"""
20201216: Package Spinning disk tif stack to imaris
"""

src_dir = "/datahub/rawdata/tandeng/mRNA_imaging/mRNA_confocal_again/20201215/sCMOS"
out_dir = "/datahub/rawdata/tandeng/mRNA_imaging/mRNA_confocal_again/20201215"
#src_dir = ARGS[1]
t_len = 42 # 79-120 time point
z_len = 20
pos_len = 40

buffer = zeros(N0f16, 1900, 1300, z_len*t_len*pos_len)
img_num = 866

raw = load(File(format"TIFF", "$src_dir/HE7-1NLS-uw-PWM_1_MMStack_72.ome.tif"))
buffer[:, :, 1:818] = raw[:, :, 49:end] # push 364 slice

Threads.@threads for index in 73:109 # 18 file here, remain 412 slice
    println(index)
    filename = "HE7-1NLS-uw-PWM_1_MMStack_$index.ome.tif"
    raw = load(File(format"TIFF", "$src_dir/$filename"))
	GC.gc()
    id = (index-73)*img_num + 1 + 818
    buffer[:, :, id:id+img_num-1] = raw
end

raw = load(File(format"TIFF", "$src_dir/HE7-1NLS-uw-PWM_1_MMStack_110.ome.tif"))
buffer[:, :, end-740+1:end] = raw[:, :, :] # push 48 slice

buffer = reshape(buffer, (1900, 1300, z_len, t_len*pos_len))
Threads.@threads for pos in 1:pos_len
    imsname = @sprintf("%s/pos%02d-4.tiff", out_dir, pos)
    #save2ims(reinterpret(UInt16, buffer[:, :, :, :, pos]),
    #         imsname, dx=0.108, compression=1)
    save(imsname, reshape(buffer[:, :, :, pos:40:end],
                          (1900, 1300, z_len*t_len)))
end


text:
# Batched Linear Algebra code

"Given 3D CuArrays A and B, fill in X[:,:,k] = A[:,:,k] \\ B[:,:,k]"
function batch_solve!(X::CuArray{FT,3}, A::CuArray{FT,3}, B::CuArray{FT,3}) where {FT}

    # Temporary factorization matrix
    temp = similar(A)

    # LU-factorize A
    pivot, info   = CUBLAS.getrf_strided_batched!(A, true);
    synchronize()

    # Invert LU factorization of A
    getri_strided_batched!(A, temp, pivot);

    # X = inv(A) * B
    NNlib.batched_mul!(X, temp, B)
    synchronize()

end

"Given 3D Julia Arrays A and B, fill in X[:,:,k] = A[:,:,k] \\ B[:,:,k]"
function batch_solve!(X::AbstractArray{FT,3}, A::AbstractArray{FT,3}, B::AbstractArray{FT,3}) where {FT}
    Threads.@threads for i = 1:size(A, 3)
        @views ldiv!(X[:,:,i], qr!(A[:,:,i]), B[:,:,i])
    end
end

"Given 3D CuArray A, fill in X[:,:,k] = A[:,:,k] \\ I"
function batch_inv!(X::CuArray{FT,3}, A::CuArray{FT,3}) where {FT}

    # LU-factorize A
    pivot, info   = CUBLAS.getrf_strided_batched!(A, true);
    synchronize()

    # Invert LU factorization of A
    getri_strided_batched!(A, X, pivot);
    synchronize()

    return nothing
end

"Given 3D Julia Array A, fill in X[:,:,k] = A[:,:,k] \\ I"
function batch_inv!(X::AbstractArray{FT,3}, A::AbstractArray{FT,3}) where {FT}
    Threads.@threads for i = 1:size(A, 3)
        @views X[:,:,i] = A[:,:,i]\I;
    end
end

"Batched matrix multiply (overwrite NNlib definition)"
function batched_mul(A::CuArray{FT,3}, B::CuArray{FT,3}) where {FT}
    CUBLAS.gemm_strided_batched('N', 'N', A, B)
end


text:
using DataFrames: DataFrames

@testset "stats" begin
    idata = load_arviz_data("centered_eight")

    @testset "compare" begin
        idata2 = load_arviz_data("non_centered_eight")
        df = compare(Dict("a" => idata, "b" => idata2))
        @test df isa DataFrames.DataFrame
    end

    @testset "hdi" begin
        rng = Random.MersenneTwister(42)
        x = randn(rng, 100)
        @test hdi(x) == ArviZ.arviz.hdi(x)
    end

    @testset "r2_score" begin
        rng = Random.MersenneTwister(42)
        ytrue = randn(rng, 100)
        ypred = randn(rng, 100)
        df = r2_score(ytrue, ypred)
        @test df isa DataFrames.DataFrame
        @test all(df == ArviZ.todataframes(ArviZ.arviz.r2_score(ytrue, ypred)))
    end

    @testset "loo" begin
        df = loo(idata)
        @test df isa DataFrames.DataFrame
        @test all(df == ArviZ.todataframes(ArviZ.arviz.loo(idata)))
    end

    @testset "waic" begin
        df = waic(idata)
        @test df isa DataFrames.DataFrame
        @test all(df == ArviZ.todataframes(ArviZ.arviz.waic(idata)))
    end

    @testset "loo_pit" begin
        ret = loo_pit(idata; y="obs")
        @test ret == ArviZ.arviz.loo_pit(idata; y="obs")
    end

    @testset "summarystats" begin
        rng = MersenneTwister(42)
        nchains, ndraws = 4, 10
        idata = convert_to_inference_data(
            Dict(
                "a" => randn(rng, nchains, ndraws), "b" => randn(rng, nchains, ndraws, 3, 4)
            ),
        )

        s = summarystats(idata)
        @test s isa DataFrames.DataFrame
        @test string(first(names(summarystats(idata)))) == "variable"
        @test string(first(names(summarystats(idata; fmt="wide")))) == "variable"
        @test :variable in propertynames(summarystats(idata; fmt="wide"))
        @test "a" ∈ s.variable
        @test "b" ∉ s.variable
        @test "b[0, 0]" ∉ s.variable
        @test "b[1, 1]" ∈ s.variable

        s2 = summarystats(idata; fmt="long")
        @test s2 isa DataFrames.DataFrame
        @test string(first(names(s2))) == "statistic"
        @test "mean" ∈ s2.statistic

        s3 = summarystats(idata; fmt="xarray")
        @test s3 isa ArviZ.Dataset
    end

    @testset "ArviZ.summary" begin
        rng = MersenneTwister(42)
        nchains, ndraws = 4, 10
        data = Dict(
            "a" => randn(rng, nchains, ndraws), "b" => randn(rng, nchains, ndraws, 3, 4)
        )

        @test ArviZ.summary(data) isa DataFrames.DataFrame
    end
end


text:
using CoordinateTransformations

@testset "Indexing" begin
    x = GeoArray(rand(5, 5, 5))
    @test length(x[1]) == 1
    @test length(x[1, 2]) == 5
    @test size(x[1:3, 1:3]) == (3, 3, 5)
    @test size(x[1:3, 1:3, 1:3]) == (3, 3, 3)
end

@testset "Concrete" begin
    ga = GeoArray(rand(5, 5))
    @test isconcretetype(typeof(ga))
    @test isconcretetype(typeof(ga.A))
    @test isconcretetype(typeof(ga.f))
    @test isconcretetype(typeof(ga.crs))
end

@testset "Reading rasters" begin
    ga = GeoArrays.read(joinpath(testdatadir, "data/utmsmall.tif"))
    @test bbox(ga) == (min_x = 440720.0, min_y = 3.74532e6, max_x = 446720.0, max_y = 3.75132e6)
    @test bboxes(ga)[1] == (min_x = 440720.0, max_x = 440780.0, min_y = 3.75126e6, max_y = 3.75132e6)
    @test bboxes(ga)[end] == (min_x = 446660.0, max_x = 446720.0, min_y = 3.74532e6, max_y = 3.74538e6)
end

@testset "Coords" begin
    straight = GeoArray(rand(5, 5, 1), AffineMap([1.0 0.0; 0.0 -1.0], [375000.03, 380000.03]), "")
    rot = GeoArray(rand(5, 5, 1), AffineMap([1.0 0.5; 0.1 1.0], [0.0, 0.0]), "")
    @test coords(straight, :x, GeoArrays.Vertex()) == collect(375000.03:1:375005.03)
    @test coords(straight, :y, GeoArrays.Vertex()) == collect(380000.03:-1:379995.03)
    @test_throws ErrorException coords(straight, :z)
    @test_throws ErrorException coords(rot, :x)
    @test_throws ErrorException coords(rot, :y)
end

@testset "GeoArray constructors" begin
    x, y = range(4, stop = 8.0, length = 10), range(0, stop = 1, length = 9)
    ga2 = GeoArray(rand(10, 9), x, y)
    ga2 = GeoArray(rand(10, 9), x, y, "")
    ga3 = GeoArray(rand(10, 9, 8), x, y)
    ga3 = GeoArray(rand(10, 9, 8), x, y, "")
    for i in 1:length(x), j in 1:length(y)
        @test GeoArrays.coords(ga2, [i, j]) ≈ [x[i], y[j]]
    end
    for i in 1:length(x), j in 1:length(y)
        @test GeoArrays.coords(ga3, [i, j]) ≈ [x[i], y[j]]
    end
    x, y = range(4, stop = 8.0, length = 11), range(0, stop = 1, length = 9)
    @test_throws ErrorException GeoArray(rand(10, 9), x, y)
end

@testset "Conversions" begin
    ga = GeoArray(rand(1:32000, 5, 5))
    GeoArrays.write!(joinpath(testdatadir, "test_conversion.tif"), ga)

    ga = GeoArray(rand(Bool, 5, 5))
    @test_throws ErrorException GeoArrays.write!(joinpath(testdatadir, "test_conversion.tif"), ga)
end

@testset "Similar" begin
    ga = GeoArrays.read(joinpath(testdatadir, remotefiles[end-1]))
    gg = ga[250:end-2, 250:end-250]
    @test gg[1, 1] == ga[250, 250]
    @test coords(gg, [1, 1]) == coords(ga, [250, 250])
    GeoArrays.write!("test.tif", gg)
end

@testset "Indexing" begin
    ga = GeoArray(rand(10, 10))
    ga[Float32(1.0), Float32(2.0)]
    i, j = 2, 5
    x, y = coords(ga, (i, j))
    ii, jj = indices(ga, (x, y))
    @test ii == i
    @test jj == j
end


text:
using EVQueues, Plots
lambda=120.0;
mu=1.0;
gamma=0.5;
C=80;

Tfinal=100.0;

@time sim = ev_pf(lambda,mu,gamma,Tfinal,C)
compute_statistics!(sim)
plot(sim.timetrace)
#@time sim2 = ev_llf(lambda,mu,gamma,Tfinal,C)
#compute_statistics!(sim2)

#plot using PyPlot and then save using PGFPlots
# PyPlot.plot(sim.workloads, sim.deadlinesON, "*", label="All")
# PyPlot.plot(sim.workloads[sim.U.==1],sim.deadlinesON[sim.U.==1], "*", label="In service")
# PyPlot.plot(sim.workloads[sim.U.==0],sim.deadlinesON[sim.U.==0], "*", label="Not in service")

#density of workloads
# sW=sort(sim.W[5000:end,2]);
# k=length(sW);
# PyPlot.plot(sW,(1:k)/k,drawstyle="steps")

# rW = sim.W[:,2];
# sW=sort(rW[5000:end]);
# k=length(sW);
# plot(sW,(1:k)/k,drawstyle="steps")

# fig = Axis([
#     Plots.Linear(sim.workloads[sim.U.==1],sim.deadlinesON[sim.U.==1], onlyMarks=true, style="azulcito", legendentry="In service"),
#     Plots.Linear(sim.workloads[sim.U.==0],sim.deadlinesON[sim.U.==0], onlyMarks=true, style="rojito", legendentry="Not in service"),
#     ], legendPos="north east", xlabel=L"\sigma", ylabel=L"\tau")
#
# save("edf.tex",fig,include_preamble=false)

# quiver(sim.workloads[sim.U.==1],sim.deadlinesON[sim.U.==1],-sim.U[sim.U.==1],-ones(size(sim.U[sim.U.==1])),color="red", scale=20, angles="xy")
# quiver(sim.workloads[sim.U.<1],sim.deadlinesON[sim.U.<1],-sim.U[sim.U.<1],-ones(size(sim.U[sim.U.<1])),color="blue", scale=20, angles="xy")
# axis("square")
# grid()
#figure()
#quiver(sim.workloads[sim.U.==0],sim.deadlinesON[sim.U.==0]-sim.workloads[sim.U.==0],-sim.U[sim.U.==0],-ones(size(sim.U[sim.U.==0]))+-sim.U[sim.U.==0],color="red", scale=100, angles="xy")
#quiver(sim.workloads[sim.U.>0],sim.deadlinesON[sim.U.>0]-sim.workloads[sim.U.>0],-sim.U[sim.U.>0],-ones(size(sim.U[sim.U.>0]))+sim.U[sim.U.>0],color="blue", scale=100, angles="xy")

#print(sim)
#
#  figure()
#  h=fit(Histogram,sim.W[:,2])
#  bar(h.edges[1][1:end-1],h.weights)
# #
# k=collect(0:3*lambda/mu);
# p=1.0;
# P=zeros(k,Float64);
# P[1]=p;
#
# for i=2:length(k)
#  p=p*lambda/(min(k[i],C)*mu+k[i]*gamma);
#  P[i]=p;
# end
# P=P/sum(P);
# stem(k,P)

#plot(sim.W[:,1],sim.W[:,2],"o")
#plot(sim2.W[:,1],sim2.W[:,2],"or")
#figure()
#plot3D(sim.W[:,1],sim.W[:,2],sim.W[:,3],"or")
#plot3D(sim.W[:,1],sim.W[:,3]-sim.W[:,1],sim.W[:,2],"or")


text:
@testset "561.array-partition-i.jl" begin
    @test array_pair_sum([26, 26, 21, 28, -24, -11, 26, 19, -10, -22, -22, -29, 28, -11, -1,
                          -10, -23, 7, 16, 7, 0, 1, 16, 14, 22, 9, 29, -23, 21, -20, -10,
                          21, -23, 21, 18, 2, -26, 6, 19, 8, 11, -29, 9, -13, -11, -23, -24,
                          13, -21, -21, 9, -25, 8, -5, 17, -25, -17, 28, -12, -27, -1, -7,
                          1, -26, -28, -11, 29, -28, 2, 1, 4, -21, 23, 0, 18, -23, 18, 23,
                          3, -10, 12, 4, 28, 29, -27, -28, 23, -27, -16, 13]) == -33
    @test array_pair_sum([1, 4, 3, 2]) == 4
    @test array_pair_sum([6, 2, 6, 5, 1, 2]) == 9
end


text:
# Starting example file demonstrating exceptions for Learning Julia

# Exceptions provide a way for a program to handle one or more
# unexpected conditions

arg = -9

# the try / catch / finally construct is used to work with exceptions
try
    x = sqrt(arg)
    println(x)
catch exception
    println(exception)
finally
    println("This section of code always runs")
end

max_stars_repo_name: scaotravis/Julia-Course

max_issues_repo_name: scaotravis/Julia-Course

max_forks_repo_name: scaotravis/Julia-Course


text:
using .Constants
using .LocaleIdTranslations
using .LC

export LocaleId, Locales, default_locale, locale_id, locale, set_locale!

import Base: ==, hash

"""

    LocaleId(languagetag::String))
    LocaleId(lang, region)
    LocaleId(lang, script, region)
    LocaleId(lang, script, region, variant)
    LocaleId("") -> DEFAULT
    LocaleId() -> BOTTOM

Return `LocaleId` object from cache or create new one and register in cache.
"""
LocaleId() = BOTTOM
LocaleId(langtag::AS) = langtag == "" ? DEFAULT : create_locid(splitlangtag(langtag)...)
LocaleId(lang::AS, region::AS) = create_locid(lang, EMPTYV, "", region, EMPTYV, nothing)
LocaleId(lang::AS, script::AS, region::AS) = create_locid(lang, EMPTYV, script, region, EMPTYV, nothing)
LocaleId(lang::AS, script::AS, region::AS, variant::AS) = create_locid(lang, EMPTYV, script, region, [variant], nothing)

# utilities

# create instance and register in global cache.
function create_locid(language::AS, extlang::Vector{String}, script::AS, region::AS, variant::Vector{String}, extension::Union{ExtensionDict,Nothing})

    lang = check_language(language, extlang)
    scri = check_script(titlecase(script))
    regi = check_region(uppercase(region))
    vari = check_variant(variant)
    if lang == S0
        lex = extension == nothing ? 0 : length(extension)
        if !(scri == S0 && regi == S0 && length(vari) == 0 &&
             (lex == 1 && first(keys(extension)) == 'x' || lex == 0 ) )
            throw(ArgumentError("missing language prefix"))
        end
    end
    key = tuple(lang, scri, regi, vari, extension)
    try
        lock(CACHE_LOCK)
        get!(CACHE, key) do
            LocaleId(key...)
        end
    finally
        unlock(CACHE_LOCK)
    end
end
function check_language(x::AS, extlang::Vector{String})
    is_language(x) || length(x) == 0 || throw(ArgumentError("no language prefix '$x'"))
    x = get(OLD_TO_NEW_LANG, x, x)
    len = length(extlang)
    if length(x) <= 3
        len <= 1 || throw(ArgumentError("only one language extension allowed '$x$SEP2$(join(extlang, SEP2))'"))
        if len >= 1
            x = extlang[1]
        end
        if length(x) == 3
            x = LANGUAGE3_DICT[x] # replace 3-char code by preferred 2-char code
        end
    else
        len == 0 || throw(ArgumentError("no language exensions allowed '$x$SEP2$(join(extlang, SEP2))'"))
    end
    Symbol(x)
end

function is_language(x::AS)
    len = length(x)
    (2 <= len <= 8 && is_alpha(x)) || len == 1 && x == "C"
end

function is_langext(x::AS)
    len = length(x)
    len == 3 && is_alpha(x)
end

function check_script(x::AS)
    is_script(x) || length(x) == 0 || throw(ArgumentError("no script '$x'"))
    Symbol(x)
end

function is_script(x::AS)
    len = length(x)
    len == 4 && is_alpha(x)
end

function check_region(x::AS)
    is_region(x) || length(x) == 0 || throw(ArgumentError("no region '$x'"))
    Symbol(x)
end

function is_region(x::AS)
    len = length(x)
    ( len == 2 && is_alpha(x) ) || ( len == 3 && is_digit(x) )
end

function check_variant(x::Vector{String})
    all(is_variant, x) || throw(ArgumentError("no variants '$(join(x, SEP2))'"))
    Symbol.(x)
end

function is_variant(x::AS)
    len = length(x)
    is_alnum(x) && ( ( 4 <= len <= 8 && isdigit(x[1]) ) || ( 5 <= len <= 8 ))
end

function is_single(x::AS)
    length(x) == 1 && is_alpha(x)
end

"""

Parse language tag and convert to Symbols and collections of Symbols.
"""
function splitlangtag(x::AS)
    is_alnumsep(x) || throw(ArgumentError("language tag contains invalid characters: '$x'"))
    x = cloc_to_loc(x) # handle and replace '.' and '@'.
    x = replace(x, SEP => SEP2) # normalize input
    x = get(GRANDFATHERED, x, x) # replace some old-fashioned language tags
    token = split(x, SEP2, keepempty=true)
    lang = ""
    langex = String[]
    scri = ""
    regi = ""
    vari = String[]
    exte = nothing
    langlen = 0
    k = 1
    n = length(token)
    if k <= n && is_language(token[k])
        lang = token[k]
        langlen = length(lang)
        k += 1
    end
    while k <= n && 2 <= langlen <= 3 && is_langext(token[k])
        push!(langex, token[k])
        k += 1
    end
    if k <= n && is_script(token[k])
        scri = token[k]
        k += 1
    end
    while k <= n && is_region(token[k])
        regi = token[k]
        k += 1
    end
    while k <= n && is_variant(token[k])
        push!(vari, token[k])
        k += 1
    end
    while k <= n && is_single(token[k])
        sing = token[k][1]
        if exte == nothing
            exte = ExtensionDict()
        end
        if haskey(exte, sing)
            throw(ArgumentError("multiple occurrence of singleton '$sing'"))
        end
        m = sing == 'x' ? 1 : 2
        k += 1
        ext = Symbol[]
        while k <= n && m <= length(token[k]) <= 8
            push!(ext, Symbol(token[k]))
            k += 1
        end
        exte[sing] = ext
    end

    k > n || x == "" || throw(ArgumentError("no language tag: '$x' after $(k-1)"))
    length(langex) <= 3 || throw(ArgumentError("too many language extensions '$x'"))

    lang, langex, scri, regi, vari, exte
end

# character properties for all characters in string
is_alpha(x::AS) = all(isletter, x)
is_digit(x::AS) = all(isdigit, x)
is_alnum(x::AS) = all(is_alnum, x)
is_alnumsep(x::AS) = all(c->isascii(c) && ( is_alnum(c) || c in "-_.@" ), x)

# equality
function ==(x::LocaleId, y::LocaleId)
    x === y && return true
    x.language == y.language &&
    x.script == y.script &&
    x.region == y.region &&
    x.variants == y.variants &&
    x.extensions == y.extensions
end

flat(lang::Symbol) = lang == :C ? S0 : lang

function hash(x::LocaleId, h::UInt)
    hash(x.extensions, hash(x.variants, hash(x.region, hash(x.script, hash(x.language, h)))))
end

function Base.issubset(x::LocaleId, y::LocaleId)
    ( x == y || x == BOTTOM || y == ROOT ) && return true
    y == BOTTOM && return false
    issublang(x.language, y.language) &&
    issubscript(x.script, y.script) &&
    issubregion(x.region, y.region) &&
    issubvar(x.variants, y.variants) &&
    issubext(x.extensions, y.extensions)
end

issublang(x::Symbol, y::Symbol) = startswith(string(x), string(y))
issubscript(x::Symbol, y::Symbol) = startswith(string(x), string(y))
issubregion(x::Symbol, y::Symbol) = startswith(string(x), string(y))
issubvar(x::Vector{Symbol}, y::Vector{Symbol}) = issubset(y, x)
function issubext(x::ExtensionDict, y::ExtensionDict)
    ky = keys(y)
    issubset(ky, keys(x)) &&
    all(k-> issubset(y[k], x[k]), ky)
end
issubext(x::Nothing, y::ExtensionDict) = false
issubext(x, y::Nothing) = true

Base.isless(x::LocaleId, y::LocaleId) = issubset(x, y) || (!issubset(y,x) && islexless(x, y))
islexless(x::LocaleId, y::LocaleId) = string(x) < string(y)

"""
    less_specific(loc::LocaleId)
Give the next less specific locale id. If loc = ROOT, return ROOT.
"""
function less_specific(loc::LocaleId)
    loc == ROOT && return ROOT
    if loc.extensions != nothing && !isempty(loc.extensions) > 0
        LocaleId(loc.language, loc.script, loc.region, loc.variants, nothing)
    elseif length(loc.variants) != 0
        LocaleId(loc.language, loc.script, loc.region, Symbol[], nothing)
    elseif loc.region != S0
        LocaleId(loc.language, loc.script, S0, Symbol[], nothing)
    elseif loc.script != S0
        LocaleId(loc.language, S0, S0, Symbol[], nothing)
    else
        ROOT
    end
end

function Base.show(io2::IO, x::LocaleId)
    ES = Symbol("")
    sep = ""
    io = IOBuffer()
    x.language !== ES && ( print(io, x.language); sep = SEP2 )
    x.script != ES &&  ( print(io, sep, x.script); sep = SEP2 )
    x.region != ES && ( print(io, sep, x.region); sep = SEP2 )
    for v in x.variants
        v != ES && ( print(io, sep, v); sep = SEP2 )
    end
    ltx(a::Char, b::Char) = ( a != 'x' && a < b ) || b == 'x'
    if x.extensions != nothing
        for k in sort(collect(keys(x.extensions)), lt=ltx)
            print(io, sep, k); sep = SEP2
            for v in x.extensions[k]
                print(io, sep, v)
            end
        end
    end
    out = String(take!(io))
    print(io2, out)
end

const CACHE = Dict{Key, LocaleId}()
const CACHE_LOCK = ReentrantLock()

"""

    locale_id([gloc::Locale, ]category)

Determine current locale id for given category as stored in locale variable.
If gloc is not given, use task specific locale variable.
Throw exception, if no valid category name.
Valid categories are
:CTYPE, :COLLATE, :MESSAGES, :MONETARY, :NUMERIC, :TIME
"""
locale_id(cat::Category) = locale().locids[cat.id+1]
locale_id(gloc::Locale, cat::Category) = gloc.locids[cat.id+1]

"""

    set_locale!([gloc::Locale, ]locale::LocaleId[, category::CategorySet])

Set contents of locale in selected categories.
Missing category or :ALL sets all defined categories to the same locale.
If `gloc` is not given, the current task-specific locale is used.
Throw exception if category is not :ALL or one of the supported categories of `locale`.
"""
set_locale!(loc::LocaleId, cats::CategorySet = LC.ALL) = set_locale!(locale(), loc, cats)

function set_locale!(gloc::Locale, loc::LocaleId, cats::CategorySet = LC.ALL)
    cld = gloc.locids
    cloc = _newlocale(cats, loc, gloc.cloc)
    if cloc != CLocales.CL0 || gloc.cloc == CLocales.CL0
        gloc.cloc = cloc
        for cat in cats
            lloc = loc == DEFAULT ? default_locale(cat) : loc
            cld[cat.id+1] = lloc
        end
    end
    cloc != CLocales.CL0 || gloc.cloc == CLocales.CL0
end

function _newlocale(cats::CategorySet, loc::LocaleId, base::CLocaleType)
    cloc = CLocales.newlocale(cats, loc, base)
    (cloc != CLocales.CL0 || loc == ResourceBundles.ROOT) && return cloc
    _newlocale(cats, less_specific(loc), base)
end

"""
    default_locale(category)

Determine default locale from posix environment variables:

LANG default if specific category not defined
LC_* specific category
LC_ALL  overides all other settings

* may be one of
MESSAGES    message catalogs

NUMERIC     number formats
MONETARY    format of monetary values
TIME        date/time formats
"""
function default_locale(category::Category)
    LocaleId(localeid_from_env(category))
end

"""

    localeid_from_env(category)

Read posix environment variable for category.
"""
function localeid_from_env(category)
    s = uppercase(string(category))
    if !startswith(s, "LC_")
        s = s == "LANG" ? s : "LC_" * s
    end
    if s == "LC_ALL"
        get(ENV, s, "")
    else
        get2("LC_ALL") do
            get2(s) do
                get(ENV, "LANG", "C")
            end
        end
    end
end

# treat empty value
function get2(f::Function, k::Any)
    v = get(ENV, k, "")
    v == "" ? f() : v
end

"""
    Locale()

Create and initialize a new `Locale` object.
"""
function Locale()
    gloc = Locale(Ptr{Nothing}(0))
    for cat in LC.ALL_CATS
        set_locale!(gloc, default_locale(cat), cat)
    end
    gloc
end

"""
    locale()

Return task specific locale object.
Create and initialize from environment at first access within a task.
"""
function locale()
    tld = task_local_storage()
    if !haskey(tld, :CURRENT_LOCALES)
        gloc = Locale() # create and fill with default values from ENV
        finalizer(finalize_gloc, gloc)
        task_local_storage(:CURRENT_LOCALES, gloc)
    else
        task_local_storage(:CURRENT_LOCALES)
    end
end

# finalizer required to free the associated clib object.
function finalize_gloc(gloc::Locale)
    if gloc.cloc != Ptr{Nothing}(0)
        CLocales.freelocale(gloc.cloc)
    end
end

"""

    DEFAULT

Useful constant for the default locale identifier. It is used to indicate,
that the actual value for concrete locale category (different form :ALL) has to
be determined from the global environment variables `LC_...` and `LANG`.
"""
const DEFAULT = LocaleId("", "")
"""

    ROOT

Useful constant for the root locale.  The root locale is the locale whose
language is "C", country, and variant are empty ("") strings.  This is regarded
as the base locale of all locales, and is used as the language/country
neutral locale for the locale sensitive operations.
"""
const ROOT = LocaleId("C", "")

const BOTTOM = LocaleId(:Bot, S0, S0, EMPTY_VECTOR, nothing)

"""
    Provide a set of commonly used LocaleId with language- and country names
    in uppercase. e.g. `FRENCH`, `UK`. See also `names(Locales)`.
"""
module Locales

    import ResourceBundles: LocaleId, ROOT, DEFAULT, BOTTOM

    export ROOT, DEFAULT, BOTTOM
    export ENGLISH, FRENCH, GERMAN, ITALIAN, JAPANESE, KOREAN, CHINESE,
        SIMPLIFIED_CHINESE, TRADITIONAL_CHINESE
    export FRANCE, GERMANY, ITALY, JAPAN, KOREA, CHINA, TAIWAN, PRC, UK, US, CANADA

    # Languages
    const ENGLISH = LocaleId("en", "")
    const FRENCH = LocaleId("fr", "")
    const GERMAN = LocaleId("de", "")
    const ITALIAN = LocaleId("it", "")
    const JAPANESE = LocaleId("ja", "")
    const KOREAN = LocaleId("ko", "")
    const CHINESE = LocaleId("zh", "")
    const SIMPLIFIED_CHINESE = LocaleId("zh", "CN")
    const TRADITIONAL_CHINESE = LocaleId("zh", "TW")

    # Countries
    const FRANCE = LocaleId("fr", "FR")
    const GERMANY = LocaleId("de", "DE")
    const ITALY = LocaleId("it", "IT")
    const JAPAN = LocaleId("ja", "JP")
    const KOREA = LocaleId("ko", "KR")
    const PRC = SIMPLIFIED_CHINESE
    const CHINA = PRC
    const TAIWAN = TRADITIONAL_CHINESE
    const UK = LocaleId("en", "GB")
    const US = LocaleId("en", "US")
    const CANADA = LocaleId("en", "CA")

end # module LocaleTag


text:
function get_possible_planar_indices(ex)
    if !TO.istensorexpr(ex)
        return [[]]
    elseif TO.isgeneraltensor(ex)
        _,leftind,rightind = TO.decomposegeneraltensor(ex)
        ind = planar_unique2(vcat(leftind, reverse(rightind)))
        return length(ind) == length(unique(ind)) ? Any[ind] : Any[]
    elseif ex.head == :call && (ex.args[1] == :+ || ex.args[1] == :-)
        inds = get_possible_planar_indices(ex.args[2])
        keep = fill(true, length(inds))
        for i = 3:length(ex.args)
            inds′ = get_possible_planar_indices(ex.args[i])
            keepᵢ = fill(false, length(inds))
            for (j, ind) in enumerate(inds), ind′ in inds′
                if iscyclicpermutation(ind′, ind)
                    keepᵢ[j] = true
                end
            end
            keep .&= keepᵢ
            any(keep) || break # give up early if keep is all false
        end
        return inds[keep]
    elseif ex.head == :call && ex.args[1] == :*
        @assert length(ex.args) == 3
        inds1 = get_possible_planar_indices(ex.args[2])
        inds2 = get_possible_planar_indices(ex.args[3])
        inds = Any[]
        for ind1 in inds1, ind2 in inds2
            for (oind1, oind2, cind1, cind2) in possible_planar_complements(ind1, ind2)
                push!(inds, vcat(oind1, oind2))
            end
        end
        return inds
    else
        return Any[]
    end
end

# remove double indices (trace indices) from cyclic set
function planar_unique2(allind)
    oind = collect(allind)
    removing = true
    while removing
        removing = false
        i = 1
        while i <= length(oind) && length(oind) > 1
            j = mod1(i+1, length(oind))
            if oind[i] == oind[j]
                deleteat!(oind, i)
                deleteat!(oind, mod1(i, length(oind)))
                removing = true
            else
                i += 1
            end
        end
    end
    return oind
end

# remove intersection (contraction indices) from two cyclic sets
function possible_planar_complements(ind1, ind2)
    # quick return path
    (isempty(ind1) || isempty(ind2)) && return Any[(ind1, ind2, Any[], Any[])]
    # general case:
    j1 = findfirst(in(ind2), ind1)
    if j1 === nothing # disconnected diagrams, can be made planar in various ways
        return Any[(circshift(ind1, i-1), circshift(ind2, j-1), Any[], Any[])
                    for i ∈ eachindex(ind1), j ∈ eachindex(ind2)]
    else # genuine contraction
        N1, N2 = length(ind1), length(ind2)
        j2 = findfirst(==(ind1[j1]), ind2)
        jmax1 = j1
        jmin2 = j2
        while jmax1 < N1 && ind1[jmax1+1] == ind2[mod1(jmin2-1, N2)]
            jmax1 += 1
            jmin2 -= 1
        end
        jmin1 = j1
        jmax2 = j2
        if j1 == 1 && jmax1 < N1
            while ind1[mod1(jmin1-1, N1)] == ind2[mod1(jmax2 + 1, N2)]
                jmin1 -= 1
                jmax2 += 1
            end
        end
        if jmax2 > N2
            jmax2 -= N2
            jmin2 -= N2
        end
        indo1 = jmin1 < 1 ? ind1[(jmax1+1):mod1(jmin1-1, N1)] :
                    vcat(ind1[(jmax1+1):N1], ind1[1:(jmin1-1)])
        cind1 = jmin1 < 1 ? vcat(ind1[mod1(jmin1, N1):N1], ind1[1:jmax1]) : ind1[jmin1:jmax1]
        indo2 = jmin2 < 1 ? ind2[(jmax2+1):mod1(jmin2-1, N2)] :
                    vcat(ind2[(jmax2+1):N2], ind2[1:(jmin2-1)])
        cind2 = reverse(cind1)
        return isempty(intersect(indo1, indo2)) ? Any[(indo1, indo2, cind1, cind2)] : Any[]
    end
end


text:
function aggDiscreteReturns(returns)
        n = size(returns,1)
        p = 1.0
        @inbounds @avx for i ∈ 1:n
            p = p * (returns[i] + 1.0)
        end
        return(p-1.0)
end

function geo_mean(returns::DataFrame;
                  dateColumn="date")

        vars = names(returns)
        nVars = length(vars)
        vars = Symbol.(vars[vars.!=dateColumn])
        if nVars == length(vars)
          throw(ArgumentError(string("dateColumn: ", dateColumn, " not in DataFrame: ",vars)))
        end
        nVars = nVars-1
        dc = Symbol(dateColumn)

        n = size(returns,1)

        out = DataFrame(:__temp => 1.0)
        for i in 1:nVars
                out[!,vars[i]] .= (1.0+aggDiscreteReturns(returns[!,vars[i]]))^(1/n) - 1.0
        end
        return(out[!,vars])

end

function standard_deviation(returns::DataFrame; scale::Int=1,
                            dateColumn="date",
                            annualized::Bool = false,
                            )

        vars = names(returns)
        nVars = length(vars)
        vars = Symbol.(vars[vars.!=dateColumn])
        if nVars == length(vars)
            throw(ArgumentError(string("dateColumn: ", dateColumn, " not in DataFrame: ",vars)))
        end
        nVars = nVars-1

        out = DataFrame(:_stat_=>"Standard Deviation")

        if annualized
        #   TODO: Test if Threads.@treads is faster for a large number of variables...
                s = convert(Float64,scale)
                for i in 1:nVars
                        out[!,vars[i]] .= std(returns[!,vars[i]]) * sqrt(s)
                end
        else
                for i in 1:nVars
                    out[!,vars[i]] .= std(returns[!,vars[i]])
                end
        end

        return(out)
end


text:
using SpikingNetworks
@unit
parseParameters"""
τ = 20*ms
N= 100
a= [Float64(0.05+0.7*i/N) for i=1:N]
b = 1.2
freq = 10*Hz"""
parseEquations"""
dv/dt=(-v+Iₑ(t))/τ
Iₑ(t)=a*sin(2π*freq*t)+b"""
net=init"""
N=N
v=rand(N)"""
spike"v.>1."
reset"v[i]=0."
stateMonitor"[50]"
net.dt=0.1
run!(net,1000/net.dt)

using MatlabPlot
mplot(net.vRecord)
t,neuron=rasterPlot(net)
mplot(t,neuron,".k")


text:
using DataStructures, Primes

const Split = Vector
const SplitTree = Dict{T, Vector{Split{T}}} where T

function splittree(n::S) where S
    st = SplitTree{S}()
    stack = [n]
    while !isempty(stack)
        m = pop!(stack)
        st[m] = Vector{Split{S}}()
        for xs in split(m)
            if xs in st[m]
                continue
            end
            push!(st[m], xs)
            for x in xs
                if !haskey(st, x)
                    push!(stack, x)
                end
            end
        end
    end
    st
end

shortcuts(ss::Vector{T}) where T = convert(Vector{T}, filter(s -> any(t -> isbelow(s, t), ss), ss))

function product(components::Vector{Vector{Vector{T}}}) where T
    M = length(components)
    groups = Vector{T}[]
    idx = fill(1, M)
    max = length.(components)
    N = prod(max)
    i = 1
    while i <= N
        a = map(getindex, components, idx)
        push!(groups, vcat(a...))
        for j in 1:M
            if idx[j] < max[j]
                idx[j] += 1
                for k in 1:j-1
                    idx[k] = 1
                end
                break
            end
        end
        i += 1
    end
    groups
end

function assembly(st::SplitTree{S}, ss::Vector{S}, sc::Vector{S}; limit=typemax(Int)) where S
    Q = Queue{Tuple{Vector{S}, Vector{S}, Int}}()
    enqueue!(Q, (ss, sc, length(ss)))
    while !isempty(Q)
        (ss, sc, cc) = dequeue!(Q) :: Tuple{Vector{S}, Vector{S}, Int}
        if cc ≥ limit
            continue
        end
        for objects in product([st[s] for s in ss])
            filter!(!isbasic, objects)
            setdiff!(objects, sc)
            if isempty(objects)
                limit = min(limit, cc)
                break
            elseif cc + length(objects) < limit
                scs = shortcuts(objects)
                union!(scs, sc)
                enqueue!(Q, (objects, scs, cc + length(objects)))
            end
        end
    end
    limit
end

function assembly(s::S...; limit=typemax(Int)) where S
    if (all(isbasic, s))
        return 0
    end
    st = merge(SplitTree{S}(), splittree.(s)...)
    ss = collect(s)
    sc = shortcuts(ss)
    setdiff!(ss, sc)
    assembly(st, ss, sc; limit)
end

function project(ϕ, st::SplitTree)
    T = typeof(ϕ(first(keys(st))))

    ϕ̂(x) = sort(map(ϕ, x))
    tree = SplitTree{T}()
    for (node, leaves) in st
        new_node = ϕ(node)
        new_leaves = unique!(map(ϕ̂, leaves))
        if haskey(tree, new_node)
            union!(tree[new_node], new_leaves)
        else
            tree[new_node] = new_leaves
        end
    end
    tree
end
project(T, ϕ) = st -> project(T, ϕ, st)

function assembly(ϕ::Function, s::S...; limit=typemax(Int)) where S
    st = merge(SplitTree{S}(), splittree.(s)...)
    ss = collect(s)
    sc = shortcuts(ss)::Vector{S}

    ssp = unique!(map(ϕ, ss))
    scp = convert(typeof(ssp), unique!(map(ϕ, sc)))

    setdiff!(ssp, scp)
    assembly(project(ϕ, st), ssp, scp; limit)
end

function split(str::S) where {S <: AbstractString}
    N = length(str) - 1
    xs = Array{Split{S}}(undef, N)
    for i in 1:N
        xs[i] = [str[1:i], str[i+1:end]]
    end
    xs
end

isbelow(s::S, t::S) where {S <: AbstractString} = length(s) != length(t) && !isnothing(findfirst(s, t))
isbasic(s::AbstractString) = length(s) ≤ 1

function formula(s::AbstractString; chars=sort(unique(collect(s))))
    d = Dict(c => 0 for c in chars)
    merge!(d, counter(collect(s)))
    last.(sort(collect(d); by=first))
end

function split(n::Int)
    xs = Array{Split{Int}}(undef, n ÷ 2)
    for i in eachindex(xs)
        xs[i] = [i, n-i]
    end
    xs
end

isbelow(n::Int, m::Int) = n < m
isbasic(n::Int) = n == 1

limit(n::Int) = sum(digits(n; base=2)) + floor(Int, log2(n)) - 1

assembly(n::Int; limit=limit(n)) = assembly(splittree(n), [n], Int[]; limit)

function split(v::AbstractVector{Int})
    a = fill(0, length(v))
    a[1] = min(1, v[1])
    b = v .- a

    M = length(v)

    xs = Vector{Vector{Int}}[]
    i = 1
    while any(a .< v)
        if any(a .!= 0)
            x = (a < b) ? [a, b] : [b, a]
            push!(xs, deepcopy(x))
        end
        for j in 1:M
            if a[j] < v[j]
                a[j] += 1
                b[j] -= 1
                for k in 1:j-1
                    a[k] = 0
                    b[k] = v[k]
                end
                break
            end
        end
    end
    xs
end

isbelow(v::V, w::V) where {V <: AbstractVector} = v != w && all(v .≤ w)
isbasic(v::AbstractVector{Int}) = all(v .≥ 0) && sum(v) == 1

struct Mult{T <: Integer}
    x::T
end

function split(a::Mult{T}) where T
    xs = Split{Mult{T}}[]
    fs = factor(a.x).pe
    ps = first.(fs)
    ns = last.(fs)
    map(split(ns)) do sp
        a, b = sp
        Mult{T}.([prod(ps .^ a),  prod(ps .^ b)])
    end
end

isbelow(a::Mult, b::Mult) = a.x != b.x && b.x % a.x == 0
isbasic(a::Mult) = isprime(a.x)
Base.isless(a::Mult, b::Mult) = isless(a.x, b.x)

struct AddMult{T <: Integer}
    x::T
end

Base.convert(::Type{Mult}, a::AddMult) = Mult(a.x)
Base.convert(::Type{Int}, a::AddMult) = a.x
Base.convert(::Type{AddMult}, a::Mult) = AddMult(a.x)
Base.convert(::Type{AddMult}, a::Int) = AddMult(a)

function split(a::AddMult{T}) where T
    xs = Split{AddMult{T}}[]
    if !isone(a.x)
        for (x,y) in [split(Mult(a.x)); split(a.x)]
            push!(xs, [convert(AddMult, x), convert(AddMult, y)])
        end
    else
        for (x,y) in split(a.x)
            push!(xs, [convert(AddMult, x), convert(AddMult, y)])
        end
    end
    xs
end

isbelow(a::AddMult, b::AddMult) = isbelow(a.x, b.x)
isbasic(a::AddMult) = isone(a.x)
Base.isless(a::AddMult, b::AddMult) = isless(a.x, b.x)


text:
using Pkg;Pkg.activate(@__DIR__)
using Comrade
using PyCall
using Plots

using GalacticOptim, Optim
using Zygote
using Parameters
using Distributions
using SpeedMapping
using AdvancedHMC
using Dynesty

load_ehtim()
@pyimport eht_dmc as ed

# To download the data visit https://doi.org/10.25739/g85n-f134
obs = ehtim.obsdata.load_uvfits(joinpath(@__DIR__, "SR1_M87_2017_096_hi_hops_netcal_StokesI.uvfits"))
obs.add_scans()

obsavg = obs.avg_coherent(0.0, scan_avg=true)

img = ehtim.image.make_empty(512, μas2rad(250.0), obs.ra, obs.dec, obs.rf, obs.source)
img = img.add_gauss(1.0, [μas2rad(40.0), μas2rad(30.0), π/3, 0.0, 0.0])

obslist = obsavg.split_obs()

gainoff = 0.0
gainp = Dict("AA"=> 0.01,
             "AP" => 0.1,
             "AZ" => 0.1,
             "JC" => 0.1,
             "LM" => 0.2,
             "PV" => 0.1,
             "SM" => 0.1,
             "SR" => 0.1)
obsim = img.observe_same(ehtim.obsdata.merge_obs(obslist[10:15]), ttype="fast",  gainp=gainp, gain_offset=gainoff, ampcal=false, phasecal=false, stabilize_scan_phase=true, stabilize_scan_amp=true)
# now get cal table
ctable = ehtim.calibrating.self_cal.self_cal(obsim, img, caltable=true)
ehtim.caltable.save_caltable(ctable, obsim, datadir=joinpath(@__DIR__ ,"CaltableTest"))

dvis = extract_vis(obsim)
dlcamp = extract_lcamp(obsim; count="min")
dcphase = extract_cphase(obsim, count="min-cut0bl")
damp = extract_amp(obsim)
st = scantable(dvis)

gcache = Comrade.GainCache(st)

struct Model{G}
    gcache::G
end

function Model(st::Comrade.ScanTable)
    gcache = Comrade.GainCache(st)
    return Model{typeof(gcache)}(gcache)
end

function (mod::Model)(θ)
    @unpack f, σ, τ, ξ,  gamp, gphase = θ
    g = gamp.*cis.(gphase)
    m = f*rotated(stretched(Gaussian(), σ*τ, σ), ξ)
    Comrade.GainModel(mod.gcache, g, m)
end

# define the priors
distamp = (AA = LogNormal(0.0, 0.1),
           AP = LogNormal(0.0, 0.1),
           LM = LogNormal(0.0, 0.2),
           AZ = LogNormal(0.0, 0.1),
           JC = LogNormal(0.0, 0.1),
           PV = LogNormal(0.0, 0.1),
           #SM = LogNormal(0.0, 0.1)
         )
distphase = (AA = Normal(0.0, 1e-4),
             AP = Normal(0.0, π),
             LM = Normal(0.0, π),
             AZ = Normal(0.0, 1.0*π),
             JC = Normal(0.0, 1.0*π),
             PV = Normal(0.0, π),
             #SM = Normal(0.0, 1.0*π),
             )
prior = (
          f = Uniform(0.9, 1.1),
          σ = Uniform(μas2rad(10.0), μas2rad(30.0)),
          τ = Uniform(0.1, 1.0),
          ξ = Uniform(-π/2, π/2),
          gamp = Comrade.GainPrior(distamp, st),
          gphase = Comrade.GainPrior(distphase, st)
        )
# Now form the posterior

mms  = Model(st)

cllklhd = RadioLikelihood(dlcamp, dcphase)
clpost = Posterior(cllklhd, prior, mms)

lklhd = RadioLikelihood(dvis)#damp, dcphase)
post = Posterior(lklhd, prior, mms)
tpost = asflat(post)
# We will use HMC to sample the posterior.
# First to reduce burn in we use pathfinder
ndim = dimension(tpost)
f, tr = GalacticOptim.OptimizationFunction(post, GalacticOptim.AutoForwardDiff{15}())
#x0 = inverse(tr, rand(post.prior))

x0 = rand(post.prior, 50)
q, ϕ, inds = multipathfinder(clpost, 100; init_params=x0, ndraws_per_run=50)

res = map(1:150) do i
    #x0 = xx
    #x0.gphase .= randn(length(xx.gphase))
    #x0.gamp .= 1 .+ 0.2*randn(length(xx.gamp))
    prob = GalacticOptim.OptimizationProblem(f, randn(ndim), nothing)
    #sol, xopt = solve(prob, BBO_adaptive_de_rand_1_bin_radiuslimited(), tr; maxiters=200_000)

    #xopt = rand(post.prior)
    #prob = GalacticOptim.OptimizationProblem(f, sol.u, nothing)
    sol, xopt = solve(prob, LBFGS(), tr; iterations=2_000)
    @info "$i/50 $(sol.minimum)"
    xopt, sol.minimum
end

metric = DenseEuclideanMetric(ndim)
chain, stats = sample(post, HMC(;metric), 14_000; nadapts=10_000, init_params=res[ind[1]][1])


text:
# Note that this script can accept some limited command-line arguments, run
# `julia build_tarballs.jl --help` to see a usage message.
using BinaryBuilder, Pkg

name = "FlowCutterPACE17"
version = v"0.0.1"

# Collection of sources required to complete build
sources = [
    GitSource("https://github.com/kit-algo/flow-cutter-pace17.git", "fd405a2b003c9a93838e0488728addc0610a769f")
]

# Bash recipe for building across all platforms
script = raw"""
cd $WORKSPACE/srcdir/flow-cutter-pace17/
mkdir -p "${bindir}"
c++ -o "${bindir}/flow_cutter_pace17${exeext}" -Wall -std=c++11 -O3 -DNDEBUG src/*.cpp
"""

# These are the platforms we will build for by default, unless further
# platforms are passed in on the command line
platforms = supported_platforms()
platforms = expand_cxxstring_abis(platforms)

# The products that we will ensure are always built
products = [
    ExecutableProduct("flow_cutter_pace17", :flow_cutter_pace17)
]

# Dependencies that must be installed before this package can be built
dependencies = Dependency[
]

# Build the tarballs, and possibly a `build.jl` as well.
build_tarballs(ARGS, name, version, sources, script, platforms, products, dependencies)


text:
function test_HomogeneousWaveguide(scenario)
    @unpack bfield, species, ground = scenario

    distance = 1000e3
    waveguide = HomogeneousWaveguide(bfield, species, ground, distance)

    adjwaveguide = LMP.adjoint(waveguide)
    oB = waveguide.bfield
    aB = adjwaveguide.bfield
    @test aB.B == oB.B
    @test aB.dcl == -oB.dcl
    @test aB.dcm == oB.dcm
    @test aB.dcn == oB.dcn
    @test adjwaveguide.species == waveguide.species
    @test adjwaveguide.ground == waveguide.ground
    @test adjwaveguide.distance == waveguide.distance
end

@testset "Waveguides.jl" begin
    @info "Testing Waveguides"

    for scn in (verticalB_scenario, resonant_scenario, nonresonant_scenario,
        multiplespecies_scenario)
        test_HomogeneousWaveguide(scn)
    end
end


text:
module ZXCalculus

using YaoHIR, YaoLocations
using YaoHIR.IntrinsicOperation
using YaoHIR: Chain
using YaoLocations: plain
using MLStyle
using LightGraphs, Multigraphs

using LightGraphs: nv, ne, outneighbors, inneighbors, neighbors, rem_edge!,
    add_edge!, has_edge, degree, indegree, outdegree

export SpiderType, EdgeType
export AbstractZXDiagram, ZXDiagram, ZXGraph
export Rule, Match

export spider_type, phase, spiders, rem_spider!, rem_spiders!
export push_gate!, pushfirst_gate!, tcount
export convert_to_chain, convert_to_zxd
export rewrite!, simplify!, clifford_simplification, full_reduction,
    circuit_extraction, phase_teleportation
export random_circuit

include("phase.jl")
include("scalar.jl")

include("abstract_zx_diagram.jl")
include("zx_layout.jl")
include("zx_diagram.jl")
include("zx_graph.jl")

include("rules.jl")
include("simplify.jl")
include("circuit_extraction.jl")
include("phase_teleportation.jl")

include("ir.jl")

include("deprecations.jl")

end # module


text:
using BinDeps
using Compat

@BinDeps.setup

# specify the version of pcl we use
pcl_git_version = "master"

ignore_paths = split(strip(get(ENV, "PCLJL_LIBRARY_IGNORE_PATH", "")), ':')

# default validate function
default_validate = function(libpath, handle)
    for path in ignore_paths
        isempty(path) && continue
        ismatch(Regex("^$(path)"), libpath) && return false
    end
    return true
end

function pcl_library_dependency(s, validate=default_validate)
    library_dependency(s, validate=validate)
end

pcl_common = pcl_library_dependency("libpcl_common")
pcl_io = pcl_library_dependency("libpcl_io")
pcl_features = pcl_library_dependency("libpcl_features")
pcl_filters = pcl_library_dependency("libpcl_filters")
pcl_kdtree = pcl_library_dependency("libpcl_kdtree")
pcl_keypoints = pcl_library_dependency("libpcl_keypoints")
pcl_segmentation = pcl_library_dependency("libpcl_segmentation")
pcl_visualization = pcl_library_dependency("libpcl_visualization")
pcl_recognition = pcl_library_dependency("libpcl_recognition")
pcl_registration = pcl_library_dependency("libpcl_registration")
pcl_octree = pcl_library_dependency("libpcl_octree")
pcl_surface = pcl_library_dependency("libpcl_surface")
pcl_people = pcl_library_dependency("libpcl_people")
pcl_search = pcl_library_dependency("libpcl_search")
pcl_tracking = pcl_library_dependency("libpcl_tracking")

pcl_libs = [
    pcl_common,
    pcl_io,
    pcl_features,
    pcl_filters,
    pcl_kdtree,
    pcl_keypoints,
    pcl_segmentation,
    pcl_visualization,
    pcl_recognition,
    pcl_registration,
    pcl_octree,
    pcl_surface,
    pcl_people,
    pcl_search,
    pcl_tracking,
    ]

github_root = "https://github.com/PointCloudLibrary/pcl"
provides(Sources,
         URI("$(github_root)/archive/$(pcl_git_version).tar.gz"),
         pcl_libs,
         unpacked_dir="pcl-$(pcl_git_version)")

prefix = joinpath(BinDeps.depsdir(pcl_common), "usr")
srcdir = joinpath(BinDeps.depsdir(pcl_common), "src", "pcl-$(pcl_git_version)")

cmake_options = [
    "-DCMAKE_INSTALL_PREFIX=$prefix",
    "-DPCL_SHARED_LIBS=ON",
    "-DCMAKE_BUILD_TYPE=Release",
]

provides(SimpleBuild,
          (@build_steps begin
              GetSources(pcl_common)
              @build_steps begin
                  ChangeDirectory(srcdir)
                  `mkdir -p build`
                  @build_steps begin
                      ChangeDirectory(joinpath(srcdir, "build"))
                      `rm -f CMakeCache.txt`
                      `cmake $cmake_options ..`
                      `make -j4`
                      `make install`
                  end
                end
          end), pcl_libs, os = :Unix)

@BinDeps.install Dict(
    :libpcl_common => :libpcl_common,
    :libpcl_io => :libpcl_io,
    :libpcl_features => :libpcl_features,
    :libpcl_filters => :libpcl_filters,
    :libpcl_kdtree => :libpcl_kdtree,
    :libpcl_keypoints => :libpcl_keypoints,
    :libpcl_segmentation => :libpcl_segmentation,
    :libpcl_visualization => :libpcl_visualization,
    :libpcl_recognition => :libpcl_recognition,
    :libpcl_registration => :libpcl_registration,
    :libpcl_octree => :libpcl_octree,
    :libpcl_surface => :libpcl_surface,
    :libpcl_people => :libpcl_people,
    :libpcl_search => :libpcl_search,
    :libpcl_tracking => :libpcl_tracking,
    )


text:
# splitpath requires at least Julia 1.1.
# copy from https://github.com/JuliaLang/julia/blob/6f4b6fb62ceb5e5b6a00206b9b542dc321f0bbb7/base/path.jl
if v"1.0" <= VERSION < v"1.1"
    if Sys.isunix()
        const path_dir_splitter = r"^(.*?)(/+)([^/]*)$"
    elseif Sys.iswindows()
        const path_dir_splitter = r"^(.*?)([/\\]+)([^/\\]*)$"
    else
        error("path primitives for this OS need to be defined")
    end

    _splitdir_nodrive(path::String) = _splitdir_nodrive("", path)
    function _splitdir_nodrive(a::String, b::String)
        m = match(path_dir_splitter,b)
        m === nothing && return (a,b)
        a = string(a, isempty(m.captures[1]) ? m.captures[2][1] : m.captures[1])
        a, String(m.captures[3])
    end

    function splitpath(p::String)
        drive, p = splitdrive(p)
        out = String[]
        isempty(p) && (pushfirst!(out,p))  # "" means the current directory.
        while !isempty(p)
            dir, base = _splitdir_nodrive(p)
            dir == p && (pushfirst!(out, dir); break)  # Reached root node.
            if !isempty(base)  # Skip trailing '/' in basename
                pushfirst!(out, base)
            end
            p = dir
        end
        if !isempty(drive)  # Tack the drive back on to the first element.
            out[1] = drive*out[1]  # Note that length(out) is always >= 1.
        end
        return out
    end
end

if v"1.0" <= VERSION < v"1.1"
    isnothing(x) = x===nothing
end


text:
using TinySegmenter, Test

@test tokenize("私の名前は中野です") == ["私", "の", "名前", "は", "中野", "です"]
@test tokenize("TinySegmenterは25kBで書かれています。")　== ["TinySegmenter", "は", "2", "5", "kB", "で", "書か", "れ", "て", "い", "ます", "。"]
@test tokenize("") == []

result_text = join(TinySegmenter.tokenize(read("timemachineu8j.txt", String)), " | ")
@test result_text == read("timemachineu8j.tokenized.txt", String)

import TinySegmenter.ctype
@test ctype('一') == UInt8('M')
@test ctype('〆') == UInt8('H')
@test ctype('名') == UInt8('H')
@test ctype('あ') == UInt8('I')
@test ctype('ア') == UInt8('K')
@test ctype('Ｚ') == UInt8('A')
@test ctype('９') == UInt8('N')


text:
# set JULIA_NUM_THREADS=8
using Base.Threads
using Printf
using Dates
fout = open("test.log","w")
flock = Threads.SpinLock()
idxlock = Threads.SpinLock()
glbidx  =1
function getIdxGlb( )
global glbidx
    i=0
    lock( idxlock )
    i = glbidx
    glbidx = glbidx +1
    unlock( idxlock )
    return i
end

function writefile( fout,id ,flock)
    lock(flock )
    a=Dates.now()
    b=string(hour(a),":",minute(a),":",second(a),".",millisecond(a) )
    strTest = @sprintf( "%06d,%u,%06d,%18s\r\n",id,Threads.threadid(),getIdxGlb(),b )
    write(fout, strTest )
    unlock( flock )
end
@threads for idx = 1:100000
    writefile( fout,idx ,flock)
end
close(fout)

max_stars_repo_name: wangzhongtian/fiberAlarmAnalyseTool

max_issues_repo_name: wangzhongtian/fiberAlarmAnalyseTool

max_forks_repo_name: wangzhongtian/fiberAlarmAnalyseTool


text:
# Based on http://en.wikipedia.org/wiki/Cross-entropy_method

using Distributions

function sample_gaussian(mu, sigma, n)
  distr = Normal(mu, sigma)
  rand(distr, n)
end

# Objective function that we are optimizing
function my_fun1(x)
  exp(-(x-2).^2) + 0.8 * exp(-(x+2).^2)
end

# Cross-entropy using a gaussian proposal distr...
function cross_entropy_method(func;
  max_iterations = 100, num_samples = 100, top_quantile = 0.10,
  std_convergence = 1e-5, mu = 0, sigma = sqrt(100), maximization = true)

  num_top = convert(Int64, ceil(num_samples * top_quantile))
  step = 0

  while( step < max_iterations && sigma > std_convergence)
    X = sample_gaussian(mu, sigma, num_samples)
    S = func(X)
    top_X = X[sortperm(S, rev=maximization)[1:num_top]]
    mu = mean(top_X)
    sigma = std(top_X)
    step += 1
  end

  return mu

end


text:
# plots a map of the radarlines of all glacier with radar

using VAWTools, ProgressMeter
import BITEModel
const BM = BITEModel
# include("../rgi-setup.jl")

region_strs = ["03", "04", "07", "11", "14"]

for region_str in region_strs
    @show region_str

    region = parse(Int, region_str)

    glnrs1 = BM.get_glaciers_with_radar(region)
    @showprogress 0.5 "Plotting..." for g in glnrs1
        try
            gid = BM.RGIGlacier(g, region)
            pl = BM.LoadPara(gid)
            gl,pp,pm,pn,pl = BM.load_glacier(gid,pl)
            # BM.plot_radar2d(gl)
            # Plots.savefig("paper1/figs/radar/$(region_str)_$(VAWTools.int2str5(g)).png")

            Plots.plot(gl)
            Plots.savefig("paper1/figs/dem/$(region_str)_$(VAWTools.int2str5(g)).png")
        catch e
            if e isa InterruptException
                rethrow(e)
            end
            println("$g Error $e")
        end
    end
end

# get sorted
function get_sorted(reg)
    out = Int[]
    for f in readdir("paper1/figs/radar/sorted/$(VAWTools.int2str2(reg))")
        push!(out, parse(Int, split(splitext(f)[1], '_')[2]))
    end
    out
end


text:
@system Emergence(Stage, Planting) begin
    emergence_date => nothing ~ preserve::datetime(optional, parameter)
    begin_from_emergence(emergence_date) => !isnothing(emergence_date) ~ preserve::Bool

    ER_max: maximum_emergence_rate => 0.0876 ~ preserve(u"d^-1", parameter)

    ER_T_opt: emergence_optimal_temperature => 12.7 ~ preserve(parameter, u"°C")
    ER_T_ceil: emergence_ceiling_temperature => 35.9 ~ preserve(parameter, u"°C")
    ER_BF(context, T, To=ER_T_opt', Tx=ER_T_ceil'): germination_beta_function ~ ::BetaFunction

    emergence(r=ER_max, β=ER_BF.ΔT) => begin
        #FIXME prevent extra accumulation after it's `over`
        r * β
    end ~ accumulate(when=emerging)

    emergeable(planted) ~ flag
    emerged(emergence, begin_from_emergence, emergence_date, t=calendar.time) => begin
        if begin_from_emergence
            t >= emergence_date
        else
            emergence >= 1.0
        end
    end ~ flag
    emerging(emergeable & !emerged) ~ flag

    # #FIXME postprocess similar to @produce?
    # def finish(self):
    #     GDD_sum = self.pheno.gdd_recorder.rate
    #     T_grow = self.pheno.growing_temperature
    #     print(f"* Emergence: time = {self.time}, GDDsum = {GDD_sum}, Growing season T = {T_grow}")

    #     #HACK reset GDD tracker after emergence
    #     self.emerge_GDD = GDD_sum
    #     self.pheno.gdd_recorder.reset()
end


text:
using AutoHashEquals

abstract Graph

@auto_hash_equals type Node<:Graph
    label::AbstractString
    children::Vector{Graph}
    Node(label, children...) = new(label, Graph[children...])
end

type Cycle<:Graph
    node::Nullable{Graph}
    Cycle() = new(Nullable{Graph}())
end

function gprint(known::Set{Graph}, n::Node)
    function producer()
        if n in known
            produce(string(n.label, "..."))
        else
            push!(known, n)
            produce(n.label)
            for child in n.children
                prefix = child == n.children[end] ? "`-" : "+-"
                for line in gprint(known, child)
                    produce(string(prefix, line))
                    prefix = child == n.children[end] ? "  " : "| y"
                end
            end
            delete!(known, n)
        end
    end
    Task(producer)
end

function gprint(known::Set{Graph}, c::Cycle)
    if isnull(c.node)
        Task(() -> produce("?"))
    elseif c in known
        Task(() -> produce("..."))
    else
        push!(known, c)
        t = gprint(known, get(c.node))
        delete!(known, c)
        t
    end
end

function Base.print(io::Base.IO, g::Graph)
    for line in gprint(Set{Graph}(), g)
        println(io, line)
    end
end

x = Cycle()
g = Node("a",
         Node("b"),
         Node("c",
              x,
              Node("d")))
print(g)

x.node = g
print(g)


text:
# prints solution of any part
function x(num = 30000000)
	f = open("15.txt")
	l = readline(f)
	d = Dict{Int, Int}()
	lastnum = 0
	i = 1
	for n in split(l, ",")
		x = parse(Int, n)
		lastnum = x
		#println(lastnum)
		d[lastnum] = i
		i+=1
	end
	c = 0
	while i <= num
		if lastnum in keys(d)
			c = i-1-d[lastnum]
		else
			c = 0
		end
		d[lastnum] = i-1
		lastnum = c
		i+=1
	end
	println(lastnum)
end
x(2020)
x(30000000)


text:
module Ariadne

using Luxor: Drawing, Point, background, finish, setcolor, setline, rect, line, preview

export CartesianGrid
export Distances
export Maze
export colindex, rowindex
export dijkstra, dijkstra!
export pathto, pathto!
export links
export islinked
export link!, unlink!
export distances, path
export setdistances!, setpath!
export north, south, west, east
export entrance, getexit
export neighbors
export aldousbroder!
export binarytree!
export sidewinder!
export render

mutable struct Cell
    rowindex::Int
    colindex::Int
    links::Set{Cell}
end

Cell(rowindex, colindex) = Cell(rowindex, colindex, Set{Cell}())

Base.show(io::IO, c::Cell) = print(io, "Cell($(c.rowindex), $(c.colindex))")

rowindex(c) = c.rowindex
colindex(c) = c.colindex

links(::Nothing) = Set{Cell}()
links(x::Cell) = x.links

function link!(a, b, reverse=true)
    push!(a.links, b)
    if reverse link!(b, a, false) end
end

function unlink!(a, b, reverse=true)
    pop!(a.links, b, nothing)
    if reverse unlink!(b, a, false) end
end

islinked(::Nothing, b) = false
islinked(a, ::Nothing) = false
islinked(a, b) = b in a.links

mutable struct CartesianGrid <: AbstractMatrix{Cell}
    cells::Matrix
end

_cellmatrix(nrows, ncols) = [Cell(r, c) for r in 1:nrows, c in 1:ncols]

CartesianGrid(nrows, ncols) = _cellmatrix(nrows, ncols) |> CartesianGrid

Base.size(g::CartesianGrid) = size(g.cells)

function Base.getindex(g::CartesianGrid, row, col)
    nrows, ncols = size(g)
    rowoob = row < 1 || row > nrows
    coloob = col < 1 || col > ncols
    (rowoob || coloob) && return nothing
    return getindex(g.cells, row, col)
end

north(g, c) = g[c.rowindex - 1, c.colindex]
south(g, c) = g[c.rowindex + 1, c.colindex]
west(g, c) = g[c.rowindex, c.colindex - 1]
east(g, c) = g[c.rowindex, c.colindex + 1]

function neighbors(g, c)
    n = north(g, c)
    s = south(g, c)
    w = west(g, c)
    e = east(g, c)
    return filter(!isnothing, [n, s, w, e])
end

mutable struct Distances <: AbstractDict{Cell,Int}
    root::Cell
    cells::Dict{Cell,Int}
end

Base.length(d::Distances) = length(d.cells)

Base.iterate(d::Distances) = iterate(d.cells)
Base.iterate(d::Distances, s) = iterate(d.cells, s)

Base.get(d::Distances, key, default) = get(d.cells, key, default)

Base.minimum(d::Distances) = findmin(d.cells)
Base.maximum(d::Distances) = findmax(d.cells)

root(d::Distances) = d.root
cells(d::Distances) = d.cells

function dijkstra(root)
    cells = Dict{Cell,Int}()
    cells[root] = 0
    frontier = [root]
    while !isempty(frontier)
        newfrontier = empty([], Cell)
        for cell in frontier
            for link in links(cell)
                if link in keys(cells)
                    continue
                end
                cells[link] = cells[cell] + 1
                push!(newfrontier, link)
            end
        end
        frontier = newfrontier
    end
    return Distances(root, cells)
end

pathto(::Nothing, goal) = nothing

function pathto(d, goal)
    current = goal
    path = Distances(root(d), Dict{Cell,Int}())
    cells(path)[current] = d[current]
    while current != root(d)
        for link in links(current)
            if d[link] < d[current]
                cells(path)[link] = d[link]
                current = link
                break
            end
        end
    end
    return path
end

mutable struct Maze <: AbstractMatrix{Cell}
    grid::AbstractMatrix{Cell}
    distances::Union{Nothing,Distances}
    entrance::Union{Nothing,Cell}
    exit::Union{Nothing,Cell}
    path::Union{Nothing,Distances}
end

Maze(grid) = Maze(
    grid,
    nothing,
    first(grid),
    nothing,
    nothing)

Base.size(m::Maze) = size(grid(m))
Base.getindex(m::Maze, row, col) = getindex(grid(m), row, col)

grid(m) = m.grid
distances(m) = m.distances
entrance(m) = m.entrance
getexit(m) = m.exit
path(m) = m.path

function setentrance!(m, e)
    m.entrance = e
    return m
end

function setexit!(m, e)
    m.exit = e
    return m
end

function setdistances!(m, d)
    m.distances = d
    return m
end

function setpath!(m, p)
    m.path = p
    return m
end

dijkstra!(m, root) = setdistances!(m, dijkstra(root))
pathto!(m, goal) = setpath!(m, pathto(distances(m), goal))

function longestpath!(m)
    root = first(m)
    d = dijkstra(root)
    ignored, start = findmax(d)
    d = dijkstra(start)
    ignored, exit = findmax(d)
    setdistances!(m, d)
    setpath!(m, pathto(d, exit))
    setentrance!(m, start)
    setexit!(m, exit)
end

function binarytree!(m::AbstractMatrix{Cell})
    for cell in m
        neighbors = Set{Cell}()
        n = north(m, cell)
        e = east(m, cell)
        isnothing(n) || push!(neighbors, n)
        isnothing(e) || push!(neighbors, e)
        if !isempty(neighbors)
            target = rand(neighbors)
            link!(cell, target)
        end
    end
    return m
end

function sidewinder!(m::AbstractMatrix{Cell})
    for row in eachrow(m)
        run = Set{Cell}()
        for cell in row
            push!(run, cell)
            atebound = isnothing(east(m, cell))
            atnbound = isnothing(north(m, cell))
            closerun = atebound || (!atnbound && iszero(rand((0, 1))))
            if closerun
                target = rand(run)
                n = north(m, target)
                !isnothing(n) && link!(target, n)
                empty!(run)
            else
                link!(cell, east(m, cell))
            end
        end
    end
    return m
end

function aldousbroder!(m::AbstractMatrix{Cell})
    cell = rand(m)
    nrows, ncols = size(m)
    unvisited = nrows * ncols - 1
    while unvisited > 0
        neighbor = rand(neighbors(m, cell))
        if isempty(links(neighbor))
            link!(cell, neighbor)
            unvisited -= 1
        end
        cell = neighbor
    end
    return m
end

function _bgcolor(m::Maze, cell::Cell;
    renderpath = false,
    renderdistances = false,
    renderentrance = false,
    renderexit = false)
    if renderentrance && cell == entrance(m)
        return 1.0, 0.0, 0.0
    end
    if renderexit && cell == getexit(m)
        return 0.0, 1.0, 0.0
    end
    d = distances(m)
    if isnothing(d)
        return 1.0, 1.0, 1.0
    end
    p = path(m)
    if renderpath && !isnothing(p) && haskey(p.cells, cell)
        return 0.1, 0.8, 1.0
    end
    if renderdistances && haskey(d.cells, cell)
        distance = d[cell]
        maxdistance = first(maximum(d))
        intensity = (maxdistance  - distance) / maxdistance
        dark = intensity
        bright = 0.5 + (intensity * 0.5)
        return dark, bright, bright
    end
    return 1.0, 1.0, 1.0
end

function render(m;
    out = "out.png",
    cellsize = 16,
    modes = [:background, :walls],
    renderpath = false,
    renderdistances = false)
    nrows, ncols = size(m)
    imgw = cellsize * ncols
    imgh = cellsize * nrows
    Drawing(imgw + 2, imgh + 2, out)
    background("white")
    for mode in modes
        for cell in m
            x1 = (colindex(cell) - 1) * cellsize + 0.5
            y1 = (rowindex(cell) - 1) * cellsize + 0.5
            x2 = colindex(cell) * cellsize + 0.5
            y2 = rowindex(cell) * cellsize + 0.5
            if mode == :background
                color = color = _bgcolor(m, cell,
                    renderpath = renderpath,
                    renderdistances = renderdistances)
                setcolor(color)
                setline(1.0)
                rect(x1, y1, cellsize, cellsize, :fill)
                rect(x1, y1, cellsize, cellsize, :stroke)
            else
                setcolor("black")
                setline(1.0)
                isnothing(north(m, cell)) && line(Point(x1, y1), Point(x2, y1), :stroke)
                isnothing(west(m, cell)) && line(Point(x1, y1), Point(x1, y2), :stroke)
                islinked(cell, east(m, cell)) || line(Point(x2, y1), Point(x2, y2), :stroke)
                islinked(cell, south(m, cell)) || line(Point(x1, y2), Point(x2, y2), :stroke)
            end
        end
    end
    finish()
    preview()
    return m
end

function test()
    const dim = 64
    CartesianGrid(dim, dim) |>
        Maze |>
        binarytree! |>
        m -> dijkstra!(m, m[dim, dim ÷ 2]) |>
        m -> pathto!(m, m[dim, dim]) |>
        m -> render(m, cellsize = 16)
end

end # module

max_stars_repo_name: basp/ariadne

max_issues_repo_name: basp/ariadne

max_forks_repo_name: basp/ariadne


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

"""
    CloneBackend()

This operation clones an existing backend.

# Required Parameters
- `appId`: The app ID.
- `backendEnvironmentName`: The name of the backend environment.
- `targetEnvironmentName`: The name of the destination backend environment to be created.

"""
clone_backend(appId, backendEnvironmentName, targetEnvironmentName; aws_config::AWSConfig=global_aws_config()) = amplifybackend("POST", "/backend/$(appId)/environments/$(backendEnvironmentName)/clone", Dict{String, Any}("targetEnvironmentName"=>targetEnvironmentName); aws_config=aws_config)
clone_backend(appId, backendEnvironmentName, targetEnvironmentName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = amplifybackend("POST", "/backend/$(appId)/environments/$(backendEnvironmentName)/clone", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("targetEnvironmentName"=>targetEnvironmentName), args)); aws_config=aws_config)

"""
    CreateBackend()

This operation creates a backend for an Amplify app. Backends are automatically created at the time of app creation.

# Required Parameters
- `appId`: The app ID.
- `appName`: The name of the app.
- `backendEnvironmentName`: The name of the backend environment.

# Optional Parameters
- `resourceConfig`: The resource configuration for the create backend request.
- `resourceName`: The name of the resource.
"""
create_backend(appId, appName, backendEnvironmentName; aws_config::AWSConfig=global_aws_config()) = amplifybackend("POST", "/backend", Dict{String, Any}("appId"=>appId, "appName"=>appName, "backendEnvironmentName"=>backendEnvironmentName); aws_config=aws_config)
create_backend(appId, appName, backendEnvironmentName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = amplifybackend("POST", "/backend", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("appId"=>appId, "appName"=>appName, "backendEnvironmentName"=>backendEnvironmentName), args)); aws_config=aws_config)

"""
    CreateBackendAPI()

Creates a new backend API resource.

# Required Parameters
- `appId`: The app ID.
- `backendEnvironmentName`: The name of the backend environment.
- `resourceConfig`: The resource configuration for this request.
- `resourceName`: The name of this resource.

"""
create_backend_api(appId, backendEnvironmentName, resourceConfig, resourceName; aws_config::AWSConfig=global_aws_config()) = amplifybackend("POST", "/backend/$(appId)/api", Dict{String, Any}("backendEnvironmentName"=>backendEnvironmentName, "resourceConfig"=>resourceConfig, "resourceName"=>resourceName); aws_config=aws_config)
create_backend_api(appId, backendEnvironmentName, resourceConfig, resourceName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = amplifybackend("POST", "/backend/$(appId)/api", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("backendEnvironmentName"=>backendEnvironmentName, "resourceConfig"=>resourceConfig, "resourceName"=>resourceName), args)); aws_config=aws_config)

"""
    CreateBackendAuth()

Creates a new backend authentication resource.

# Required Parameters
- `appId`: The app ID.
- `backendEnvironmentName`: The name of the backend environment.
- `resourceConfig`: The resource configuration for this request object.
- `resourceName`: The name of this resource.

"""
create_backend_auth(appId, backendEnvironmentName, resourceConfig, resourceName; aws_config::AWSConfig=global_aws_config()) = amplifybackend("POST", "/backend/$(appId)/auth", Dict{String, Any}("backendEnvironmentName"=>backendEnvironmentName, "resourceConfig"=>resourceConfig, "resourceName"=>resourceName); aws_config=aws_config)
create_backend_auth(appId, backendEnvironmentName, resourceConfig, resourceName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = amplifybackend("POST", "/backend/$(appId)/auth", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("backendEnvironmentName"=>backendEnvironmentName, "resourceConfig"=>resourceConfig, "resourceName"=>resourceName), args)); aws_config=aws_config)

"""
    CreateBackendConfig()

Creates a config object for a backend.

# Required Parameters
- `appId`: The app ID.

# Optional Parameters
- `backendManagerAppId`: The app ID for the backend manager.
"""
create_backend_config(appId; aws_config::AWSConfig=global_aws_config()) = amplifybackend("POST", "/backend/$(appId)/config"; aws_config=aws_config)
create_backend_config(appId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = amplifybackend("POST", "/backend/$(appId)/config", args; aws_config=aws_config)

"""
    CreateToken()

Generates a one time challenge code to authenticate a user into your Amplify Admin UI.

# Required Parameters
- `appId`: The app ID.

"""
create_token(appId; aws_config::AWSConfig=global_aws_config()) = amplifybackend("POST", "/backend/$(appId)/challenge"; aws_config=aws_config)
create_token(appId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = amplifybackend("POST", "/backend/$(appId)/challenge", args; aws_config=aws_config)

"""
    DeleteBackend()

Removes an existing environment from your Ampify project.

# Required Parameters
- `appId`: The app ID.
- `backendEnvironmentName`: The name of the backend environment.

"""
delete_backend(appId, backendEnvironmentName; aws_config::AWSConfig=global_aws_config()) = amplifybackend("POST", "/backend/$(appId)/environments/$(backendEnvironmentName)/remove"; aws_config=aws_config)
delete_backend(appId, backendEnvironmentName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = amplifybackend("POST", "/backend/$(appId)/environments/$(backendEnvironmentName)/remove", args; aws_config=aws_config)

"""
    DeleteBackendAPI()

Deletes an existing backend API resource.

# Required Parameters
- `appId`: The app ID.
- `backendEnvironmentName`: The name of the backend environment.
- `resourceName`: The name of this resource.

# Optional Parameters
- `resourceConfig`: Defines the resource configuration for the data model in your Amplify project.
"""
delete_backend_api(appId, backendEnvironmentName, resourceName; aws_config::AWSConfig=global_aws_config()) = amplifybackend("POST", "/backend/$(appId)/api/$(backendEnvironmentName)/remove", Dict{String, Any}("resourceName"=>resourceName); aws_config=aws_config)
delete_backend_api(appId, backendEnvironmentName, resourceName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = amplifybackend("POST", "/backend/$(appId)/api/$(backendEnvironmentName)/remove", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("resourceName"=>resourceName), args)); aws_config=aws_config)

"""
    DeleteBackendAuth()

Deletes an existing backend authentication resource.

# Required Parameters
- `appId`: The app ID.
- `backendEnvironmentName`: The name of the backend environment.
- `resourceName`: The name of this resource.

"""
delete_backend_auth(appId, backendEnvironmentName, resourceName; aws_config::AWSConfig=global_aws_config()) = amplifybackend("POST", "/backend/$(appId)/auth/$(backendEnvironmentName)/remove", Dict{String, Any}("resourceName"=>resourceName); aws_config=aws_config)
delete_backend_auth(appId, backendEnvironmentName, resourceName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = amplifybackend("POST", "/backend/$(appId)/auth/$(backendEnvironmentName)/remove", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("resourceName"=>resourceName), args)); aws_config=aws_config)

"""
    DeleteToken()

Deletes the challenge token based on the given appId and sessionId.

# Required Parameters
- `appId`: The app ID.
- `sessionId`: The session Id.

"""
delete_token(appId, sessionId; aws_config::AWSConfig=global_aws_config()) = amplifybackend("POST", "/backend/$(appId)/challenge/$(sessionId)/remove"; aws_config=aws_config)
delete_token(appId, sessionId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = amplifybackend("POST", "/backend/$(appId)/challenge/$(sessionId)/remove", args; aws_config=aws_config)

"""
    GenerateBackendAPIModels()

Generates a model schema for an existing backend API resource.

# Required Parameters
- `appId`: The app ID.
- `backendEnvironmentName`: The name of the backend environment.
- `resourceName`: The name of this resource.

"""
generate_backend_apimodels(appId, backendEnvironmentName, resourceName; aws_config::AWSConfig=global_aws_config()) = amplifybackend("POST", "/backend/$(appId)/api/$(backendEnvironmentName)/generateModels", Dict{String, Any}("resourceName"=>resourceName); aws_config=aws_config)
generate_backend_apimodels(appId, backendEnvironmentName, resourceName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = amplifybackend("POST", "/backend/$(appId)/api/$(backendEnvironmentName)/generateModels", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("resourceName"=>resourceName), args)); aws_config=aws_config)

"""
    GetBackend()

Provides project level details for your Amplify UI project.

# Required Parameters
- `appId`: The app ID.

# Optional Parameters
- `backendEnvironmentName`: The name of the backend environment.
"""
get_backend(appId; aws_config::AWSConfig=global_aws_config()) = amplifybackend("POST", "/backend/$(appId)/details"; aws_config=aws_config)
get_backend(appId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = amplifybackend("POST", "/backend/$(appId)/details", args; aws_config=aws_config)

"""
    GetBackendAPI()

Gets the details for a backend api.

# Required Parameters
- `appId`: The app ID.
- `backendEnvironmentName`: The name of the backend environment.
- `resourceName`: The name of this resource.

# Optional Parameters
- `resourceConfig`: Defines the resource configuration for the data model in your Amplify project.
"""
get_backend_api(appId, backendEnvironmentName, resourceName; aws_config::AWSConfig=global_aws_config()) = amplifybackend("POST", "/backend/$(appId)/api/$(backendEnvironmentName)/details", Dict{String, Any}("resourceName"=>resourceName); aws_config=aws_config)
get_backend_api(appId, backendEnvironmentName, resourceName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = amplifybackend("POST", "/backend/$(appId)/api/$(backendEnvironmentName)/details", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("resourceName"=>resourceName), args)); aws_config=aws_config)

"""
    GetBackendAPIModels()

Generates a model schema for existing backend API resource.

# Required Parameters
- `appId`: The app ID.
- `backendEnvironmentName`: The name of the backend environment.
- `resourceName`: The name of this resource.

"""
get_backend_apimodels(appId, backendEnvironmentName, resourceName; aws_config::AWSConfig=global_aws_config()) = amplifybackend("POST", "/backend/$(appId)/api/$(backendEnvironmentName)/getModels", Dict{String, Any}("resourceName"=>resourceName); aws_config=aws_config)
get_backend_apimodels(appId, backendEnvironmentName, resourceName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = amplifybackend("POST", "/backend/$(appId)/api/$(backendEnvironmentName)/getModels", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("resourceName"=>resourceName), args)); aws_config=aws_config)

"""
    GetBackendAuth()

Gets a backend auth details.

# Required Parameters
- `appId`: The app ID.
- `backendEnvironmentName`: The name of the backend environment.
- `resourceName`: The name of this resource.

"""
get_backend_auth(appId, backendEnvironmentName, resourceName; aws_config::AWSConfig=global_aws_config()) = amplifybackend("POST", "/backend/$(appId)/auth/$(backendEnvironmentName)/details", Dict{String, Any}("resourceName"=>resourceName); aws_config=aws_config)
get_backend_auth(appId, backendEnvironmentName, resourceName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = amplifybackend("POST", "/backend/$(appId)/auth/$(backendEnvironmentName)/details", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("resourceName"=>resourceName), args)); aws_config=aws_config)

"""
    GetBackendJob()

Returns information about a specific job.

# Required Parameters
- `appId`: The app ID.
- `backendEnvironmentName`: The name of the backend environment.
- `jobId`: The ID for the job.

"""
get_backend_job(appId, backendEnvironmentName, jobId; aws_config::AWSConfig=global_aws_config()) = amplifybackend("GET", "/backend/$(appId)/job/$(backendEnvironmentName)/$(jobId)"; aws_config=aws_config)
get_backend_job(appId, backendEnvironmentName, jobId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = amplifybackend("GET", "/backend/$(appId)/job/$(backendEnvironmentName)/$(jobId)", args; aws_config=aws_config)

"""
    GetToken()

Gets the challenge token based on the given appId and sessionId.

# Required Parameters
- `appId`: The app ID.
- `sessionId`: The session Id.

"""
get_token(appId, sessionId; aws_config::AWSConfig=global_aws_config()) = amplifybackend("GET", "/backend/$(appId)/challenge/$(sessionId)"; aws_config=aws_config)
get_token(appId, sessionId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = amplifybackend("GET", "/backend/$(appId)/challenge/$(sessionId)", args; aws_config=aws_config)

"""
    ListBackendJobs()

Lists the jobs for the backend of an Amplify app.

# Required Parameters
- `appId`: The app ID.
- `backendEnvironmentName`: The name of the backend environment.

# Optional Parameters
- `jobId`: The ID for the job.
- `maxResults`: The maximum number of results you want in the response.
- `nextToken`: The token for the next set of results.
- `operation`: Filters the list of response objects to only include those with the specified operation name.
- `status`: Filters the list of response objects to only include those with the specified status.
"""
list_backend_jobs(appId, backendEnvironmentName; aws_config::AWSConfig=global_aws_config()) = amplifybackend("POST", "/backend/$(appId)/job/$(backendEnvironmentName)"; aws_config=aws_config)
list_backend_jobs(appId, backendEnvironmentName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = amplifybackend("POST", "/backend/$(appId)/job/$(backendEnvironmentName)", args; aws_config=aws_config)

"""
    RemoveAllBackends()

Removes all backend environments from your Amplify project.

# Required Parameters
- `appId`: The app ID.

# Optional Parameters
- `cleanAmplifyApp`: Cleans up the Amplify Console app if this value is set to true.
"""
remove_all_backends(appId; aws_config::AWSConfig=global_aws_config()) = amplifybackend("POST", "/backend/$(appId)/remove"; aws_config=aws_config)
remove_all_backends(appId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = amplifybackend("POST", "/backend/$(appId)/remove", args; aws_config=aws_config)

"""
    RemoveBackendConfig()

Removes the AWS resources required to access the Amplify Admin UI.

# Required Parameters
- `appId`: The app ID.

"""
remove_backend_config(appId; aws_config::AWSConfig=global_aws_config()) = amplifybackend("POST", "/backend/$(appId)/config/remove"; aws_config=aws_config)
remove_backend_config(appId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = amplifybackend("POST", "/backend/$(appId)/config/remove", args; aws_config=aws_config)

"""
    UpdateBackendAPI()

Updates an existing backend API resource.

# Required Parameters
- `appId`: The app ID.
- `backendEnvironmentName`: The name of the backend environment.
- `resourceName`: The name of this resource.

# Optional Parameters
- `resourceConfig`: Defines the resource configuration for the data model in your Amplify project.
"""
update_backend_api(appId, backendEnvironmentName, resourceName; aws_config::AWSConfig=global_aws_config()) = amplifybackend("POST", "/backend/$(appId)/api/$(backendEnvironmentName)", Dict{String, Any}("resourceName"=>resourceName); aws_config=aws_config)
update_backend_api(appId, backendEnvironmentName, resourceName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = amplifybackend("POST", "/backend/$(appId)/api/$(backendEnvironmentName)", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("resourceName"=>resourceName), args)); aws_config=aws_config)

"""
    UpdateBackendAuth()

Updates an existing backend authentication resource.

# Required Parameters
- `appId`: The app ID.
- `backendEnvironmentName`: The name of the backend environment.
- `resourceConfig`: The resource configuration for this request object.
- `resourceName`: The name of this resource.

"""
update_backend_auth(appId, backendEnvironmentName, resourceConfig, resourceName; aws_config::AWSConfig=global_aws_config()) = amplifybackend("POST", "/backend/$(appId)/auth/$(backendEnvironmentName)", Dict{String, Any}("resourceConfig"=>resourceConfig, "resourceName"=>resourceName); aws_config=aws_config)
update_backend_auth(appId, backendEnvironmentName, resourceConfig, resourceName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = amplifybackend("POST", "/backend/$(appId)/auth/$(backendEnvironmentName)", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("resourceConfig"=>resourceConfig, "resourceName"=>resourceName), args)); aws_config=aws_config)

"""
    UpdateBackendConfig()

Updates the AWS resources required to access the Amplify Admin UI.

# Required Parameters
- `appId`: The app ID.

# Optional Parameters
- `loginAuthConfig`: Describes the Amazon Cognito configuration for Admin UI access.
"""
update_backend_config(appId; aws_config::AWSConfig=global_aws_config()) = amplifybackend("POST", "/backend/$(appId)/config/update"; aws_config=aws_config)
update_backend_config(appId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = amplifybackend("POST", "/backend/$(appId)/config/update", args; aws_config=aws_config)

"""
    UpdateBackendJob()

Updates a specific job.

# Required Parameters
- `appId`: The app ID.
- `backendEnvironmentName`: The name of the backend environment.
- `jobId`: The ID for the job.

# Optional Parameters
- `operation`: Filters the list of response objects to only include those with the specified operation name.
- `status`: Filters the list of response objects to only include those with the specified status.
"""
update_backend_job(appId, backendEnvironmentName, jobId; aws_config::AWSConfig=global_aws_config()) = amplifybackend("POST", "/backend/$(appId)/job/$(backendEnvironmentName)/$(jobId)"; aws_config=aws_config)
update_backend_job(appId, backendEnvironmentName, jobId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = amplifybackend("POST", "/backend/$(appId)/job/$(backendEnvironmentName)/$(jobId)", args; aws_config=aws_config)