text:
function makeMesh(r,outDir=".")

  n = size(r,1)

  gmsh.initialize()
  gmsh.option.setNumber("General.Terminal", 0) # change to 1 for Gmsh output

  gmsh.model.add("mixing")

  lc = 1e-2
  global theta = range(0.0,stop=2.0*pi,length=n+1)

  for i=1:n
    gmsh.model.geo.addPoint(r[i]*cos(theta[i]),
                            r[i]*sin(theta[i]),
                            0.0, lc, i)
  end

  for i=1:n
    gmsh.model.geo.addPoint(2*cos(theta[i]),2*sin(theta[i]),0.0, 2*lc,n+i)
  end

  nCircle = 15
  global theta1 = range(0.0,stop=2.0*pi,length=nCircle+1)
  for i=1:nCircle
    gmsh.model.geo.addPoint(1.25+0.1*cos(theta1[i]),1.25+0.1*sin(theta1[i]),0.0, lc,2n+i)
#    gmsh.model.geo.addPoint(1.75+0.1*cos(theta1[i]),0.0+0.1*sin(theta1[i]),0.0, lc,2n+i)
  end

  #  Assemble boundary points into curves following the right-hand-rule
  #  (traverse the boundary with your right hand toward the "outside")
  gmsh.model.geo.addBSpline([1;collect(n:-1:1)],1)
  gmsh.model.geo.addSpline([collect((n+1):(2*n));n+1],2)
  gmsh.model.geo.addSpline([2*n+1;collect(2*n+nCircle:-1:2*n+1)],3)

  gmsh.model.geo.addCurveLoop([1],1)
  gmsh.model.geo.addCurveLoop([2],2)
  gmsh.model.geo.addCurveLoop([3],3)
  gmsh.model.geo.addPlaneSurface([1,2,3],1)
  gmsh.model.geo.addPlaneSurface([3],2)

  gmsh.model.addPhysicalGroup(1, [1], 1)
  gmsh.model.addPhysicalGroup(1, [2], 2)
 # gmsh.model.addPhysicalGroup(1, [3], 3)
  gmsh.model.setPhysicalName(1, 1, "Inner")
  gmsh.model.setPhysicalName(1, 2, "Outer")

  gmsh.model.addPhysicalGroup(2, [1], 1)
  gmsh.model.addPhysicalGroup(2, [2], 2)
  gmsh.model.setPhysicalName(2, 1, "Mesh")
  # gmsh.model.setPhysicalName(2, 2, "Sensor")

  gmsh.model.geo.synchronize()

  gmsh.model.mesh.generate(2)
  gmsh.model.mesh.setOrder(2)  # quadratic elements

  ##nodeIds,nodeCoords,_ = gmsh.model.mesh.getNodes()
  ##x = reshape(nodeCoords,3,:)
  nodeTags1,xx1 = gmsh.model.mesh.getNodesForPhysicalGroup(2,1)
  nodeTags2,xx2 = gmsh.model.mesh.getNodesForPhysicalGroup(2,2)
  xx1 = reshape(xx1,3,:)
  xx2 = reshape(xx2,3,:)
  nn = convert(Int64,maximum(nodeTags2))
  x = zeros(3,nn)
  for i=1:length(nodeTags1)
    x[:,nodeTags1[i]] = xx1[:,i]
  end
  for i=1:length(nodeTags2)
    x[:,nodeTags2[i]] = xx2[:,i]
  end

  nInner,xInner = gmsh.model.mesh.getNodesForPhysicalGroup(1,1) # 1D groups, #1 is the inner circle
  nOuter,xOuter = gmsh.model.mesh.getNodesForPhysicalGroup(1,2) # 1D groups, #2 is the outer circle

  elemTypes1, elemTags1, elemConnectivity1 = gmsh.model.mesh.getElements(2,1)
  elemTypes2, elemTags2, elemConnectivity2 = gmsh.model.mesh.getElements(2,2)

  eConn1 = reshape(elemConnectivity1[1],6,:)
  eConn2 = reshape(elemConnectivity2[1],6,:)

  eConn = [eConn1 eConn2]
#  eC = convert(Array{Int64,2},eConn)   # for debugging

#  gmsh.write(outDir*"mixing.msh")
  gmsh.finalize()

 return x,eConn,eConn2, nInner,xInner, nOuter,xOuter
end


text:
# function tcm_evaluateKL(N, v, transaction_counts)
# 	M = size(transaction_counts,1)

# 	empirical_probs = transaction_counts ./ sum(transaction_counts, 2)

# 	KL = 0.0;

# 	for m in 1:M
# 		for i in 1:N
# 			if (transaction_counts[m,i] > 0)
# 				temp = transaction_counts[m,i] * log( v[m,i] / empirical_probs[m,i] )
# 				KL += temp
# 			end
# 		end
# 	end

# 	KL_avg = KL / sum(transaction_counts)

# 	return -KL_avg
# end

function tcm_evaluateKL(N, v, transaction_counts)
	M = size(transaction_counts,1)

	empirical_probs = transaction_counts ./ sum(transaction_counts, 2)

	KL_noinf = 0.0
	total_noinf_transactions = 0;

	for m in 1:M
		for i in 1:N
			if (transaction_counts[m,i] > 0)
				temp = transaction_counts[m,i] * log( v[m,i] / empirical_probs[m,i] )
				if (!isinf(temp))
					KL_noinf += temp
					total_noinf_transactions += transaction_counts[m,i]
				end
			end
		end
	end
	KL_noinf = -KL_noinf

	KL_noinf_avg = KL_noinf / total_noinf_transactions * 100

	return KL_noinf, total_noinf_transactions, KL_noinf_avg
end

# function tcm_evaluateKL_debug(N, v, transaction_counts)
# 	M = size(transaction_counts,1)

# 	empirical_probs = transaction_counts ./ sum(transaction_counts, 2)

# 	KL = 0.0;

# 	KL_matrix = zeros(M, N);

# 	for m in 1:M
# 		for i in 1:N
# 			if (transaction_counts[m,i] > 0)
# 				KL += transaction_counts[m,i] * log( v[m,i] / empirical_probs[m,i] )
# 				KL_matrix[m,i] = transaction_counts[m,i] * log( v[m,i] / empirical_probs[m,i] )
# 			end
# 		end
# 	end
# 	return -KL, KL_matrix
# end

ext: jl

max_stars_repo_licenses: MIT Unlicense

max_issues_repo_licenses: MIT Unlicense

max_forks_repo_licenses: MIT Unlicense


text:
using DifferentialEvolutionMCMC, Test, Random, Turing, Parameters, Distributions
using SequentialSamplingModels, LinearAlgebra
Random.seed!(9918)

dist = LNR(μ=[-2.,-2.,-3.,-3], σ=1.0, ϕ=.5)
data = rand(dist, 100)

function loglike(data, μ, σ, ϕ)
    dist = LNR(μ, σ, ϕ)
    return sum(logpdf.(dist, data))
end

function prior_loglike(μ, σ, ϕ)
    LL = 0.0
    LL += sum(logpdf.(Normal(0, 3), μ))
    LL += logpdf(truncated(Cauchy(0, 1), 0.0, Inf), σ)
    LL += logpdf(Uniform(0., min_rt), ϕ)
end

function sample_prior()
    LL = 0.0
    μ = rand(Normal(0, 3), 4)
    σ = rand(truncated(Cauchy(0, 1), 0.0, Inf))
    ϕ = rand(Uniform(0, min_rt))
    return as_union([μ,σ,ϕ])
end

min_rt = minimum(x -> x[2], data)

bounds = ((-Inf,0.),(1e-10,Inf),(0.,min_rt))
names = (:μ,:σ,:ϕ)

model = DEModel(;
    sample_prior,
    prior_loglike,
    loglike,
    data,
    names
)

de = DE(;sample_prior, bounds, burnin=2000, Np=24, n_groups=4)
n_iter = 4000
chains = sample(model, de, MCMCThreads(), n_iter, progress=true)

μ_de = describe(chains)[1][:,:mean]
σ_de = describe(chains)[1][:,:std]
rhat = describe(chains)[1][:,:rhat]

@model model1(data) = begin
    min_rt = minimum(x -> x[2], data)
    μ ~ MvNormal(zeros(4), I * 3^2)
    σ ~ truncated(Cauchy(0, 1), 0.0, Inf)
    ϕ ~ Uniform(0.0, min_rt)
    data ~ LNR(μ=μ, σ=σ, ϕ=ϕ)
end

chn = sample(model1(data), NUTS(1500, .85), 3000)
μ_nuts = describe(chn)[1][:,:mean]
σ_nuts = describe(chn)[1][:,:std]

@test all(isapprox.(rhat, fill(1.0, 6), atol=.05))
@test all(isapprox.(μ_nuts, μ_de, rtol=.05))
@test all(isapprox.(σ_nuts, σ_de, rtol=.05))


text:
action(::Type{PointerMovesEvent}) = PointerMoves
action(::Type{PointerLeavesWindowEvent}) = PointerLeavesWindow
action(::Type{PointerEntersWindowEvent}) = PointerEntersWindow
action(::Type{ExposeEvent}) = Expose
action(::Type{ResizeEvent}) = Resize
action(::Type{<:MouseEvent{A}}) where {A} = A
action(::Type{<:KeyEvent{A}}) where {A} = A
action(::Type{<:EventDetails{T}}) where {T} = action(T)
action(ed::EventDetails) = action(typeof(ed))
action(ed::EventData) = action(typeof(ed))

callback_symbol(::Type{Resize}) = :on_resize
callback_symbol(::Type{ButtonPressed}) = :on_mouse_button_pressed
callback_symbol(::Type{ButtonReleased}) = :on_mouse_button_released
callback_symbol(::Type{KeyPressed}) = :on_key_pressed
callback_symbol(::Type{KeyReleased}) = :on_key_released
callback_symbol(::Type{Expose}) = :on_expose
callback_symbol(::Type{PointerEntersWindow}) = :on_pointer_enter
callback_symbol(::Type{PointerLeavesWindow}) = :on_pointer_leave
callback_symbol(::Type{PointerMoves}) = :on_pointer_move

callback(callbacks::Callbacks, T) = getproperty(callbacks, callback_symbol(action(T)))

function execute_callback(wm::AbstractWindowManager, ed::EventDetails)
    execute_callback(callback(callbacks(wm, ed.win), typeof(ed)), (ed,))
end

function execute_callback(cb::Function, args::Tuple)
    cb(args...)
end

execute_callback(cb::Nothing, args::Tuple) = nothing

"""
    run(window_manager, mode; kwargs...)

Run an event loop associated with the `window_manager` in a synchronous or asynchronous fashion.
"""
Base.run(W::AbstractWindowManager, ::ExecutionMode) = not_implemented_for(W)


text:
targetarea = "target area: x=244..303, y=-91..-54"

part1(y) = abs(y) * (abs(y)-1)/2

function part2(xmin,xmax,ymin,ymax)
  t = 0
  for dx in 0:xmax+1, dy in ymin:-ymin
    x = 0
    y = 0
    vx = dx
    vy = dy
    while x <= xmax && y >= ymin
      if x >= xmin && y <= ymax
        t += 1
        break
      end
      x,y = (x + vx, y + vy)
      vy -= 1
      if vx > 0
        vx -= 1
      end
    end
  end
  t
end

@show part1(-91)
@show part2(244,303,-91,-54)

using BenchmarkTools
@btime part2(244,303,-91,-54)


text: squaresneeded(grains) = grains > 0 ? trunc( log2(grains)+1 ) : 0

max_stars_repo_name: UlrichBerntien/Codewars-Katas

max_issues_repo_name: UlrichBerntien/Codewars-Katas

max_forks_repo_name: UlrichBerntien/Codewars-Katas


text:
function f(x)
    x^2
end

@show f(42)

function goma(msg)
    println("Hi $msg goma")
end

gomagoma(msg) = println("Hi $msg gomagoma")

gomagomakyukkyu = msg -> println("Hi $msg gomagomakyukkyu")

goma("kyui")
gomagoma("kyui")
gomagomakyukkyu("kyui")

A = rand(3,3)
@show f(A)

# Mutating vs. non-mutating functions
#By convention, functions followed by ! alter their contents and functions lacking ! do not.
#For example, let's look at the difference between `sort` and `sort!`.

v = [3, 5, 2]
@show sort(v)
@show v
@show sort!(v)
@show v

#=
`map` is a "higher-order" function
in Julia that takes a function as one of its output arguments.
=#

map(f,[1,2,3])

# this will give us an output array where the function `f` has been applied to all elements of `[1,2,3]`

@show map(f, [1, 2, 3])
@show [f(1), f(2), f(3)]

# we could have
@show map(x-> x^3, [1, 2, 3])

@show broadcast(f, [1,2,3])
@show f.([1,2,3])

A = [i+3j for j in 0:2, i in 1:3]

@show A
@show f(A)
@show f.(A)

@show A .+ 2 .* f.(A) ./ A
@show broadcast(x-> x+2f(x)/x, A)

max_stars_repo_name: terasakisatoshi/juliaExer

max_issues_repo_name: terasakisatoshi/juliaExer

max_forks_repo_name: terasakisatoshi/juliaExer


text:
function HaloXZPlaneCrossingDetector(arg0::jdouble, arg1::jdouble)
    return HaloXZPlaneCrossingDetector((jdouble, jdouble), arg0, arg1)
end

function g(obj::HaloXZPlaneCrossingDetector, arg0::SpacecraftState)
    return jcall(obj, "g", jdouble, (SpacecraftState,), arg0)
end


text:
### A Pluto.jl notebook ###
# v0.12.11

using Markdown
using InteractiveUtils

# ╔═╡ 105d9a64-0fd3-11eb-192d-d37c599b9dc2
using Pkg, DrWatson

# ╔═╡ 1341e8f2-0fd3-11eb-1511-47cd22733425
begin
	#@quickactivate "StatisticalRethinkingStan"
	using StructuralCausalModels
	using StatisticalRethinking
end

# ╔═╡ 97cd0aea-0fd1-11eb-0521-8903ecc73a1e
md"## Dag-06-02.jl"

# ╔═╡ 1342211e-0fd3-11eb-0fb5-cd39a62203a6
begin
	df = CSV.read(sr_datadir("WaffleDivorce.csv"), DataFrame; delim=';')
	df = DataFrame(
	  :s => df[:, :South],
	  :a => df[:, :MedianAgeMarriage],
	  :m => df[:, :Marriage],
	  :w => df[:, :WaffleHouses],
	  :d => df[:, :Divorce]
	)
end;

# ╔═╡ 1342b30e-0fd3-11eb-2ccb-394372532970
Text(precis(df; io=String))

# ╔═╡ 13541126-0fd3-11eb-0529-e762f8366698
StatsPlots.cornerplot(Array(df), label=names(df))

# ╔═╡ 8c2f36b8-0fd1-11eb-1400-e7ca54fe97f2
begin
	d = OrderedDict(
	  [:w, :m, :a] => :s,
	  :d => [:a, :w, :m],
	  :m => [:a]
	);

	dag6_2 = DAG("dag6_2", d, df=df)
end

# ╔═╡ 4bbb315c-0fd3-11eb-0b32-f70ce8b38cd3
begin
	fname = mktempdir() * "/dag6_2.dot"
	to_graphviz(dag6_2, fname)
	Sys.isapple() && run(`open -a GraphViz.app $(fname)`)
end;

# ╔═╡ 4bbb7266-0fd3-11eb-060f-f1a72f82ca30
dag6_2.s

# ╔═╡ 4bbc19f0-0fd3-11eb-30b6-7f8cd384b710
Text(pluto_string(basis_set(dag6_2)))

# ╔═╡ 4bc968da-0fd3-11eb-31ab-7133a99fb3ed
t = shipley_test(dag6_2)

# ╔═╡ 4bc9fb06-0fd3-11eb-1c5c-f91ca46cb479
begin
	f = :w; s = :d;
	e = d_separation(dag6_2, [f], [s], c=[:m, :a])
end

# ╔═╡ 4bd7c590-0fd3-11eb-2b79-c9560ef98ee4
ap = all_paths(dag6_2, f, s)

# ╔═╡ 4bd87064-0fd3-11eb-276d-ed4ff376be3d
bp = backdoor_paths(dag6_2, ap, f)

# ╔═╡ 4be6d776-0fd3-11eb-3b49-69805f91a0b8
adjustmentsets = adjustment_sets(dag6_2, :w, :d)

# ╔═╡ 4be77730-0fd3-11eb-085b-fbc552a4e865
md"## End of dag-06-02.jl"

# ╔═╡ Cell order:
# ╠═97cd0aea-0fd1-11eb-0521-8903ecc73a1e
# ╠═105d9a64-0fd3-11eb-192d-d37c599b9dc2
# ╠═1341e8f2-0fd3-11eb-1511-47cd22733425
# ╠═1342211e-0fd3-11eb-0fb5-cd39a62203a6
# ╠═1342b30e-0fd3-11eb-2ccb-394372532970
# ╠═13541126-0fd3-11eb-0529-e762f8366698
# ╠═8c2f36b8-0fd1-11eb-1400-e7ca54fe97f2
# ╠═4bbb315c-0fd3-11eb-0b32-f70ce8b38cd3
# ╠═4bbb7266-0fd3-11eb-060f-f1a72f82ca30
# ╠═4bbc19f0-0fd3-11eb-30b6-7f8cd384b710
# ╠═4bc968da-0fd3-11eb-31ab-7133a99fb3ed
# ╠═4bc9fb06-0fd3-11eb-1c5c-f91ca46cb479
# ╠═4bd7c590-0fd3-11eb-2b79-c9560ef98ee4
# ╠═4bd87064-0fd3-11eb-276d-ed4ff376be3d
# ╠═4be6d776-0fd3-11eb-3b49-69805f91a0b8
# ╟─4be77730-0fd3-11eb-085b-fbc552a4e865


text:
# # This is a title

## This is a comment
### This is also a comment

# # [This is another title](@id custom_id)

# This is a description

y = 2+2


text:
"""
```
Module      : FinanceLib.Derivatives
Description : Implement Derivatives modules for the FinanceLib library
Copyright   : (c) 2022 Kishaloy Neogi
License     : MIT
Maintainer  : Kishaloy Neogi
Email       : nkishaloy@yahoo.com
```
The module describes the base modules of Derivatives like .

You may see the github repository at <https://github.com/n-kishaloy/FinanceLib.jl>
"""
module Derivatives

include("Forwards.jl")
include("Options.jl")

end


text:
@require "../"

suite("it should pretty milliseconds") do
  val = pretty(500)
  @test contains(val, "ms")
end

suite("it should pretty seconds") do
  val = pretty(1203)
  @test contains(val, "s")
  @test contains(val, ".")
end

suite("it should pretty full time") do
  val = pretty(12034375678)
  println(val)
  @test contains(val, "d")
  @test contains(val, "h")
  @test contains(val, "m")
  @test contains(val, "s")
end

max_stars_repo_name: queckezz/ms-pretty

max_issues_repo_name: queckezz/ms-pretty

max_forks_repo_name: queckezz/ms-pretty


text:
abstract type AbstractGPLayer <: AbstractGP end;

const jitt = 1e-5

struct SVGPLayer{GPType,TV<:AbstractVector{<:GPType}} <: AbstractGPLayer
    dim::Int
    gps::TV
end

function SVGPLayer(
    dim::Int, μ::AbstractVector, L::AbstractMatrix, Z::AbstractVector, kernel::Kernel, μ₀
)
    gps = [
        SVGP_Base(length(μ), copy(μ), copy(L), GP(deepcopy(μ₀), deepcopy(kernel)), deepcopy(Z)) for _ in 1:dim
    ]
    return SVGPLayer(dim, gps)
end

Base.length(l::SVGPLayer) = l.dim
Base.getindex(l::SVGPLayer, i::Int) = getindex(l.gps, i)
Base.iterate(l::SVGPLayer) = iterate(l.gps)
Base.iterate(l::SVGPLayer, state::Any) = iterate(l.gps, state)

bsqrt(v::AbstractVector) = sqrt.(v)

## Return the parametrization m + eps * sqrt(S)
function propagate(l::AbstractGPLayer, samples::AbstractVector)
    m_v_s = [mean_and_var(gp, samples) for gp in l]
    out =
        mapreduce(first, hcat, m_v_s) +
        randn(length(samples), l.dim) .* mapreduce(bsqrt ∘ last, hcat, m_v_s)
    return RowVecs(out)
end

function propagate(l::AbstractGPLayer, sample::AbstractArray{<:Real})
    m_v_s = [mean_and_var(gp, sample) for gp in l]
    return first(m_v_s) .+ randn(l.dim) .* sqrt.(last(m_v_s))
end

# mu(l::AbstractGPLayer,x) = reduce(hcat,mu(gp,x) for gp in l.gps)
function Statistics.mean(l::AbstractGPLayer, x::AbstractVector)
    return mapreduce(Base.Fix2(mean, x), hcat, l)
end
Statistics.var(l::AbstractGPLayer, x) = mapreduce(Base.Fix2(var, x), hcat, l)
Statistics.cov(l::AbstractGPLayer, x) = cov.(l, Ref(x))

kl_divergence(l::AbstractGPLayer) = sum(kl_divergence, l)

abstract type AbstractGPBase end;

"""
    SVGP_Base

Corresponds to one node in the Deep GP
"""
struct SVGP_Base{
    T,Tμ<:AbstractVector{T},TL<:AbstractMatrix{T},Tgp<:AbstractGP,TZ<:AbstractVector
} <: AbstractGPs.AbstractGP
    dim::Int
    μ::Tμ
    L::TL
    prior::Tgp
    Z::TZ
end

function SVGP_Base{T}(
    dim, Z::AbstractVector, kernel=SqExponentialKernel(), μ₀=AbstractGPs.ZeroMean()
) where {T}
    return SVGP_Base(dim, zeros(T, dim), diagm(ones(T, dim)), GP(μ₀, kernel), Z)
end

function ParameterHandling.flatten(x::SVGP_Base{T}) where {T}
    θprior, build_prior = flatten(x.prior)
    θZ, build_Z = flatten(x.Z)
    nZ = length(θZ)
    θ = vcat(x.μ, vec(x.L), θZ, θp)
    function unflatten_svgp_base(θ)
        μ = θ[1:x.dim]

        SVGP_Base{T}(x.dim, μ)
    end
end

"""
    kappa(gp::SVGP_Base, x::AbstractVector)

"""
function kappa(gp::SVGP_Base, x::AbstractVector, K::AbstractMatrix=cov(gp.prior, gp.Z))
    ## Return the K_XZ K_ZZ^{-1}
    return cov(gp.prior, x, gp.Z) / K
end

function Statistics.mean(
    gp::SVGP_Base,
    x::AbstractVector,
    K::AbstractMatrix=cov(gp.prior, gp.Z),
    κ::AbstractMatrix=kappa(gp, x, K),
)
    return κ * gp.μ - mean(gp.prior, x)
end

function Statistics.var(
    gp::SVGP_Base,
    x::AbstractVector,
    K::AbstractMatrix=cov(gp.prior, gp.Z),
    κ::AbstractMatrix=kappa(gp, x, K),
)
    return var(gp.prior, x) - opt_diag(κ * (K - gp.L * gp.L'), κ)
end
function Statistics.cov(
    gp::SVGP_Base,
    x::AbstractVector,
    K::AbstractMatrix=cov(gp.prior, gp.Z),
    κ::AbstractMatrix=kappa(gp, x, K),
)
    return cov(gp.prior, x) - κ * (K - gp.L * gp.L') * κ'
end
function StatsBase.mean_and_var(gp::SVGP_Base, x::AbstractVector)
    K = cov(gp.prior, gp.Z)
    κ = kappa(gp, x, K)
    return mean(gp, x, K, κ), var(gp, x, K, κ)
end

function kl_divergence(gp::SVGP_Base)
    K = cov(gp.prior, gp.Z)
    return 0.5 * (
        -2logdet(gp.L) +
        logdet(K) +
        opt_trace(inv(K), gp.L * gp.L') +
        dot(gp.μ, K \ (gp.μ)) - length(gp.μ)
    ) #WARNING removed μ₀
end #WARNING removed μ₀


text:
mutable struct GR4J

    X1::Float64     # Capacity of the production store (mm)
    X2::Float64     # Water exchange coefficient (mm/day)
    X3::Float64     # Capacity of the routing store (mm)
    X4::Float64     # Time base of the unit hydrograph (days)

    Sp::Float64     # Level in production store (mm)
    Sr::Float64     # level in routing store (mm)

    UH1::Array{Float64,1}
    UH2::Array{Float64,1}

    oUH1::Array{Float64,1}
    oUH2::Array{Float64,1}

    function GR4J(X1::Float64, X2::Float64, X3::Float64, X4::Float64,
                  Sp::Float64, Sr::Float64)
        X1 >= 0.0 || throw(DomainError(X1, "X1 should have non-negative value"))
        X3 >= 0.0 || throw(DomainError(X3, "X3 should have non-negative value"))
        X4 >= 0.0 || throw(DomainError(X4, "X1 should have non-negative value"))
        Sp <= X1  || throw(DomainError(Sp, "Sp should be less than or equal to X1, $X1"))
        Sr <= X3  || throw(DomainError(Sr, "Sr should be less than or equal to X3, $X3"))

        nUH1 = ceil(Int32, X4)
        nUH2 = ceil(Int32, 2.0 * X4)

        UH1 = zeros(Float64, nUH1)
        UH2 = zeros(Float64, nUH2)

        oUH1 = [SS1(i, X4) - SS1(i - 1, X4) for i in 1:nUH1]
        oUH2 = [SS2(i, X4) - SS2(i - 1, X4) for i in 1:nUH2]

        new(X1, X2, X3, X4, Sp, Sr, UH1, UH2, oUH1, oUH2)
    end
end

function GR4J()
    GR4J(350.0, 0.0, 40.0, 0.5, 0.0, 0.0)
end

function GR4J(X1::Float64, X2::Float64, X3::Float64, X4::Float64)
    GR4J(X1, X2, X3, X4, 0.0, 0.0)
end

function GR4J(m::GR4J)
    model = GR4J(m.X1, m.X2, m.X3, m.X4, m.Sp, m.Sr)
    model.UH1[:] = m.UH1
    model.UH2[:] = m.UH2
    return model
end

function GR4J(d::Dict)
    model = GR4J(d[:X1], d[:X2], d[:X3], d[:X4], d[:Sp], d[:Sr])
    model.UH1[:] = d[:UH1]
    model.UH2[:] = d[:UH2]
    return model
end

function ==(a::GR4J, b::GR4J)
    x = a.X1 == b.X1 && a.X2 == b.X2 && a.X2 == b.X2 && a.X2 == b.X2
    y = a.Sp == b.Sp && a.Sr == b.Sr
    z = all(a.UH1 .== b.UH1) && all(a.UH2 .== b.UH2)

    return x && y && z
end

function show(io::IO, model::GR4J)
    println("GR4J Model:")
    println(io, "X1 = $(model.X1)")
    println(io, "X2 = $(model.X2)")
    println(io, "X3 = $(model.X3)")
    println(io, "X4 = $(model.X4)")
    println(io, "Sp = $(model.Sp)")
    println(io, "Sr = $(model.Sr)")
    return
end

function Base.setproperty!(model::GR4J, field::Symbol, value)
    if field == :X1
        value >= 0.0 || throw(DomainError(value, "X1 should have non-negative value"))
    elseif field == :X3
        value >= 0.0 || throw(DomainError(value, "X3 should have non-negative value"))
    elseif field == :X4
        value >= 0.0 || throw(DomainError(value, "X4 should have non-negative value"))
    elseif field == :Sp
        value <= model.X1  || throw(DomainError(value, "Sp should be less than or equal to X1, $model.X1"))
    elseif field == :Sr
        value <= model.X3  || throw(DomainError(value, "Sr should be less than or equal to X3, $model.X3"))
    end

    setfield!(model, field, value)
end

function stash(model::GR4J)::Dict
    return Dict(:X1=>model.X1, :X2=>model.X2, :X3=>model.X3, :X4=>model.X4,
                :Sp=>model.Sp, :Sr=>model.Sr,
                :UH1=>copy(model.UH1), :UH2=>copy(model.UH2))
end

function simulate(model::GR4J, P::Array{Float64,1}, PET::Array{Float64,1})
    if size(P) != size(PET)
        throw(DimensionMismath("P and PET have different sizes"))
    end

    Q = zeros(Float64, size(P))
    AET = zeros(Float64, size(P))
    for i in 1:length(P)
        Q[i], AET[i] = simulate(model, P[i], PET[i])
    end
    return Q, AET
end

function simulate(model::GR4J, P::Float64, PET::Float64)
    X1 = model.X1
    X2 = model.X2
    X3 = model.X3
    X4 = model.X4

    Sp = model.Sp
    Sr = model.Sr

    UH1 = model.UH1
    UH2 = model.UH2

    oUH1 = model.oUH1
    oUH2 = model.oUH2

    Rp = Sp / X1

    # Production store:
    if P >= PET
        ES = 0.0
        AET = PET
        WS = (P - PET) / X1
        if (WS > 13.0) WS = 13.0 end
        TWS = tanh(WS)

        PS = X1 * (1.0 - Rp * Rp) * TWS / (1.0 + Rp * TWS)
        PR = P - PET - PS
    else
        WS = (PET - P) / X1
        if (WS > 13.0) WS = 13.0 end
        TWS = tanh(WS)

        ES = Sp * (2.0 - Rp) * TWS / (1.0 + (1.0 - Rp) * TWS)
        AET = ES + P
        PS = 0.0
        PR = 0.0
    end
    Sp = Sp - ES + PS

    @assert Sp >= 0.0

    Rp = Sp / X1

    @debug "PS: $PS"
    @debug "Es: $ES"
    @debug "Sp/X1: $Rp"

    # Percolation:
    r = Rp / 2.25
    PERC = Sp - Sp / sqrt(sqrt(1.0 + r * r * r * r))
    Sp = Sp - PERC
    @assert Sp >= 0.0
    PR = PR + PERC

    @debug "PERC: $PERC"
    @debug "Sp/X1: $(Sp / X1)"
    @debug "PR: $PR"

    B = 0.9
    for i in 1:(length(UH1) - 1)
        UH1[i] = UH1[i + 1] + oUH1[i] * B * PR
    end
    UH1[end] = oUH1[end] * B * PR

    for i in 1:(length(UH2) - 1)
        UH2[i] = UH2[i + 1] + oUH2[i] * (1.0 - B) * PR
    end
    UH2[end] = oUH2[end] * (1.0 - B) * PR

    @debug "oUH1: $oUH1"
    @debug "oUH2: $oUH2"
    @debug "UH1: $UH1"
    @debug "UH2: $UH2"

    # Water exchange:
    Rr = Sr / X3
    ECH = X2 * Rr * Rr * Rr * sqrt(Rr)
    @debug "ECH(F): $ECH"

    # QR calculation [routing store]:
    # Different from MS Excel. In Excel, no 0.9 *
    # Also ECH added not multiplied
    Sr = max(0.0, Sr + UH1[1] + ECH)
    Rr = Sr / X3
    @debug "Sr/X3: $Rr"
    QR = Sr - Sr / sqrt(sqrt(1.0 + Rr * Rr * Rr * Rr))
    @debug "QR: $QR"
    Sr = Sr - QR
    @assert Sr >= 0.0
    @debug "Sr/X3: $(Sr / X3)"
    # QD calculation:
    QD = max(0.0, UH2[1] + ECH)
    @debug "QD: $QD"
    # Total streamflow:
    Q = QR + QD
    @debug "Q: $Q"

    model.Sp = Sp
    model.Sr = Sr

    return Q, AET

end

function SS1(I, X4)
    if I <= 0
        return 0.0
    elseif I < X4
        r = I / X4
        return r * r * sqrt(r)
    else
        return 1.0
    end
end

function SS2(I, X4)
    if I <= 0
        return 0.0
    elseif I < X4
        r = I / X4
        return 0.5 * r * r * sqrt(r)
    elseif I < 2 * X4
        r = 2.0 - I / X4
        return 1.0 - 0.5 * r * r * sqrt(r)
    else
        return 1.0
    end
end


text:
#= Molecules
Data types for organic molecules.

OxygenMol implements a mutable molecule type, using weighted adjacency lists to denote bonds.
A bond order of 1.5 refers to an aromatic bond.
Hydrogens are implicit

TODO: Implement a static molecule type
=#

import AutoHashEquals: @auto_hash_equals

abstract type Molecular end

@auto_hash_equals mutable struct OxygenMol <: Molecular
    atoms::Array{OxygenAtom,1}
    adj::Array{Array{Tuple{Int,Float64},1},1}
end

"""
    OxygenMol

Mutable molecule type.

Represents molecules using an array of atoms and a weighted adjacency list to represent bonds.
"""
OxygenMol

OxygenMol(atoms::Array{Int,1}) = OxygenMol(map(number -> OxygenAtom(number), atoms), [[] for _ in 1:length(atoms)])

OxygenMol(atoms::Array{String,1}) = OxygenMol(map(symbol -> OxygenAtom(symbol), atoms), [[] for _ in 1:length(atoms)])


text:
@testset "Sampling" begin
  γ = GaussianVariogram()
  seg = Segment((0.,0.),(1.,1.))
  ps = Variography._sample(γ, seg)
  @test all(p -> Point(0.,0.) ⪯ p ⪯ Point(1.,1.), ps)
  @test length(ps) == 3

  γ = GaussianVariogram()
  quad = Quadrangle((0.,0.), (1.,0.), (1.,1.), (0.,1.))
  ps = Variography._sample(γ, quad)
  @test all(p -> Point(0.,0.) ⪯ p ⪯ Point(1.,1.), ps)
  @test length(ps) == 3*3

  γ = GaussianVariogram()
  hex = Hexahedron((0.,0.,0.), (1.,0.,0.), (1.,1.,0.), (0.,1.,0.),
                   (0.,0.,1.), (1.,0.,1.), (1.,1.,1.), (0.,1.,1.))
  ps = Variography._sample(γ, hex)
  @test all(p -> Point(0.,0.,0.) ⪯ p ⪯ Point(1.,1.,1.), ps)
  @test length(ps) == 3*3*3

  # regularization properties
  γ = GaussianVariogram()
  u = Point(0., 0.)
  v = Point(1., 0.)
  U = Quadrangle((-0.5,-0.5), (0.5,-0.5), (0.5,0.5), (-0.5,0.5))
  V = Quadrangle((0.5,-0.5), (1.5,-0.5), (1.5,0.5), (0.5,0.5))
  @test 0 < γ(U, v) < γ(u, v) < 1
  @test 0 < γ(u, V) < γ(u, v) < 1
  @test isapprox(γ(U, v), γ(u, V), atol=1e-1)
  @test 0 < γ(U, V) < γ(U, v) < 1
  @test 0 < γ(U, V) < γ(u, V) < 1

  # deterministic samples in arbitrary geometries
  γ = GaussianVariogram()
  G = PolyArea((0.,0.), (0.5,-1.5), (1.,0.), (1.5,0.5),
               (1.,1.), (0.5,1.5), (-0.5,0.5), (0.,0.))
  ps1 = Variography._sample(γ, G)
  ps2 = Variography._sample(γ, G)
  @test ps1 == ps2

  # samples with nugget effect model
  γ = NuggetEffect()
  h = Hexahedron((0.,0.,0.), (1.,0.,0.), (1.,1.,0.), (0.,1.,0.),
                 (0.,0.,1.), (1.,0.,1.), (1.,1.,1.), (0.,1.,1.))
  ps = Variography._sample(γ, h) |> collect
  @test length(ps) == 3*3*3
end


text:
using Test, Dates, Mocking

Mocking.activate()

@testset "TESTSETS: Test conversion of datestring to date time" begin
    the_last_year = DateTime(2020, 1, 1, 0, 0, 0) # Begining of the end

    @testset "CASE: Test parsing of a datestring without milliseconds" begin
        valid_20_ch_datestr = "2020-01-01T00:00:00"
        @test TCX.convertToDateTime(valid_20_ch_datestr) == the_last_year
        @test TCX.convertToDateTime(valid_20_ch_datestr * "Z") == the_last_year
    end

    for i in 1:3
        @testset "CASE: Test parsing of a string with $(i) ms digits" begin
            valid_datestr = "2020-01-01T00:00:00." * ("0" ^ i)
            @test TCX.convertToDateTime(valid_datestr) == the_last_year
            @test TCX.convertToDateTime(valid_datestr * "Z") == the_last_year
        end
    end

    @testset "CASE: Test parsing an improperly formatted string" begin
        invalid_datestr = "01-01-2020"
        try
            TCX.convertToDateTime(invalid_datestr)
        catch err
            @test err isa ArgumentError
            @test occursin(
                "'$(invalid_datestr)' is improperly formatted.",
                sprint(showerror, err)
            )
        end
    end

    @testset "CASE: Test successfully catching and recovering from an argument error" begin
        datestr = "2020-05-20T21:58:03Z"
        error = ArgumentError("I'm being unreasonably difficult")
        patch = @patch DateTime(dt::AbstractString, format::AbstractString) = fn(throw(error))
        apply(patch) do
            datetime = TCX.convertToDateTime(datestr)
            @test 3 == second(datetime)
            @test 58 == minute(datetime)
            @test 21 == hour(datetime)
            @test 20 == day(datetime)
            @test 5 == month(datetime)
            @test 2020 == year(datetime)
        end
    end

    @testset "CASE: Test that an unexpected error is not silenced" begin
        datestr = "2020-05-20T21:58:03Z"
        error = ErrorException("Oh boy now something else is wrong!")
        patch = @patch DateTime(dt::AbstractString, format::AbstractString) = fn(throw(error))
        apply(patch) do
            @test_throws ErrorException TCX.convertToDateTime(datestr)
        end
    end
end

@testset "TESTSETS: Test warn on TCX error" begin
    @testset "CASE: NOT a TCX error" begin
        real_tcx = "let's pretend this is a real TCX string"
        @test_logs TCX.warn_on_tcx_error(TCX.OK, real_tcx, false)
    end

    @testset "CASE: Is a TCX error on a document" begin
        path = "path/to/doc"
        @test_logs(
            (:warn, r"Invalid TCX.+document:"),
            TCX.warn_on_tcx_error(TCX.CLIENT_TCX_ERROR, path, true)
        )
    end

    @testset "CASE: Is a TCX error on a string" begin
        string = "<NotTCX>Derp!</NotTCX>"
        @test_logs(
            (:warn, "Invalid TCX string: <NotTCX>Derp!</NotTCX>"),
            TCX.warn_on_tcx_error(TCX.CLIENT_TCX_ERROR, string, false)
        )
    end
end


text:
"""
Generate examples with known number of leading zeros, for test
purposes only (no production code).
"""
module CLZ
import Random: MersenneTwister

function generate(T = UInt64, n = 9, seed = 0)
    nums = rand(MersenneTwister(seed), T, n)
    bitlen = 8 * sizeof(T)
    ONE = one(T) << (bitlen - 1)
    @assert bitstring(ONE)[1] == '1'
    @assert all(bitstring(ONE)[i] == '0' for i=2:bitlen)
    nums .|= ONE    # all start by ONE
    for i in 1:n
        nums[i] >>= 2i^2 - 5i + 3
    end
    nums[end-2] = zero(T)
    nums[end-1] = +one(T)
    nums[end-0] = -one(T)
    nums
end

nums = generate(UInt64, 9)
expect = leading_zeros.(nums)

nums32 = generate(UInt32, 8)
# show(reinterpret.(Int32, (generate(UInt32, 8, 0)))
end

max_stars_repo_name: EQt/graphidx

max_issues_repo_name: EQt/graphidx

max_forks_repo_name: EQt/graphidx


text:
const data = split("Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can.")
d = Dict()
const f = [1, 5, 6, 7, 8, 9, 15, 16, 19]

for i = 1:length(data)
  if i in f
    d[data[i][1]] = i
  else
    d[data[i][1:2]] = i
  end
end

println(d)

# Dictはjuliaの連想配列


text:
module Consts

export MPI_Aint, MPI_Count, MPI_Offset, MPI_Status,
    MPI_Comm, MPI_Datatype, MPI_Errhandler, MPI_File, MPI_Group,
    MPI_Info, MPI_Message, MPI_Op, MPI_Request, MPI_Win

import MPIPreferences
import ..libmpi, ..libmpiconstants

const initexprs = Any[]

"""
    @const_ref name T expr

Defines an constant binding
```julia
const name = Ref{T}()
```
and adds a hook to execute
```julia
name[] = expr
```
at module initialization time.
"""
macro const_ref(name, T, expr)
    push!(initexprs, :($name[] = $expr))
    :(const $(esc(name)) = Ref{$T}())
end

@static if MPIPreferences.abi == "MPICH"
    include("mpich.jl")
elseif MPIPreferences.abi == "OpenMPI"
    include("openmpi.jl")
elseif MPIPreferences.abi == "MicrosoftMPI"
    include("microsoftmpi.jl")
elseif MPIPreferences.abi == "MPItrampoline"
    include("mpitrampoline.jl")
elseif MPIPreferences.abi == "HPE MPT"
    include("mpt.jl")
else
    error("Unknown MPI ABI $(MPIPreferences.abi)")
end

# Initialize the ref constants from the library.
# This is not `Consts.__init__`, as it should be called _after_
# `dlopen` to ensure the library is opened correctly.
@eval function init_consts()
    $(Expr(:block, initexprs...))
end

# since this is called by invokelatest, it isn't automatically precompiled
precompile(init_consts, ())

end


text:
# AUTO GENERATED FILE - DO NOT EDIT

export uishell

"""
    uishell(;kwargs...)

An UIShell component.
UIShell is a default layout with the header and a sidebar
Keyword arguments:
- `id` (String; optional): Element id
- `name` (String; required): Platform Name
- `sidebarItems` (optional): Items of the sidebar. sidebarItems has the following type: Array of lists containing elements 'name', 'url'.
Those elements have the following types:
  - `name` (String; optional)
  - `url` (String; optional)s
- `headerItems` (optional): Items of the header. headerItems has the following type: Array of lists containing elements 'name', 'url'.
Those elements have the following types:
  - `name` (String; optional)
  - `url` (String; optional)s
- `loading_state` (optional): Object that holds the loading state object coming from dash-renderer. loading_state has the following type: lists containing elements 'is_loading', 'prop_name', 'component_name'.
Those elements have the following types:
  - `is_loading` (Bool; optional): Determines if the component is loading or not
  - `prop_name` (String; optional): Holds which property is loading
  - `component_name` (String; optional): Holds the name of the component that is loading
"""
function uishell(; kwargs...)
        available_props = Symbol[:id, :name, :sidebarItems, :headerItems, :loading_state]
        wild_props = Symbol[]
        return Component("uishell", "UIShell", "dash_carbon_components", available_props, wild_props; kwargs...)
end

max_stars_repo_name: Matheus-Rangel/dash-carbon-components

max_issues_repo_name: Matheus-Rangel/dash-carbon-components

max_forks_repo_name: Matheus-Rangel/dash-carbon-components


text:
module SixDof

using LinearAlgebra, DifferentialEquations, Distances
using ...Utils, ...Types
include("aerodynamic_coeff.jl")
export trajectorySixDof!, QEfinderSixDof!, iniCondSixDof

function sixdof(du,u,p,t)
    calibre,m,Ixx,It, ω_bar, g₀, Rz, target,dist = p

    λ0 = u[1]
    λ1 = u[2]
    λ2 = u[3]
    λ3 = u[4]

    U = u[5]
    V = u[6]
    W = u[7]

    P = u[8]
    Q = u[9]
    R = u[10]

    X₁ = u[11]
    X₂ = u[12]
    X₃ = u[13]

    V_bar = [U, V, W]
    X_bar = [X₁, X₂, X₃]

    α = atan(W/U)
    β = asin(V/norm(V_bar))
    αt = asin(sqrt((sin(α)*cos(β))^2+(sin(β))^2))
    δ = sqrt((sin(α)*cos(β))^2+(sin(β))^2)

    mach = Utils.machNumber(norm(V_bar),-u[13])
    CD0 = CD0_inter(mach)
    CDδ2 = CDδ2_inter(mach)
    CD = CD0 + CDδ2 * δ^2
    CLα0 = Cl_α0_inter(mach)
    CLα2 = Cl_α2_inter(mach)
    CLα = CLα0 + CLα2 * δ^2
    Cx0 = CD0
    Cx2 = CDδ2
    Cna = CLα#CD + cos(αt)*CLα
    Cypa = CN_pα_inter(mach,(rad2deg(αt))^2)
    Cldd = 0.0
    Clp = Cl_p_inter(mach)
    CMα0 = CM_α0_inter(mach)
    CMα2 = CM_α2_inter(mach)
    Cma = CMα0 +CMα2 * δ^2
    Cmq = CM_q_plus_CM_α_inter(mach)
    Cnpa =  CM_pα_inter(mach,(rad2deg(αt))^2)

    Ωx = 2*R*(λ1*λ3-λ0*λ2)/(λ0^2-λ1^2-λ2^2+λ3^2)

    ρ = Utils.density(-u[13])
    S = pi*(calibre^2)/4

    g = Utils.gravity(-u[13])

    gx = 2*(λ1*λ3-λ0*λ2)*g
    gy = 0.0
    gz = (λ0^2-λ1^2-λ2^2+λ3^2)*g

    FGx = - g₀*X₁/Rz
    FGy = - g₀*X₂/Rz
    FGz = g₀*(1+2*X₃/Rz)

    FG = [gx, gy, gz]

    FAx = -1/2*ρ*(norm(V_bar))^2*S*(Cx0 + Cx2*(V^2+W^2)/(norm(V_bar))^2)#Cx
    FAy = -1/2*ρ*(norm(V_bar))^2*S*(CLα*V/norm(V_bar))#(Cna * V/norm(V_bar)
    FAz = -1/2*ρ*(norm(V_bar))^2*S*(CLα*W/norm(V_bar))#(Cna * W/norm(V_bar) #Cz

    FMx =0.0
    FMy = 1/2*ρ*(norm(V_bar))^2*S* (P*calibre/(2*norm(V_bar))*Cypa*W/(norm(V_bar)))#Cy
    FMz = -1/2*ρ*(norm(V_bar))^2*S* (P*calibre/(2*norm(V_bar))*Cypa*V/(norm(V_bar)))

    T = T_MatrixQ(λ0, λ1, λ2, λ3)

    v_bar = T*V_bar
    FC = -2*cross(ω_bar,v_bar)

    FCp = transpose(T)*FC
    FGp = transpose(T)*FG
    FGp[2] = 0.0
    FCx = FCp[1]
    FCy = FCp[2]
    FCz = FCp[3]

    Fx = FAx +FMx + FCx
    Fy = FAy + FMy + FCy
    Fz = FAz + FMz + FCz

    L = 1/2*ρ*(norm(V_bar))^2* S *calibre*(Cldd + P*calibre/(2*norm(V_bar))*Clp)#Cl
    M = 1/2*ρ*(norm(V_bar))^2* S *calibre*( Cma*W/norm(V_bar)+Q*calibre/(2*norm(V_bar))*Cmq+P*calibre/(2*norm(V_bar))*Cnpa*V/norm(V_bar))#Cm
    N = 1/2*ρ*(norm(V_bar))^2* S *calibre*(-Cma*V/norm(V_bar)+R*calibre/(2*norm(V_bar))*Cmq+P*calibre/(2*norm(V_bar))*Cnpa*W/norm(V_bar))#Cq

    ϵw = norm([λ0,λ1,λ2,λ3])-1

    du[1] = -1/2*(Q*λ2+R*λ3/(λ0^2-λ1^2-λ2^2+λ3^2))-ϵw*λ0 #λ0p
    du[2] = -1/2*(Q*λ3+R*λ2/(λ0^2-λ1^2-λ2^2+λ3^2))-ϵw*λ1  #λ1p
    du[3] = 1/2*(Q*λ0+R*λ1/(λ0^2-λ1^2-λ2^2+λ3^2))-ϵw*λ2  #λ2p
    du[4] = 1/2*(Q*λ1+R*λ0/(λ0^2-λ1^2-λ2^2+λ3^2))-ϵw*λ3  #λ3p

    du[5] = FG[1]+Fx/m-Q*W+R*V #Up
    du[6] = FG[2]+Fy/m-R*U+Ωx*W  # Vp
    du[7] = FG[3]+Fz/m-Ωx*V+Q*U  # Wp

    du[8] = L/Ixx #Pp
    du[9] = 1/It * (M-Ixx*R*P+It*R*Ωx)#Qp
    du[10] = 1/It * (N+Ixx*Q*P-It*Q*Ωx)#Rp

    du[11] = v_bar[1] #x
    du[12] = v_bar[2] #y
    du[13] = v_bar[3] #z

end
function condition(u,t,integrator) # Event when event_f(u,t) == 0

  integrator.p[8][1]-u[11]

end

function timeFuze(u,t,integrator)

    close=(euclidean([u[11],u[12],u[13]],integrator.p[8])-integrator.p[9])-1e-6

    return close
end

miss(u,t,integrator) = u[13]
affect_miss!(integrator) = terminate!(integrator)

affect!(integrator) = terminate!(integrator)
affect_tf!(integrator) = terminate!(integrator)

function iniCondSixDof(θ::Float64, ψ::Float64, u₀::Float64, gun::Canon, calibre::Float64)
    p₀ = 2*pi*u₀/(gun.tc*calibre)
    Φ = 0.0
    λ0, λ1, λ2, λ3 = euler2quartenions(θ, ψ, Φ)
    Q = 0.0
    R = 0.0
    u₀_bar = [u₀*cos(θ)*cos(ψ), u₀*cos(θ)*sin(ψ), -u₀*sin(θ) ]
    T_euler = T_matrixE(θ,ψ,Φ)
    u₀_bar_m = transpose(T_euler)*u₀_bar
    X₀_bar = [gun.lw*cos(θ)*cos(ψ),  gun.lw*cos(θ)*sin(ψ),- (gun.X2w + gun.lw *sin(θ))]

    u0 = [λ0, λ1, λ2, λ3, u₀_bar_m[1], u₀_bar_m[2], u₀_bar_m[3], p₀,Q, R, X₀_bar[1], X₀_bar[2], X₀_bar[3]]
    return u0
end

function QEfinderSixDof!(drone::Target2D, proj::Projectile2D, u₀::Float64, g₀::Float64, gun::Canon, w_bar::Array{Float64,1},lat::Float64)

    epsilonAz = 1e6
    epsilonQE = 1e6
    precisie = 0.001
    ddoel = euclidean(proj.position, drone.position)
    tdoel = sqrt(drone.position[1]^2+drone.position[2]^2)/u₀
    #QE = asind(((-drone.position[3]) - (-proj.position[3]) + g₀ /2 *tdoel^2)*tdoel/u₀)
    QE = (((-drone.position[3]) - (-proj.position[3]) + g₀ /2 *tdoel^2)*tdoel/u₀)
    AZ = 0.0
    tspan = (0.0,1000.0)
    Rz = 6.356766*1e6 #m
    Ω = 7.292115*1e-5 #rad/s
    ω_bar = [Ω*cosd(lat)*cosd(AZ), Ω*sind(lat), -Ω*cosd(lat)*sind(AZ)]
    p = [proj.calibre,proj.mass,proj.inertia[1],proj.inertia[2], ω_bar,g₀, Rz,drone.position,0.0]

    while abs(epsilonAz)>precisie || abs(epsilonQE)>precisie
        u0 = iniCondSixDof(deg2rad(QE), deg2rad(AZ), u₀, gun, proj.calibre)
        #global proj = projectile(u0[1],u0[2],u0[3],u0[4],u0[5],u0[6],0.0)
        #proj = projectile(u0[1],u0[2],u0[3],u0[4],u0[5],u0[6],0.0)
        proj.position = [u0[11],u0[12],u0[13]]
        proj.velocity = [u0[5],u0[6],u0[7]]
        proj.tof = 0.0
        trajectorySixDof!(u0, tspan, p, proj, drone)

        #global epsilonQE = proj.y - drone.y
        epsilonQE = (-proj.position[3]) - (-drone.position[3])
        #println("epsilonQE", " ", epsilonQE)
        #QE = QE0 + (accuracy)/(range_/QE0)
        #global epsilonAz = (sqrt((proj.z-drone.z)^2+(proj.x-drone.x)^2)*sign(atan(proj.z)/proj.x)-atan(drone.z/drone.x))
        epsilonAz = (sqrt((proj.position[2]-drone.position[2])^2+(proj.position[1]-drone.position[1])^2)*sign(atan(proj.position[2])/proj.position[1])-atan(drone.position[2]/drone.position[1]))
        #println("epsilonAz", " ", epsilonAz)
        #global AZ = AZ - epsilonAz/ddoel
        AZ = AZ - epsilonAz/ddoel
        #global QE = QE - epsilonQE/ddoel
        QE = QE - epsilonQE/ddoel

        #trajectory!(u0, tspan, p, proj, drone)
        #calcRange = euclidean([0.0,0.0,0.0], [proj.x,proj.y, proj.z])
        #global accuracy = range_  - calcRange
        #println("AZ", " ", AZ)
        #println("QE", " ", QE)

    end

return QE,AZ
end

function trajectorySixDof!(u0::Array{Float64,1}, tspan::Tuple{Float64,Float64}, p, proj::AbstractPenetrator, target::Target2D)

    prob = ODEProblem(sixdof,u0,tspan, p)

    cb = ContinuousCallback(condition,affect!)
    cb_tf = ContinuousCallback(timeFuze,affect!)
    cb_miss = ContinuousCallback(miss,affect!)
    #cb_tf=DiscreteCallback(timeFuze,affect_tf!)
    cbs = CallbackSet(cb,cb_tf,cb_miss)
    sol = solve(prob,Tsit5(),callback=cbs, reltol=1e-8, abstol=1e-8)
    proj.position[1] = sol.u[end][11]
    proj.position[2] = sol.u[end][12]
    proj.position[3] = sol.u[end][13]
    proj.velocity[1] = sol.u[end][5]
    proj.velocity[2] = sol.u[end][6]
    proj.velocity[3] = sol.u[end][7]
    proj.tof = sol.t[end]
    proj.spin = sol.u[end][8]

end

end


text:
using ControlSystems
using Test, LinearAlgebra, Random
import Base.isapprox
import SparseArrays: sparse
import DSP: conv
include("framework.jl")

# Local definition to make sure we get warings if we use eye
eye_(n) = Matrix{Int64}(I, n, n)

my_tests = [
            "test_statespace",
            "test_transferfunction",
            "test_zpk",
            "test_promotion",
            "test_connections",
            "test_discrete",
            "test_conversion",
            "test_complex",
            "test_linalg",
            "test_simplification",
            "test_freqresp",
            "test_timeresp",
            "test_analysis",
            "test_matrix_comps",
            "test_lqg",
            "test_synthesis",
            "test_partitioned_statespace",
            "test_delayed_systems",
            "test_demo_systems",
            ]

# try
#     Pkg.installed("ControlExamplePlots")
#     push!(my_tests, "test_plots")
# catch
#     warn("The unregistered package ControlExamplePlots is currently needed to test plots, install using:
#     Pkg.clone(\"https://github.com/JuliaControl/ControlExamplePlots.jl.git\")")
# end

run_tests(my_tests)


text:
# set random seed to promote repeatability in CI unit tests
using Random
Random.seed!(101)

for file in (
        "jop_dct.jl",
        "jop_dwt.jl",
        "jop_fft.jl",
        "jop_sft.jl",
        "jop_slantstack.jl")
    include(file)
end


text:
#= Ideas that didn't really work in pratice
=#
function localalign(target::Vector{T}, reference::Vector{T}, roi;
                    numregions=10, method=:peak) where T
    @assert length(target) == length(reference)
    # TODO I must only shift a window around the region of interest
    # If not, then the outskirts will bias the minimization, and the local
    # inverse transformation will be off
    # - What did I mean by this??

    points = []
    for (start, stop) in splitregion(roi, numregions)
        println("Working on ", start, ", ", stop)
        region = first(roi) .- 1 .+ [start:stop;]
        reference_point, target_point = try regionalign(target, reference, region)
        catch e
            println("==================")
            println(e)
            if isa(e, BoundsError)
                continue
            end
            throw(e)
        end

        # Shift points back
        reference_point += start + first(roi)
        target_point += start + first(roi)
        push!(points, [reference_point, target_point])
    end
    global tracecounter
    tracecounter = tracecounter + 1
    points
end
function regionalign(target::Vector{T}, reference::Vector{T}, roi, method=:peak,
                     smoothing=[31, 4]) where T
    @assert method ∈ [:peak, :random]
    signal = pyimport("scipy.signal")
    optim = pyimport("scipy.optimize")
    smooth(x) = signal.savgol_filter(x, smoothing...)[roi]

    refpoint = 0
    ref = smooth(reference)
    if method == :peak
        refpoint = findpeaks(ref, numpeaks=1)[1]
    elseif method == :random
        refpoint = rand(roi)
    end

    # Minimize the reference against to target to obtain the transformation
    # R→T
    shift = minimize(target, reference, roi, smooth)
    #corr = signal.correlate(target[roi], reference[roi])
    #plt = plot(corr)
    #display(plt)
    #shift = - (length(roi) - argmax(corr))
    gain = 1.0
    targetpoint = refpoint + shift |> x -> round(Int, x)

    shifted = gainshift(reference, shift, gain)
    #tracealignment(reference, target, shifted, refpoint, targetpoint, smooth, roi)

    refpoint, targetpoint
end

function log10transform(V)
    G = V[1:end]
    G[G .> 0] .= log10.(G[G .> 0])
    G[G .≤ 0] .= NaN
    G
end

tracecounter = 0
function tracealignment(reference::Vector{T}, target::Vector{T}, shifted::Vector{T}, refpoint, targetpoint, smoother, roi) where T
    tcol = :blue
    rcol = :red
    scol = :green
    bcol = :purple
    ycol = :yellow

    ref = smoother(reference)
    smoothtarget = smoother(target)
    plt = plot(reference[roi], label="Reference", alpha=0.3, color=rcol, seriestype=:steppre)
    plt = plot!(ref, label="Reference, smooth", color=rcol)
    plt = scatter!([refpoint], [ref[refpoint]],  markershape=:dtriangle, markercolor=rcol,
                   markerstrokewidth=0, label="Peak, smooth")

    plt = plot!(target[roi], label="Target", alpha=0.3, color=tcol, seriestype=:steppre)
    plt = plot!(smoothtarget,  label="Target, smooth", color=tcol)

    plt = plot!(shifted[roi], label="Shifted reference", alpha=0.3, color=scol, seriestype=:steppre)
    plt = plot!(smoother(shifted), label="Shifted reference, smooth", color=scol)

    plt = scatter!([targetpoint], [smoothtarget[targetpoint]],  markershape=:dtriangle, markercolor=bcol,
                   markerstrokewidth=0, label="Shifted peak onto target")

    l = @layout [  a{0.15h}; b{0.15h}; c]
    G = reference[roi] |> x -> convert(Vector{Float64}, x) |> log10transform
    P = target[roi] |> x -> convert(Vector{Float64}, x) |> log10transform
    p1 = heatmap(G')
    p1 = plot!([refpoint], [1], markershape=:dtriangle, markercolor=rcol, markerstrokewidth=0)
    p2 = heatmap(P')
    p2 = plot!([targetpoint], [1], markershape=:dtriangle, markercolor=tcol, markerstrokewidth=0)
    p = plot(p1, p2, plt, layout=l, yticks=nothing, colorbar=false, margin=0.2mm, size=(1000, 1000),
            legend=false)
    #p.subplots[1].attr[:xaxis][:ticks] = nothing
    p.subplots[1].attr[:framestyle] = :none

    global tracecounter
    savefig(p, "logplots/strip_$(tracecounter)_region_$(first(roi)).png")
end

max_stars_repo_name: Caronthir/JSort

max_issues_repo_name: Caronthir/JSort

max_forks_repo_name: Caronthir/JSort


text:
export @docstrings, @document

macro options(args...) :(options($(map(esc, args)...))) end
options(; args...) = @compat(Dict{Symbol, Any}(args))

macro docstrings(args...)
    ARGS = esc(:__DOCILE_ARGS__)
    quote
        const $(ARGS) = @options($(map(esc, args)...))
    end
end
macro document(args...)
    ARGS = esc(:__DOCILE_ARGS__)
    quote
        const $(ARGS) = @options($(map(esc, args)...))
    end
end

export @doc_str, @doc_mstr

macro doc_str(text)
    text
end
macro doc_mstr(text)
    Base.triplequoted(text)
end

export @md_str, @md_mstr

macro md_str(text)
    Base.warn_once("'@md_str' is deprecated, please use '@doc_str' instead.")
    text
end
macro md_mstr(text)
    Base.warn_once("'@md_mstr' is deprecated, please use '@doc_mstr' instead.")
    Base.triplequoted(text)
end

export @comment, @file_str

"""
Deprecated macro for adding object-independent docstrings to a module.

Use the following syntax instead:

    ["..."]

!!set(status:deprecated)
"""
macro comment(text)
    [text]
end

"""
The text found in the file ``text`` is used as the docstring content.

Deprecated in favour of automatically using a file's content if the docstring
matches a file path.

!!set(status:deprecated)
"""
macro file_str(text)
    text
end


text:
function derivative(f::Function, x::Array{T, 1}) where T <: AbstractFloat

  n = length(f(x))
  m = length(x)

	e  = eps(T)^(1/3)*maximum(abs,[x;one(T)])
  dh = Matrix{Float64}(I, m, m)*e
	deriv = Array{T}(undef,n,m)

  for i = 1:m
    deriv[:,i] = (-f(x+2*dh[:,i])+8*f(x+dh[:,i])-8*f(x-dh[:,i])+f(x-2*dh[:,i]))/(12*e)
  end

  return deriv

end


text:
using InplaceOps
using Base.Test

n = 10

X = randn(n,n)
v = randn(n)
y = randn()

pX = pointer(X)
pv = pointer(v)

C = cholfact(X'X)
u = C \ v
@in2! C \ v
@test u == v
@test pv == pointer(v)

A = qrfact(X)
u = A[:Q] * v
@in2! A[:Q] * v
@test u == v
@test pv == pointer(v)

Y = X .+ v .+ y
@in1! X .+ v
@in1! X .+ y
@test Y == X
@test pX == pointer(X)

pY = pointer(Y)
Z = X * X
@into! Y = X * X
@test Y == Z
@test pY == pointer(Y)

pY = pointer(Y)
Z = X' * X
@into! Y = X' * X
@test Y == Z
@test pY == pointer(Y)

pY = pointer(Y)
Z = X * X'
@into! Y = X * X'
@test Y == Z
@test pY == pointer(Y)

Z = X .+ v
@into! Y = X .+ v
@test Y == Z
@test pY == pointer(Y)

Z = X .+ y
@into! Y = X .+ y
@test Y == Z
@test pY == pointer(Y)

A = rand(n,n)
B = rand(n,n)
C = rand(n,n)
D = rand(n,n)

pA = pointer(A)

D = A + B + C
@in1! A + C
@in2! B + A
@test D == A
@test pA == pointer(A)

pA = pointer(A)

D = A - B
@in1! A - B
@test D == A
@test pA == pointer(A)

D = B - A
@in2! B - A
@test D == A
@test pA == pointer(A)

pD = pointer(D)

@into! D = A + B + C
@test D == A + B + C
@test pD == pointer(D)

@into! D = A - B
@test D == A - B
@test pD == pointer(D)


text:
using CSV, DataFrames

DP = DaylightPlots

lat = 42.716667
long = -70.866667
p = Point(lat,long)
tz = tz"EST" # USNO data are given in EST

df = CSV.read(Pkg.dir("DaylightPlots","test","rowley2018.csv"),types=[DateTime,DateTime],dateformat=DateFormat("yyyy-mm-ddTHH:MM"))

df[:RiseTZ] = ZonedDateTime.(df[:Rise],tz)
df[:SetTZ]  = ZonedDateTime.(df[:Set] ,tz)

ts = Date.(df[:Rise])

sr = [sunrise(t,p,tz) for t in ts]
ss = [sunset(t,p,tz) for t in ts]

@testset "Sunrise/Sunset calculation" begin
    @test all(x->x<Minute(1),abs.(df[:RiseTZ]-sr))
    @test all(x->x<Minute(1),abs.(df[:SetTZ] -ss))
end


text:
using MaskArrays
using Test

@testset "MaskArrays.jl" begin
    include("../examples/imputation.jl")

end


text:
include("lib_for_practic_10.jl")

function put_markers_in_labirint!(robot::CoordRobot)

    function recurs_for_labirint()
        coord = get_coord(get_coord(robot))
        if !(coord in set_coords)
            push!(set_coords, coord)
            putmarker!(robot)
            for side in (Nord, West, Sud, Ost)
                if try_move!(robot, side)
                    recurs_for_labirint()
                    move!(robot, inverse(side))
                end
            end
        end
    end

    set_coords = Set{NTuple{2,Int}}()
    recurs_for_labirint()
end

put_markers_in_labirint!(r)
show(r.robot)

max_stars_repo_name: AntonDudDm/mirea-progs

max_issues_repo_name: AntonDudDm/mirea-progs

max_forks_repo_name: AntonDudDm/mirea-progs


text:
export Periodic, Fixed

"""
    BoundaryCondition

Boundary conditions for lattices. There usually has two:

    - Fixed boundary
    - Periodic boundary

Ref: https://nanohub.org/resources/7577/download/Martini_L5_BoundaryConditions.pdf
"""
abstract type BoundaryCondition end

"""
    Periodic <: BoundaryCondition

Periodic boundary condition.
"""
abstract type Periodic <: BoundaryCondition end

"""
    Fixed <: BoundaryCondition

Fixed boundary condition.
"""
abstract type Fixed <: BoundaryCondition end


text:
using Base.Test
using Meganet

for TYPE=[Float64,Float32]
    K1 = getDenseKernel(TYPE,[18,10])
    nL = getTVNormLayer(TYPE,[6,3])

    L1 = getSingleLayer(TYPE,K1,nL)

    K2 = getDenseKernel(TYPE,[8,18])
    nL = getTVNormLayer(TYPE,[2,4])
    L2 = getSingleLayer(TYPE,K2,nL)

    blocks = Array{AbstractMeganetElement{TYPE}}(2)
    blocks[1] = L1;
    blocks[2] = L2;
    net = getNN(blocks)

    @testset "NN $TYPE" begin
     testAbstractMeganetElement(net)
    end
end


text:
using PyCall
using DataFrames
using Pandas: query

function pandas2julia(pdf)
    getcols(x) = typeof(x) == Pandas.DataFrame? map(Symbol, Pandas.columns(x)) :
                                            map(Symbol, x[:columns]);
    getdf(df, colnames) = DataFrames.DataFrame(
                            Any[Array(df[c]) for c in colnames], colnames);
    getdf(pdf, getcols(pdf));
end

function pj2pd(df)
    pd.DataFrame(df)
end

function pd2pj(df)
    Pandas.DataFrame(df)
end

function jdf2p(jdf, dftype="pd")
    df = Pandas.DataFrame([])
    for (colname, colvals) in zip(string.(names(jdf)),
        DataFrames.columns(jdf)) eval(:($df[$colname]=$colvals)) end

    if dftype=="pd"
        df = pd.DataFrame(df)
    end

    return df
end

#example expr is :(DispatchedMW == "15")
function query_pd(df, expr)
    @pipe test |> pd2pj |>  query(_, expr) |> pd.DataFrame
end

max_stars_repo_name: benzomo/PyPackages

max_issues_repo_name: benzomo/PyPackages

max_forks_repo_name: benzomo/PyPackages


text:
"""
    coordGeoRegion(geo::PolyRegion) ->
        blon::Vector{<:Real}, blat::Vector{<:Real},
        slon::Vector{<:Real}, slat::Vector{<:Real},

For a given RectRegion, extract the [N,S,E,W] bounds and create a longitude and latitude vectors for the bound and the shape of the GeoRegion

Arguments
=========

- `geo` : A PolyRegion (i.e. a polygonal GeoRegion)

Returns
=======

- `blon` : A vector of longitude points for the bound of the GeoRegion
- `blat` : A vector of latitude points for the bound of the GeoRegion
- `slon` : A vector of longitude points for the shape of the GeoRegion
- `slat` : A vector of latitude points for the shape of the GeoRegion
"""
function coordGeoRegion(GeoReg::PolyRegion)

    shape = GeoReg.shape
    npnt  = length(shape)
    lon   = zeros(npnt)
    lat   = zeros(npnt)

    for ipnt = 1 : npnt
        lon[ipnt] = shape[ipnt][1]
        lat[ipnt] = shape[ipnt][2]
    end

    N = GeoReg.N
    S = GeoReg.S
    E = GeoReg.E
    W = GeoReg.W

    return [W,E,E,W,W],[N,N,S,S,N],lon,lat

end

"""
    coordGeoRegion(geo::RectRegion) -> blon::Vector{<:Real}, blat::Vector{<:Real}

For a given RectRegion, extract the [N,S,E,W] bounds and create a longitude and latitude vector.

Arguments
=========

- `geo` : A RectRegion (i.e. a rectilinear GeoRegion)

Returns
=======

- `blon` : A vector of longitude points for the bound of the GeoRegion
- `blat` : A vector of latitude points for the bound of the GeoRegion
"""
function coordGeoRegion(GeoReg::RectRegion)

    N = GeoReg.N
    S = GeoReg.S
    E = GeoReg.E
    W = GeoReg.W
    return [W,E,E,W,W],[N,N,S,S,N]

end


text:
## Basic tests for simple utilities within BB

@testset "File Collection" begin
    temp_prefix() do prefix
        # Create a file and a link, ensure that only the one file is returned by collect_files()
        f = joinpath(prefix, "foo")
        f_link = joinpath(prefix, "foo_link")
        touch(f)
        symlink(f, f_link)

        files = collect_files(prefix)
        @test length(files) == 2
        @test f in files
        @test f_link in files

        collapsed_files = collapse_symlinks(files)
        @test length(collapsed_files) == 1
        @test f in collapsed_files
    end
end

@testset "Target properties" begin
    for t in ["i686-linux-gnu", "i686-w64-mingw32", "arm-linux-gnueabihf"]
        @test BinaryBuilder.target_nbits(t) == "32"
    end

    for t in ["x86_64-linux-gnu", "x86_64-w64-mingw32", "aarch64-linux-gnu",
              "powerpc64le-linux-gnu", "x86_64-apple-darwin14"]
        @test BinaryBuilder.target_nbits(t) == "64"
    end

    for t in ["x86_64-linux-gnu", "x86_64-apple-darwin14", "i686-w64-mingw32"]
        @test BinaryBuilder.target_proc_family(t) == "intel"
    end
    for t in ["aarch64-linux-gnu", "arm-linux-gnueabihf"]
        @test BinaryBuilder.target_proc_family(t) == "arm"
    end
    @test BinaryBuilder.target_proc_family("powerpc64le-linux-gnu") == "power"

    for t in ["aarch64-linux-gnu", "x86_64-unknown-freebsd11.1"]
        @test BinaryBuilder.target_dlext(t) == "so"
    end
    @test BinaryBuilder.target_dlext("x86_64-apple-darwin14") == "dylib"
    @test BinaryBuilder.target_dlext("i686-w64-mingw32") == "dll"
end

@testset "UserNS utilities" begin
    # Test that is_ecryptfs works for something we're certain isn't encrypted
    if isdir("/proc")
        isecfs = (false, "/proc/")
        @test BinaryBuilder.is_ecryptfs("/proc"; verbose=true) == isecfs
        @test BinaryBuilder.is_ecryptfs("/proc/"; verbose=true) == isecfs
        @test BinaryBuilder.is_ecryptfs("/proc/not_a_file"; verbose=true) == isecfs
    else
        @test BinaryBuilder.is_ecryptfs("/proc"; verbose=true) == (false, "/proc")
        @test BinaryBuilder.is_ecryptfs("/proc/"; verbose=true) == (false, "/proc/")
        @test BinaryBuilder.is_ecryptfs("/proc/not_a_file"; verbose=true) == (false, "/proc/not_a_file")
    end
end

@testset "environment and history saving" begin
    build_path = tempname()
    mkpath(build_path)
    prefix, ur = BinaryBuilder.setup_workspace(build_path, [], [], [], platform)
    @test_throws ErrorException build(ur, "foo", libfoo_products(prefix), "MARKER=1\nexit 1", platform, prefix)

    # Ensure that we get a metadir, and that our history and .env files are in there!
    metadir = joinpath(prefix.path, "..", "metadir")
    @test isdir(metadir)

    hist_file = joinpath(metadir, ".bash_history")
    env_file = joinpath(metadir, ".env")
    @test isfile(hist_file)
    @test isfile(env_file)

    # Test that exit 1 is in .bash_history
    @test occursin("\nexit 1\n", read(open(hist_file), String))

    # Test that MARKER=1 is in .env:
    @test occursin("\nMARKER=1\n", read(open(env_file), String))

    # Delete the build path
    rm(build_path, recursive = true)
end

@testset "GitHub releases build.jl reconstruction" begin
    # Download some random release that is relatively small
    product_hashes = product_hashes_from_github_release("staticfloat/OggBuilder", "v1.3.3-6")

    # Ground truth hashes for each product
    true_product_hashes = Dict(
        "arm-linux-gnueabihf"        => (
            "Ogg.v1.3.3.arm-linux-gnueabihf.tar.gz",
            "a70830decaee040793b5c6a8f8900ed81720aee51125a3aab22440b26e45997a"
        ),
        "x86_64-unknown-freebsd11.1" => (
            "Ogg.v1.3.3.x86_64-unknown-freebsd11.1.tar.gz",
            "a87e432f1e80880200b18decc33df87634129a2f9d06200cae89ad8ddde477b6"
        ),
        "i686-w64-mingw32"           => (
            "Ogg.v1.3.3.i686-w64-mingw32.tar.gz",
            "3f6f6f524137a178e9df7cb5ea5427de6694c2a44ef78f1491d22bd9c6c8a0e8"
        ),
        "powerpc64le-linux-gnu"      => (
            "Ogg.v1.3.3.powerpc64le-linux-gnu.tar.gz",
            "b133194a9527f087bbf942f77bf6a953cb8c277c98f609479bce976a31a5ba39"
        ),
        "x86_64-linux-gnu"           => (
            "Ogg.v1.3.3.x86_64-linux-gnu.tar.gz",
            "6ef771242553b96262d57b978358887a056034a3c630835c76062dca8b139ea6"
        ),
        "x86_64-apple-darwin14"      => (
            "Ogg.v1.3.3.x86_64-apple-darwin14.tar.gz",
            "077898aed79bbce121c5e3d5cd2741f50be1a7b5998943328eab5406249ac295"
        ),
        "x86_64-linux-musl"          => (
            "Ogg.v1.3.3.x86_64-linux-musl.tar.gz",
            "a7ff6bf9b28e1109fe26c4afb9c533f7df5cf04ace118aaae76c2fbb4c296b99"
        ),
        "aarch64-linux-gnu"          => (
            "Ogg.v1.3.3.aarch64-linux-gnu.tar.gz",
            "ce2329057df10e4f1755da696a5d5e597e1a9157a85992f143d03857f4af259c"
        ),
        "i686-linux-musl"            => (
            "Ogg.v1.3.3.i686-linux-musl.tar.gz",
            "d8fc3c201ea40feeb05bc84d7159286584427f54776e316ef537ff32347c4007"
        ),
        "x86_64-w64-mingw32"         => (
            "Ogg.v1.3.3.x86_64-w64-mingw32.tar.gz",
            "c6afdfb19d9b0d20b24a6802e49a1fbb08ddd6a2d1da7f14b68f8627fd55833a"
        ),
        "i686-linux-gnu"             => (
            "Ogg.v1.3.3.i686-linux-gnu.tar.gz",
            "1045d82da61ff9574d91f490a7be0b9e6ce17f6777b6e9e94c3c897cc53dd284"
        ),
    )

    @test length(product_hashes) == length(true_product_hashes)

    for target in keys(true_product_hashes)
        @test haskey(product_hashes, target)
        product_platform = extract_platform_key(product_hashes[target][1])
        true_product_platform = extract_platform_key(true_product_hashes[target][1])
        @test product_platform == true_product_platform
        @test product_hashes[target][2] == true_product_hashes[target][2]
    end
end

@testset "Wizard Utilities" begin
    # Make sure canonicalization does what we expect
    zmq_url = "https://github.com/zeromq/zeromq3-x/releases/download/v3.2.5/zeromq-3.2.5.tar.gz"
    @test BinaryBuilder.canonicalize_source_url(zmq_url) == zmq_url
    this_url = "https://github.com/JuliaPackaging/BinaryBuilder.jl/blob/1fee900486baedfce66ddb24872133ef36b9d899/test/wizard.jl"
    this_url_ans = "https://raw.githubusercontent.com/JuliaPackaging/BinaryBuilder.jl/1fee900486baedfce66ddb24872133ef36b9d899/test/wizard.jl"
    @test BinaryBuilder.canonicalize_file_url(this_url) == this_url_ans

    # Make sure normalization does what we expect
    @test BinaryBuilder.normalize_name("foo/libfoo.tar.gz") == "libfoo"
    @test BinaryBuilder.normalize_name("foo/libfoo-2.dll") == "libfoo"
    @test BinaryBuilder.normalize_name("libfoo") == "libfoo"
end


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

"""
    AssociateCertificate()

Associates an AWS Certificate Manager (ACM) Amazon Resource Name (ARN) with AWS Elemental MediaConvert.

# Required Parameters
- `arn`: The ARN of the ACM certificate that you want to associate with your MediaConvert resource.

"""
associate_certificate(arn; aws_config::AWSConfig=global_aws_config()) = mediaconvert("POST", "/2017-08-29/certificates", Dict{String, Any}("arn"=>arn); aws_config=aws_config)
associate_certificate(arn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = mediaconvert("POST", "/2017-08-29/certificates", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("arn"=>arn), args)); aws_config=aws_config)

"""
    CancelJob()

Permanently cancel a job. Once you have canceled a job, you can't start it again.

# Required Parameters
- `id`: The Job ID of the job to be cancelled.

"""
cancel_job(id; aws_config::AWSConfig=global_aws_config()) = mediaconvert("DELETE", "/2017-08-29/jobs/$(id)"; aws_config=aws_config)
cancel_job(id, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = mediaconvert("DELETE", "/2017-08-29/jobs/$(id)", args; aws_config=aws_config)

"""
    CreateJob()

Create a new transcoding job. For information about jobs and job settings, see the User Guide at http://docs.aws.amazon.com/mediaconvert/latest/ug/what-is.html

# Required Parameters
- `role`: Required. The IAM role you use for creating this job. For details about permissions, see the User Guide topic at the User Guide at https://docs.aws.amazon.com/mediaconvert/latest/ug/iam-role.html.
- `settings`: JobSettings contains all the transcode settings for a job.

# Optional Parameters
- `accelerationSettings`: Optional. Accelerated transcoding can significantly speed up jobs with long, visually complex content. Outputs that use this feature incur pro-tier pricing. For information about feature limitations, see the AWS Elemental MediaConvert User Guide.
- `billingTagsSource`: Optional. Choose a tag type that AWS Billing and Cost Management will use to sort your AWS Elemental MediaConvert costs on any billing report that you set up. Any transcoding outputs that don't have an associated tag will appear in your billing report unsorted. If you don't choose a valid value for this field, your job outputs will appear on the billing report unsorted.
- `clientRequestToken`: Optional. Idempotency token for CreateJob operation.
- `hopDestinations`: Optional. Use queue hopping to avoid overly long waits in the backlog of the queue that you submit your job to. Specify an alternate queue and the maximum time that your job will wait in the initial queue before hopping. For more information about this feature, see the AWS Elemental MediaConvert User Guide.
- `jobTemplate`: Optional. When you create a job, you can either specify a job template or specify the transcoding settings individually.
- `priority`: Optional. Specify the relative priority for this job. In any given queue, the service begins processing the job with the highest value first. When more than one job has the same priority, the service begins processing the job that you submitted first. If you don't specify a priority, the service uses the default value 0.
- `queue`: Optional. When you create a job, you can specify a queue to send it to. If you don't specify, the job will go to the default queue. For more about queues, see the User Guide topic at https://docs.aws.amazon.com/mediaconvert/latest/ug/what-is.html.
- `simulateReservedQueue`: Optional. Enable this setting when you run a test job to estimate how many reserved transcoding slots (RTS) you need. When this is enabled, MediaConvert runs your job from an on-demand queue with similar performance to what you will see with one RTS in a reserved queue. This setting is disabled by default.
- `statusUpdateInterval`: Optional. Specify how often MediaConvert sends STATUS_UPDATE events to Amazon CloudWatch Events. Set the interval, in seconds, between status updates. MediaConvert sends an update at this interval from the time the service begins processing your job to the time it completes the transcode or encounters an error.
- `tags`: Optional. The tags that you want to add to the resource. You can tag resources with a key-value pair or with only a key.  Use standard AWS tags on your job for automatic integration with AWS services and for custom integrations and workflows.
- `userMetadata`: Optional. User-defined metadata that you want to associate with an MediaConvert job. You specify metadata in key/value pairs.  Use only for existing integrations or workflows that rely on job metadata tags. Otherwise, we recommend that you use standard AWS tags.
"""
create_job(role, settings; aws_config::AWSConfig=global_aws_config()) = mediaconvert("POST", "/2017-08-29/jobs", Dict{String, Any}("role"=>role, "settings"=>settings, "clientRequestToken"=>string(uuid4())); aws_config=aws_config)
create_job(role, settings, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = mediaconvert("POST", "/2017-08-29/jobs", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("role"=>role, "settings"=>settings, "clientRequestToken"=>string(uuid4())), args)); aws_config=aws_config)

"""
    CreateJobTemplate()

Create a new job template. For information about job templates see the User Guide at http://docs.aws.amazon.com/mediaconvert/latest/ug/what-is.html

# Required Parameters
- `name`: The name of the job template you are creating.
- `settings`: JobTemplateSettings contains all the transcode settings saved in the template that will be applied to jobs created from it.

# Optional Parameters
- `accelerationSettings`: Accelerated transcoding can significantly speed up jobs with long, visually complex content. Outputs that use this feature incur pro-tier pricing. For information about feature limitations, see the AWS Elemental MediaConvert User Guide.
- `category`: Optional. A category for the job template you are creating
- `description`: Optional. A description of the job template you are creating.
- `hopDestinations`: Optional. Use queue hopping to avoid overly long waits in the backlog of the queue that you submit your job to. Specify an alternate queue and the maximum time that your job will wait in the initial queue before hopping. For more information about this feature, see the AWS Elemental MediaConvert User Guide.
- `priority`: Specify the relative priority for this job. In any given queue, the service begins processing the job with the highest value first. When more than one job has the same priority, the service begins processing the job that you submitted first. If you don't specify a priority, the service uses the default value 0.
- `queue`: Optional. The queue that jobs created from this template are assigned to. If you don't specify this, jobs will go to the default queue.
- `statusUpdateInterval`: Specify how often MediaConvert sends STATUS_UPDATE events to Amazon CloudWatch Events. Set the interval, in seconds, between status updates. MediaConvert sends an update at this interval from the time the service begins processing your job to the time it completes the transcode or encounters an error.
- `tags`: The tags that you want to add to the resource. You can tag resources with a key-value pair or with only a key.
"""
create_job_template(name, settings; aws_config::AWSConfig=global_aws_config()) = mediaconvert("POST", "/2017-08-29/jobTemplates", Dict{String, Any}("name"=>name, "settings"=>settings); aws_config=aws_config)
create_job_template(name, settings, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = mediaconvert("POST", "/2017-08-29/jobTemplates", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("name"=>name, "settings"=>settings), args)); aws_config=aws_config)

"""
    CreatePreset()

Create a new preset. For information about job templates see the User Guide at http://docs.aws.amazon.com/mediaconvert/latest/ug/what-is.html

# Required Parameters
- `name`: The name of the preset you are creating.
- `settings`: Settings for preset

# Optional Parameters
- `category`: Optional. A category for the preset you are creating.
- `description`: Optional. A description of the preset you are creating.
- `tags`: The tags that you want to add to the resource. You can tag resources with a key-value pair or with only a key.
"""
create_preset(name, settings; aws_config::AWSConfig=global_aws_config()) = mediaconvert("POST", "/2017-08-29/presets", Dict{String, Any}("name"=>name, "settings"=>settings); aws_config=aws_config)
create_preset(name, settings, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = mediaconvert("POST", "/2017-08-29/presets", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("name"=>name, "settings"=>settings), args)); aws_config=aws_config)

"""
    CreateQueue()

Create a new transcoding queue. For information about queues, see Working With Queues in the User Guide at https://docs.aws.amazon.com/mediaconvert/latest/ug/working-with-queues.html

# Required Parameters
- `name`: The name of the queue that you are creating.

# Optional Parameters
- `description`: Optional. A description of the queue that you are creating.
- `pricingPlan`: Specifies whether the pricing plan for the queue is on-demand or reserved. For on-demand, you pay per minute, billed in increments of .01 minute. For reserved, you pay for the transcoding capacity of the entire queue, regardless of how much or how little you use it. Reserved pricing requires a 12-month commitment. When you use the API to create a queue, the default is on-demand.
- `reservationPlanSettings`: Details about the pricing plan for your reserved queue. Required for reserved queues and not applicable to on-demand queues.
- `status`: Initial state of the queue. If you create a paused queue, then jobs in that queue won't begin.
- `tags`: The tags that you want to add to the resource. You can tag resources with a key-value pair or with only a key.
"""
create_queue(name; aws_config::AWSConfig=global_aws_config()) = mediaconvert("POST", "/2017-08-29/queues", Dict{String, Any}("name"=>name); aws_config=aws_config)
create_queue(name, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = mediaconvert("POST", "/2017-08-29/queues", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("name"=>name), args)); aws_config=aws_config)

"""
    DeleteJobTemplate()

Permanently delete a job template you have created.

# Required Parameters
- `name`: The name of the job template to be deleted.

"""
delete_job_template(name; aws_config::AWSConfig=global_aws_config()) = mediaconvert("DELETE", "/2017-08-29/jobTemplates/$(name)"; aws_config=aws_config)
delete_job_template(name, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = mediaconvert("DELETE", "/2017-08-29/jobTemplates/$(name)", args; aws_config=aws_config)

"""
    DeletePreset()

Permanently delete a preset you have created.

# Required Parameters
- `name`: The name of the preset to be deleted.

"""
delete_preset(name; aws_config::AWSConfig=global_aws_config()) = mediaconvert("DELETE", "/2017-08-29/presets/$(name)"; aws_config=aws_config)
delete_preset(name, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = mediaconvert("DELETE", "/2017-08-29/presets/$(name)", args; aws_config=aws_config)

"""
    DeleteQueue()

Permanently delete a queue you have created.

# Required Parameters
- `name`: The name of the queue that you want to delete.

"""
delete_queue(name; aws_config::AWSConfig=global_aws_config()) = mediaconvert("DELETE", "/2017-08-29/queues/$(name)"; aws_config=aws_config)
delete_queue(name, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = mediaconvert("DELETE", "/2017-08-29/queues/$(name)", args; aws_config=aws_config)

"""
    DescribeEndpoints()

Send an request with an empty body to the regional API endpoint to get your account API endpoint.

# Optional Parameters
- `maxResults`: Optional. Max number of endpoints, up to twenty, that will be returned at one time.
- `mode`: Optional field, defaults to DEFAULT. Specify DEFAULT for this operation to return your endpoints if any exist, or to create an endpoint for you and return it if one doesn't already exist. Specify GET_ONLY to return your endpoints if any exist, or an empty list if none exist.
- `nextToken`: Use this string, provided with the response to a previous request, to request the next batch of endpoints.
"""
describe_endpoints(; aws_config::AWSConfig=global_aws_config()) = mediaconvert("POST", "/2017-08-29/endpoints"; aws_config=aws_config)
describe_endpoints(args::AbstractDict{String, Any}; aws_config::AWSConfig=global_aws_config()) = mediaconvert("POST", "/2017-08-29/endpoints", args; aws_config=aws_config)

"""
    DisassociateCertificate()

Removes an association between the Amazon Resource Name (ARN) of an AWS Certificate Manager (ACM) certificate and an AWS Elemental MediaConvert resource.

# Required Parameters
- `arn`: The ARN of the ACM certificate that you want to disassociate from your MediaConvert resource.

"""
disassociate_certificate(arn; aws_config::AWSConfig=global_aws_config()) = mediaconvert("DELETE", "/2017-08-29/certificates/$(arn)"; aws_config=aws_config)
disassociate_certificate(arn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = mediaconvert("DELETE", "/2017-08-29/certificates/$(arn)", args; aws_config=aws_config)

"""
    GetJob()

Retrieve the JSON for a specific completed transcoding job.

# Required Parameters
- `id`: the job ID of the job.

"""
get_job(id; aws_config::AWSConfig=global_aws_config()) = mediaconvert("GET", "/2017-08-29/jobs/$(id)"; aws_config=aws_config)
get_job(id, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = mediaconvert("GET", "/2017-08-29/jobs/$(id)", args; aws_config=aws_config)

"""
    GetJobTemplate()

Retrieve the JSON for a specific job template.

# Required Parameters
- `name`: The name of the job template.

"""
get_job_template(name; aws_config::AWSConfig=global_aws_config()) = mediaconvert("GET", "/2017-08-29/jobTemplates/$(name)"; aws_config=aws_config)
get_job_template(name, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = mediaconvert("GET", "/2017-08-29/jobTemplates/$(name)", args; aws_config=aws_config)

"""
    GetPreset()

Retrieve the JSON for a specific preset.

# Required Parameters
- `name`: The name of the preset.

"""
get_preset(name; aws_config::AWSConfig=global_aws_config()) = mediaconvert("GET", "/2017-08-29/presets/$(name)"; aws_config=aws_config)
get_preset(name, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = mediaconvert("GET", "/2017-08-29/presets/$(name)", args; aws_config=aws_config)

"""
    GetQueue()

Retrieve the JSON for a specific queue.

# Required Parameters
- `name`: The name of the queue that you want information about.

"""
get_queue(name; aws_config::AWSConfig=global_aws_config()) = mediaconvert("GET", "/2017-08-29/queues/$(name)"; aws_config=aws_config)
get_queue(name, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = mediaconvert("GET", "/2017-08-29/queues/$(name)", args; aws_config=aws_config)

"""
    ListJobTemplates()

Retrieve a JSON array of up to twenty of your job templates. This will return the templates themselves, not just a list of them. To retrieve the next twenty templates, use the nextToken string returned with the array

# Optional Parameters
- `category`: Optionally, specify a job template category to limit responses to only job templates from that category.
- `listBy`: Optional. When you request a list of job templates, you can choose to list them alphabetically by NAME or chronologically by CREATION_DATE. If you don't specify, the service will list them by name.
- `maxResults`: Optional. Number of job templates, up to twenty, that will be returned at one time.
- `nextToken`: Use this string, provided with the response to a previous request, to request the next batch of job templates.
- `order`: Optional. When you request lists of resources, you can specify whether they are sorted in ASCENDING or DESCENDING order. Default varies by resource.
"""
list_job_templates(; aws_config::AWSConfig=global_aws_config()) = mediaconvert("GET", "/2017-08-29/jobTemplates"; aws_config=aws_config)
list_job_templates(args::AbstractDict{String, Any}; aws_config::AWSConfig=global_aws_config()) = mediaconvert("GET", "/2017-08-29/jobTemplates", args; aws_config=aws_config)

"""
    ListJobs()

Retrieve a JSON array of up to twenty of your most recently created jobs. This array includes in-process, completed, and errored jobs. This will return the jobs themselves, not just a list of the jobs. To retrieve the twenty next most recent jobs, use the nextToken string returned with the array.

# Optional Parameters
- `maxResults`: Optional. Number of jobs, up to twenty, that will be returned at one time.
- `nextToken`: Optional. Use this string, provided with the response to a previous request, to request the next batch of jobs.
- `order`: Optional. When you request lists of resources, you can specify whether they are sorted in ASCENDING or DESCENDING order. Default varies by resource.
- `queue`: Optional. Provide a queue name to get back only jobs from that queue.
- `status`: Optional. A job's status can be SUBMITTED, PROGRESSING, COMPLETE, CANCELED, or ERROR.
"""
list_jobs(; aws_config::AWSConfig=global_aws_config()) = mediaconvert("GET", "/2017-08-29/jobs"; aws_config=aws_config)
list_jobs(args::AbstractDict{String, Any}; aws_config::AWSConfig=global_aws_config()) = mediaconvert("GET", "/2017-08-29/jobs", args; aws_config=aws_config)

"""
    ListPresets()

Retrieve a JSON array of up to twenty of your presets. This will return the presets themselves, not just a list of them. To retrieve the next twenty presets, use the nextToken string returned with the array.

# Optional Parameters
- `category`: Optionally, specify a preset category to limit responses to only presets from that category.
- `listBy`: Optional. When you request a list of presets, you can choose to list them alphabetically by NAME or chronologically by CREATION_DATE. If you don't specify, the service will list them by name.
- `maxResults`: Optional. Number of presets, up to twenty, that will be returned at one time
- `nextToken`: Use this string, provided with the response to a previous request, to request the next batch of presets.
- `order`: Optional. When you request lists of resources, you can specify whether they are sorted in ASCENDING or DESCENDING order. Default varies by resource.
"""
list_presets(; aws_config::AWSConfig=global_aws_config()) = mediaconvert("GET", "/2017-08-29/presets"; aws_config=aws_config)
list_presets(args::AbstractDict{String, Any}; aws_config::AWSConfig=global_aws_config()) = mediaconvert("GET", "/2017-08-29/presets", args; aws_config=aws_config)

"""
    ListQueues()

Retrieve a JSON array of up to twenty of your queues. This will return the queues themselves, not just a list of them. To retrieve the next twenty queues, use the nextToken string returned with the array.

# Optional Parameters
- `listBy`: Optional. When you request a list of queues, you can choose to list them alphabetically by NAME or chronologically by CREATION_DATE. If you don't specify, the service will list them by creation date.
- `maxResults`: Optional. Number of queues, up to twenty, that will be returned at one time.
- `nextToken`: Use this string, provided with the response to a previous request, to request the next batch of queues.
- `order`: Optional. When you request lists of resources, you can specify whether they are sorted in ASCENDING or DESCENDING order. Default varies by resource.
"""
list_queues(; aws_config::AWSConfig=global_aws_config()) = mediaconvert("GET", "/2017-08-29/queues"; aws_config=aws_config)
list_queues(args::AbstractDict{String, Any}; aws_config::AWSConfig=global_aws_config()) = mediaconvert("GET", "/2017-08-29/queues", args; aws_config=aws_config)

"""
    ListTagsForResource()

Retrieve the tags for a MediaConvert resource.

# Required Parameters
- `arn`: The Amazon Resource Name (ARN) of the resource that you want to list tags for. To get the ARN, send a GET request with the resource name.

"""
list_tags_for_resource(arn; aws_config::AWSConfig=global_aws_config()) = mediaconvert("GET", "/2017-08-29/tags/$(arn)"; aws_config=aws_config)
list_tags_for_resource(arn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = mediaconvert("GET", "/2017-08-29/tags/$(arn)", args; aws_config=aws_config)

"""
    TagResource()

Add tags to a MediaConvert queue, preset, or job template. For information about tagging, see the User Guide at https://docs.aws.amazon.com/mediaconvert/latest/ug/tagging-resources.html

# Required Parameters
- `arn`: The Amazon Resource Name (ARN) of the resource that you want to tag. To get the ARN, send a GET request with the resource name.
- `tags`: The tags that you want to add to the resource. You can tag resources with a key-value pair or with only a key.

"""
tag_resource(arn, tags; aws_config::AWSConfig=global_aws_config()) = mediaconvert("POST", "/2017-08-29/tags", Dict{String, Any}("arn"=>arn, "tags"=>tags); aws_config=aws_config)
tag_resource(arn, tags, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = mediaconvert("POST", "/2017-08-29/tags", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("arn"=>arn, "tags"=>tags), args)); aws_config=aws_config)

"""
    UntagResource()

Remove tags from a MediaConvert queue, preset, or job template. For information about tagging, see the User Guide at https://docs.aws.amazon.com/mediaconvert/latest/ug/tagging-resources.html

# Required Parameters
- `arn`: The Amazon Resource Name (ARN) of the resource that you want to remove tags from. To get the ARN, send a GET request with the resource name.

# Optional Parameters
- `tagKeys`: The keys of the tags that you want to remove from the resource.
"""
untag_resource(arn; aws_config::AWSConfig=global_aws_config()) = mediaconvert("PUT", "/2017-08-29/tags/$(arn)"; aws_config=aws_config)
untag_resource(arn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = mediaconvert("PUT", "/2017-08-29/tags/$(arn)", args; aws_config=aws_config)

"""
    UpdateJobTemplate()

Modify one of your existing job templates.

# Required Parameters
- `name`: The name of the job template you are modifying

# Optional Parameters
- `accelerationSettings`: Accelerated transcoding can significantly speed up jobs with long, visually complex content. Outputs that use this feature incur pro-tier pricing. For information about feature limitations, see the AWS Elemental MediaConvert User Guide.
- `category`: The new category for the job template, if you are changing it.
- `description`: The new description for the job template, if you are changing it.
- `hopDestinations`: Optional list of hop destinations.
- `priority`: Specify the relative priority for this job. In any given queue, the service begins processing the job with the highest value first. When more than one job has the same priority, the service begins processing the job that you submitted first. If you don't specify a priority, the service uses the default value 0.
- `queue`: The new queue for the job template, if you are changing it.
- `settings`: JobTemplateSettings contains all the transcode settings saved in the template that will be applied to jobs created from it.
- `statusUpdateInterval`: Specify how often MediaConvert sends STATUS_UPDATE events to Amazon CloudWatch Events. Set the interval, in seconds, between status updates. MediaConvert sends an update at this interval from the time the service begins processing your job to the time it completes the transcode or encounters an error.
"""
update_job_template(name; aws_config::AWSConfig=global_aws_config()) = mediaconvert("PUT", "/2017-08-29/jobTemplates/$(name)"; aws_config=aws_config)
update_job_template(name, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = mediaconvert("PUT", "/2017-08-29/jobTemplates/$(name)", args; aws_config=aws_config)

"""
    UpdatePreset()

Modify one of your existing presets.

# Required Parameters
- `name`: The name of the preset you are modifying.

# Optional Parameters
- `category`: The new category for the preset, if you are changing it.
- `description`: The new description for the preset, if you are changing it.
- `settings`: Settings for preset
"""
update_preset(name; aws_config::AWSConfig=global_aws_config()) = mediaconvert("PUT", "/2017-08-29/presets/$(name)"; aws_config=aws_config)
update_preset(name, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = mediaconvert("PUT", "/2017-08-29/presets/$(name)", args; aws_config=aws_config)

"""
    UpdateQueue()

Modify one of your existing queues.

# Required Parameters
- `name`: The name of the queue that you are modifying.

# Optional Parameters
- `description`: The new description for the queue, if you are changing it.
- `reservationPlanSettings`: The new details of your pricing plan for your reserved queue. When you set up a new pricing plan to replace an expired one, you enter into another 12-month commitment. When you add capacity to your queue by increasing the number of RTS, you extend the term of your commitment to 12 months from when you add capacity. After you make these commitments, you can't cancel them.
- `status`: Pause or activate a queue by changing its status between ACTIVE and PAUSED. If you pause a queue, jobs in that queue won't begin. Jobs that are running when you pause the queue continue to run until they finish or result in an error.
"""
update_queue(name; aws_config::AWSConfig=global_aws_config()) = mediaconvert("PUT", "/2017-08-29/queues/$(name)"; aws_config=aws_config)
update_queue(name, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = mediaconvert("PUT", "/2017-08-29/queues/$(name)", args; aws_config=aws_config)


text:
"""
    finite-difference velocity objective
"""
struct VelocityObjective <: Objective
    Q
    n
    h
end

velocity_objective(Q, n; h = 0.0) = VelocityObjective(Q, n, h)

function objective(Z, obj::VelocityObjective, idx, T)
    n = obj.n

    J = 0.0

    for t = 1:T-1
        q⁻ = view(Z, idx.x[t][n .+ (1:n)])
        q⁺ = view(Z, idx.x[t + 1][n .+ (1:n)])
        h = obj.h == 0.0 ? view(Z, idx.u[t][end]) : obj.h
        v = (q⁺ - q⁻) ./ h

        J += v' * obj.Q[t] * v
    end

    return J
end

function objective_gradient!(∇J, Z, obj::VelocityObjective, idx, T)

    n = obj.n

    for t = 1:T-1
        q⁻ = view(Z, idx.x[t][n .+ (1:n)])
        q⁺ = view(Z, idx.x[t + 1][n .+ (1:n)])
        h = obj.h == 0.0 ? view(Z, idx.u[t][end]) : obj.h
        v = (q⁺ - q⁻) ./ h

        dJdv = 2.0 * obj.Q[t] * v
        ∇J[idx.x[t][n .+ (1:n)]] += -1.0 ./ h * dJdv
        ∇J[idx.x[t + 1][n .+ (1:n)]] += 1.0 ./ h * dJdv
        if obj.h == 0.0
            ∇J[idx.u[t][end]] += -1.0 * dJdv' * v ./ h
        end
    end

    return nothing
end

max_stars_repo_name: zacmanchester/DirectMotionPlanning

max_issues_repo_name: zacmanchester/DirectMotionPlanning

max_forks_repo_name: zacmanchester/DirectMotionPlanning


text:
#---------------------------------------------------------------
#   Transform to AffineMat that can be used in the renderer
#---------------------------------------------------------------
function Glimmer.transform(t::OpticSim.Transform{T}) where {T<:Real}
    rot = SMatrix{3, 3, T}(
        t[1, 1], t[2, 1], t[3, 1],
        t[1, 2], t[2, 2], t[3, 2],
        t[1, 3], t[2, 3], t[3, 3])

    translation = SVector(t[1, 4], t[2, 4], t[3, 4])
    return AffineMap(rot, translation)
end

function toTransform(tr::CoordinateTransformations.AffineMap)
    return OpticSim.Transform(tr.linear, tr.translation)
end

#---------------------------------------------------------------
#   TriangleMesh to GeometryBasics.Mesh that can be rendered
#---------------------------------------------------------------
function to_mesh(tm::OpticSim.TriangleMesh{T}) where {T<:Real}
    len = length(tm.triangles)
    points = Vector{GeometryBasics.Point3{Float64}}(undef, len * 3)
    indices = Vector{GeometryBasics.TriangleFace{Int64}}(undef, len)
    @inbounds @simd for i in 0:(len - 1)
        t = tm.triangles[i + 1]
        points[i * 3 + 1] = OpticSim.vertex(t, 1)
        points[i * 3 + 2] = OpticSim.vertex(t, 2)
        points[i * 3 + 3] = OpticSim.vertex(t, 3)
        indices[i + 1] = GeometryBasics.TriangleFace{Int64}(i * 3 + 1, i * 3 + 2, i * 3 + 3)
    end

    # create the mesh
    mesh = GeometryBasics.Mesh(points, indices)
    return mesh
end

#---------------------------------------------------------------
#   Examples Utilities
#---------------------------------------------------------------
fixFolderSeperator(fn::String) = replace(fn, '\\' => '/')

"""
    rootFolder()

return the root folder for this package.
"""
function rootFolder()
    return fixFolderSeperator(abspath(joinpath(dirname(@__FILE__), "..")))
end

"""
    examplesFolder()

return the examples folder (~/examples) for this package.
"""
function examplesFolder()
    return fixFolderSeperator(abspath(joinpath(rootFolder(), "examples")))
end

"""
    examplesList()

Display a list of avalable examples.
"""
function examplesList()
    folder = examplesFolder();

    files = readdir(folder, join=false)

    all_jl_files = [fn for fn in files if splitext(basename(fn))[2] == ".jl"]

    println("-"^60)
    println("Examples List for OpticSimVis  [$(folder)]")
    println("-"^60)
    for f in all_jl_files
        len = length(f)
        if (len < 20)
            spaces = " "^(20 - len)
        else
            spaces = ""
        end
        println("    $(f)$(spaces)       to run:  julia> OpticSimVis.runExample(\"$(splitext(f)[1])\")")
    end

end

"""
    runExample(example::String)

Run the specific example. [example] is given without extension.
For example, if we have an example file named "Emitters.jl" the command to run it is:
OpticSimVis.runExample("Emitters")
"""
function runExample(example::String)
    fn = fixFolderSeperator(joinpath(examplesFolder(), "$(splitext(example)[1]).jl"))

    @show fn
    code = "include(\"$fn\")"
    @show code
    exp = Meta.parse(code)
    return eval(exp)
end


text:
"""
Outputs that display the simulation frames live.
"""
abstract type GraphicOutput{T} <: Output{T} end

(::Type{F})(o::T; kwargs...) where F <: GraphicOutput where T <: GraphicOutput =
    F(; frames=frames(o), starttime=starttime(o), endtime=endtime(o),
      fps=fps(o), showfps=showfps(o), timestamp=timestamp(o), stampframe=stampframe(o), store=store(o),
      kwargs...)

"""
Mixin for graphic output fields
"""
@premix @default_kw struct Graphic{FPS,SFPS,TS,SF}
    fps::FPS       | 25.0
    showfps::SFPS  | 25.0
    timestamp::TS  | 0.0
    stampframe::SF | 1
    store::Bool    | false
end

# Field getters and setters
fps(o::GraphicOutput) = o.fps
setfps!(o::GraphicOutput, x) = o.fps = x
showfps(o::GraphicOutput) = o.showfps
timestamp(o::GraphicOutput) = o.timestamp
stampframe(o::GraphicOutput) = o.stampframe
isstored(o::GraphicOutput) = o.store

settimestamp!(o::GraphicOutput, f) = begin
    o.timestamp = time()
    o.stampframe = f
end

# Output interface
# Delay output to maintain the frame rate
delay(o::GraphicOutput, f) =
    sleep(max(0.0, timestamp(o) + (f - stampframe(o))/fps(o) - time()))
isshowable(o::GraphicOutput, f) = true # TODO working max fps. o.timestamp + (t - tlast(o))/o.maxfps < time()

"""
Frames are deleted and reallocated during the simulation,
which this allows runs of any length.
"""
initframes!(o::GraphicOutput, init) = begin
    deleteat!(frames(o), 1:length(o))
    push!(frames(o), deepcopy(init))
end
initframes!(o::GraphicOutput, init::NamedTuple) = begin
    deleteat!(frames(o), 1:length(o))
    push!(frames(o), deepcopy(init))
end

storeframe!(o::GraphicOutput, data) = begin
    f = currentframe(data)
    if isstored(o)
        push!(o, fill!(similar(o[1]), zero(eltype(o[1]))))
        storeframe!(o, data, f)
    else
        fill!(o[1], zero(eltype(o[1])))
        storeframe!(o, data, 1)
    end
    isshowable(o, f) && showframe(o, data, f)
end
storeframe!(o::GraphicOutput, data::MultiSimData) = begin
    f = currentframe(data)
    if isstored(o)
        push!(o, map(l -> fill!(similar(l), zero(eltype(l))), o[1]))
        storeframe!(o, data, f)
    else
        map(l -> fill!(l, zero(eltype(l))), o[1])
        storeframe!(o, data, 1)
    end
    isshowable(o, f) && showframe(o, data, f)
end

showframe(o::GraphicOutput, data::AbstractSimData) =
    showframe(o, data, lastindex(o))
showframe(o::GraphicOutput, data::AbstractSimData, f) =
    showframe(o[frameindex(o, f)], o, data, f)
showframe(o::GraphicOutput, data::AbstractVector{<:AbstractSimData}, f) =
    showframe(o, data[1], f)
showframe(frame, o::GraphicOutput, data::AbstractSimData, f) =
    showframe(frame, o, f)
showframe(o::GraphicOutput, f=firstindex(o)) = showframe(o[f], o, f)


text:
const ie = IfElse.ifelse

"""
    Saturation(; y_max, y_min=-y_max, name)

The `Saturation` IO block limits the output between `y_min` and `y_max`, equivalent to
`y ~ clamp(u, y_min, y_max)`.

Keywords: limiter, sat, actuator model
"""
function Saturation(; y_max, y_min=y_max > 0 ? -y_max : -Inf, name)
    if !ModelingToolkit.isvariable(y_max)
        y_max ≥ y_min || throw(ArgumentError("y_min must be smaller than y_max"))
    end
    @variables u(t)=0 [input=true] y(t)=0 [output=true]
    @parameters y_max=y_max y_min=y_min
    eqs = [
        # The equation below is equivalent to y ~ clamp(u, y_min, y_max)
        y ~ ie(u > y_max, y_max, ie( (y_min < u) & (u < y_max), u, y_min))
    ]
    ODESystem(eqs, t, name=name)
end

"""
    DeadZone(; u_max, u_min=-u_max, name)

A dead zone is a band within which the output is zero.
Outside of the dead zone, the output changes linearly starting from zero at the band edge.
```
       y▲
        │     /
        │    /
  u_min │   /
─────|──┼──|───────► u
    /   │   u_max
   /    │
  /     │
```
"""
function DeadZone(; u_max, u_min=-u_max, name)
    if !ModelingToolkit.isvariable(u_max)
        u_max ≥ u_min || throw(ArgumentError("u_min must be smaller than u_max"))
    end
    @variables u(t)=0 [input=true] y(t)=0 [output=true]
    @parameters u_max=u_max u_min=u_min
    eqs = [
        y ~ ie(u > u_max, u-u_max, ie( u < u_min, u-u_min, 0))
    ]
    ODESystem(eqs, t, name=name)
end


text:
#=

Authors: Shunsuke Hori

=#
"""
Function to Solve Single Beliefs
"""
function price_single_beliefs(transition::Matrix, dividend_payoff::Vector;
                              β::AbstractFloat=.75)
    # First compute inverse piece
    imbq_inv = inv(eye(size(transition, 1)) - β * transition)

    # Next compute prices
    prices = β * ((imbq_inv * transition) * dividend_payoff)

    return prices
end


text:
# script for sending request for table computation

"""
    computetable(session::EESession, featurecollection::EE.AbstractEEObject)

Fuction to request data from EarthEngine FeatureCollection and return as a GeoDataFrame.
See https://developers.google.com/earth-engine/reference/rest/v1beta/projects.table/computeFeatures
"""
function computetable(
    session::EESession,
    featurecollection::EE.AbstractEEObject,
)

    endpoint = "table:computeFeatures"

    serialized = ee.serializer.encode(featurecollection, for_cloud_api = true)

    payload = Dict(:expression => serialized)

    response = _sendrequest(session, endpoint, payload)

    return GeoDataFrames.read(response.content)
end


text:
module Proc
using YAXArrays.Cubes: YAXArray, cubechunks, caxes
using YAXArrays.Cubes.Axes: getAxis, findAxis, CategoricalAxis, axVal2Index,
  RangeAxis, get_bb, axisfrombb, CubeAxis, axname
using YAXArrays.DAT: mapCube, InDims, OutDims, NValid, AnyMissing
using YAXArrays.Datasets: getsavefolder, Cube
using Dates: year, Date, DateTime
"""
    getNpY(cube)

Get the number of time steps per year
"""
function getNpY(cube)
    timax = getAxis("Time",cube)
    years = year.(timax.values)
    years[end] > years[1] + 1 || error("Must have at least 3 years to estimate number of time steps per year")
    return count(i -> i == years[1] + 1, years)
end

include("MSC.jl")
include("Stats.jl")
include("TSDecomposition.jl")
include("remap.jl")
include("Shapes.jl")
include("extractlonlats.jl")

end


text:
using TableOfElements
using Base.Test

@test get_element(1).name == "Hydrogen"
@test get_element(18).name == "Argon"
@test get_element(43).name == "Technetium"
@test get_element(84).name == "Polonium"
@test get_element(111).name == "Roentgenium"
@test get_element("V").name == "Vanadium"
@test get_element(:he).name == "Helium"