text:
include(joinpath("inc", "algorithm_help_msg.jl"));

using ArgParse;

s = ArgParseSettings();
@add_arg_table s begin
  "--E0", "-z"
    help = "magnitude of electric field"
    arg_type = Float64
    default = 0.0
  "--dk", "-D"
    help = "kappa1 - kappa2"
    arg_type = Float64
    default = 1.0
  "--kT", "-k"
    help = "dimensionless temperature"
    arg_type = Float64
    default = 1.0
  "--theta", "-t"
    help = "angle of stretch direction (with respect to x-axis; e-field direction is pi/2)"
    arg_type = AbstractString
    default = "pi"
  "--num-monomers", "-N"
    help = "number of monomers"
    arg_type = Int
    default = 100
  "--algorithm", "-A"
    help = "algorithm (ISRES | PRAXIS | SBPLX | SLSQP | LBFGS | AUGLAG | Newton | Anneal). Run with --print-algo-help for more detailed information"
    default = "try Newton then PRAXIS,SBPLX,Newton"
  "--print-algo-help"
    help = "Get detailed information regarding algorithms themselves, and how to run to solvers in stages"
    action = :store_true
  "--reltol-int", "-r"
    help = "relative tolerance for numerical integration"
    arg_type = Float64
    default = 1e-6
  "--maxevals-int", "-e"
    help = "maximum evaluations for numerical integration"
    arg_type = Int
    default = 2500
  "--reltol-opt", "-R"
    help = "relative tolerance for optimization"
    arg_type = Float64
    default = 0.0
  "--abstol-opt", "-B"
    help = "absolute tolerance for optimization"
    arg_type = Float64
    default = 1e-8
  "--maxevals-opt", "-E"
    help = "maximum evaluations for numerical integration"
    arg_type = AbstractString
    default = "try 1000 then 10000,5000,50"
  "--num-data-points"
    help = "number of data points to collect in free energy vs. stretch graph"
    arg_type = Int
    default = 10
  "--outfile", "-O"
    help = "filename"
    default = "energy-vs-stretch.csv"
  "--verbose", "-v"
    help = "print diagnostic information"
    action = :store_true
end

pa = parse_args(s);
if pa["print-algo-help"]
  println(_ALGO_HELP_MSG_);
  exit();
end
const dk = pa["dk"];
const E0 = pa["E0"];
const theta = eval(parse(pa["theta"]));
const st = sin(theta);
const ct = cos(theta);
const kT = pa["kT"];
const N = pa["num-monomers"];
const reltol = pa["reltol-int"];
const maxevals = pa["maxevals-int"];
const numpoints = pa["num-data-points"];
const outfile = pa["outfile"];
const algo = pa["algorithm"];
const verbose = pa["verbose"];
const reltol_opt = pa["reltol-opt"];
const abstol_opt = pa["abstol-opt"];
const maxevals_opt = pa["maxevals-opt"];

x0 = 1.0 / numpoints / 10;
dx = 1.0 / (numpoints - 1);
xs = vcat([x0], collect(dx:dx:1.0));
xs[end]-=x0;

open(outfile, "w") do w
  for x in xs
    println("x = $x");
    if verbose
      command = `julia mean_field.jl -A $algo --E0 $E0 --dk $dk --kT $kT -N $N --reltol-int $reltol --maxevals-int $maxevals --reltol-opt $reltol_opt --abstol-opt $abstol_opt --maxevals-opt $maxevals_opt --gz $(x*st) --gx $(x*ct) --verbose`;
    else
      command = `julia mean_field.jl -A $algo --E0 $E0 --dk $dk --kT $kT -N $N --reltol-int $reltol --maxevals-int $maxevals --reltol-opt $reltol_opt --abstol-opt $abstol_opt --maxevals-opt $maxevals_opt --gz $(x*st) --gx $(x*ct)`;
    end

    process_output = readlines(command);
    free_energy = NaN;
    lambda = NaN;
    alpha = NaN;
    C = NaN;
    mu1 = NaN;
    mu2 = NaN;
    mu3 = NaN;
    l2 = NaN;

    if verbose; println("output:"); end
    for line in process_output
      if verbose
        println(">>  ", strip(line));
      end
      splits = map(strip, split(line, '='));
      if length(splits) > 1
        if splits[1] == "A"
          free_energy = parse(Float64, splits[2]);
        elseif splits[1] == "lambda"
          lambda = parse(Float64, splits[2]);
        elseif splits[1] == "alpha"
          alpha = parse(Float64, splits[2]);
        elseif splits[1] == "C"
          C = parse(Float64, splits[2]);
        elseif splits[1] == "mu1"
          mu1 = parse(Float64, splits[2]);
        elseif splits[1] == "mu2"
          mu2 = parse(Float64, splits[2]);
        elseif splits[1] == "mu3"
          mu3 = parse(Float64, splits[2]);
        elseif splits[1] == "L2"
          l2 = parse(Float64, splits[2]);
        end
      end
    end
    if verbose; println(); end
    println("================ RESULTS ================");

    println("        x:  $x");
    println("        A:  $free_energy");
    println("   lambda:  $lambda");
    println("    alpha:  $alpha");
    println("        C:  $C");
    println("      mu1:  $mu1");
    println("      mu2:  $mu2");
    println("      mu3:  $mu3");
    println("       L2:  $l2");
    println("=========================================\n");
    write(w, "$x, $free_energy, $lambda, $alpha, $C, $mu1, $mu2, $mu3, $l2\n");
  end
end

max_stars_repo_name: grasingerm/polymer-stats

max_issues_repo_name: grasingerm/polymer-stats

max_forks_repo_name: grasingerm/polymer-stats


text:
# -----------------------------------------
# Tests adapted from Ruby's Rugged Library
# -----------------------------------------
with_repo_access() do test_repo, test_repo_path
    context("test read config file") do
        cfg = GitConfig(test_repo)
        @test isa(cfg, GitConfig)
        @test cfg["core.bare"] == "false"
        @test cfg["not.exist"] == nothing
    end

    context("test read from path") do
        cfg = GitConfig(joinpath(path(test_repo), "config"))
        @test isa(cfg, GitConfig)
        @test cfg["core.bare"] == "false"
    end

    context("test read global config file") do
        cfg = global_config()
        @test isa(cfg, GitConfig)
        @test cfg["user.name"] != nothing
        @test cfg["core.bare"] == nothing
    end
end

with_tmp_repo_access() do test_repo, test_repo_path
   context("test write config values") do
       cfg = GitConfig(test_repo)
       cfg["custom.value"] = "my value"

       cfg2 = GitConfig(test_repo)
       @test cfg2["custom.value"] == "my value"

       content = open(readall, joinpath(path(test_repo), "config"))
       @test match(r"value = my value", content) != nothing
   end

   context("test delete config values") do
        cfg = GitConfig(test_repo)
        delete!(cfg, "core.bare")
        cfg2 = GitConfig(test_repo)
        @test cfg2["core.bare"] == nothing
    end
end

ext: jl


text:
const DenseNativeArray = DenseArray{<:NativeTypes}

"""
`vstorent!` (non-temporal store) requires data to be aligned.
`alignstores!` will align `y` in preparation for the non-temporal maps.
"""
function alignstores!(
    f::F, y::DenseArray{T},
    args::Vararg{DenseNativeArray,A}
) where {F, T <: Base.HWReal, A}
    N = length(y)
    ptry = VectorizationBase.zero_offsets(stridedpointer(y))
    ptrargs = VectorizationBase.zero_offsets.(stridedpointer.(args))
    V = VectorizationBase.pick_vector_width_val(T)
    W = unwrap(V)
    zero_index = MM{W}(Static(0))
    uintptry = reinterpret(UInt, pointer(ptry))
    @assert iszero(uintptry & (sizeof(T) - 1)) "The destination vector (`dest`) must be aligned at least to `sizeof(eltype(dest))`."
    alignment = uintptry & (VectorizationBase.REGISTER_SIZE - 1)
    if alignment > 0
        i = reinterpret(Int, W - (alignment >>> VectorizationBase.intlog2(sizeof(T))))
        m = mask(T, i)
        if N < i
            m &= mask(T, N & (W - 1))
        end
        vnoaliasstore!(ptry, f(vload.(ptrargs, ((zero_index,),), m)...), (zero_index,), m)
        gesp(ptry, (i,)), gesp.(ptrargs, ((i,),)), N - i
    else
        ptry, ptrargs, N
    end
end

function vmap_singlethread!(
    f::F, y::DenseArray{T},
    ::Val{NonTemporal},
    args::Vararg{DenseNativeArray,A}
) where {F,T <: Base.HWReal, A, NonTemporal}
    if NonTemporal # if stores into `y` aren't aligned, we'll get a crash
        ptry, ptrargs, N = alignstores!(f, y, args...)
    else
        N = length(y)
        ptry = VectorizationBase.zero_offsets(stridedpointer(y))
        ptrargs = VectorizationBase.zero_offsets.(stridedpointer.(args))
    end
    i = 0
    V = VectorizationBase.pick_vector_width_val(T)
    W = unwrap(V)
    st = VectorizationBase.static_sizeof(T)
    zero_index = MM{W}(Static(0), st)
    while i < N - ((W << 2) - 1)

        # vstore!(stridedpointer(B), VectorizationBase.VecUnroll((v1,v2,v3)), VectorizationBase.Unroll{AU,1,3,AV,W64,zero(UInt)}((i, j, k)))
        # vload(stridedpointer(B), VectorizationBase.Unroll{1,1,4,1,W,0x0000000000000000}((i,)))

        index = VectorizationBase.Unroll{1,1,4,1,W,0x0000000000000000}((i,))
        v = f(vload.(ptrargs, index)...)
        if NonTemporal
            vstorent!(ptry, v, index)
        else
            vnoaliasstore!(ptry, v, index)
        end
        i = vadd(i, 4W)
    end
    while i < N - (W - 1) # stops at 16 when
        vᵣ = f(vload.(ptrargs, ((MM{W}(i),),))...)
        if NonTemporal
            vstorent!(ptry, vᵣ, (MM{W}(i),))
        else
            vnoaliasstore!(ptry, vᵣ, (MM{W}(i),))
        end
        i = vadd(i, W)
    end
    if i < N
        m = mask(T, N & (W - 1))
        vnoaliasstore!(ptry, f(vload.(ptrargs, ((MM{W}(i),),), m)...), (MM{W}(i,),), m)
    end
    y
end

function vmap_multithreaded!(
    f::F,
    y::DenseArray{T},
    ::Val{true},
    args::Vararg{DenseNativeArray,A}
) where {F,T,A}
    ptry, ptrargs, N = alignstores!(f, y, args...)
    N > 0 || return y
    W, Wshift = VectorizationBase.pick_vector_width_shift(T)
    V = VectorizationBase.pick_vector_width_val(T)
    Wsh = Wshift + 2
    Niter = N >>> Wsh
    Base.Threads.@threads for j ∈ 0:Niter-1
        index = VectorizationBase.Unroll{1,1,4,1,W,0x0000000000000000}((j << Wsh,))
        vstorent!(ptry, f(vload.(ptrargs, index)...), index)
    end
    ii = Niter << Wsh
    while ii < N - (W - 1) # stops at 16 when
        vstorent!(ptry, f(vload.(ptrargs, ((MM{W}(ii),),))...), (MM{W}(ii),))
        ii = vadd(ii, W)
    end
    if ii < N
        m = mask(T, N & (W - 1))
        vnoaliasstore!(ptry, f(vload.(ptrargs, ((MM{W}(ii),),), m)...), (MM{W}(ii),), m)
    end
    y
end
function vmap_multithreaded!(
    f::F,
    y::DenseArray{T},
    ::Val{false},
    args::Vararg{DenseNativeArray,A}
) where {F,T,A}
    N = length(y)
    ptry = VectorizationBase.zero_offsets(stridedpointer(y))
    ptrargs = VectorizationBase.zero_offsets.(stridedpointer.(args))
    N > 0 || return y
    W, Wshift = VectorizationBase.pick_vector_width_shift(T)
    V = VectorizationBase.pick_vector_width_val(T)
    Wsh = Wshift + 2
    Niter = N >>> Wsh
    Base.Threads.@threads for j ∈ 0:Niter-1
        index = VectorizationBase.Unroll{1,1,4,1,W,0x0000000000000000}((j << Wsh,))
        vnoaliasstore!(ptry, f(vload.(ptrargs, index)...), index)
    end
    ii = Niter << Wsh
    while ii < N - (W - 1) # stops at 16 when
        vnoaliasstore!(ptry, f(vload.(ptrargs, ((MM{W}(ii),),))...), (MM{W}(ii),))
        ii = vadd(ii, W)
    end
    if ii < N
        m = mask(T, N & (W - 1))
        vnoaliasstore!(ptry, f(vload.(ptrargs, ((MM{W}(ii),),), m)...), (MM{W}(ii),), m)
    end
    y
end

"""
    vmap!(f, destination, a::AbstractArray)
    vmap!(f, destination, a::AbstractArray, b::AbstractArray, ...)

Vectorized-`map!`, applying `f` to each element of `a` (or paired elements of `a`, `b`, ...)
and storing the result in `destination`.
"""
function vmap!(
    f::F, y::DenseArray{T}, args::Vararg{DenseNativeArray,A}
) where {F,T<:Base.HWReal,A}
    vmap_singlethread!(f, y, Val{false}(), args...)
end

"""
    vmapt!(::Function, dest, args...)

Like `vmap!` (see `vmap!`), but uses `Threads.@threads` for parallel execution.
"""
function vmapt!(
    f::F, y::DenseArray{T}, args::Vararg{DenseNativeArray,A}
) where {F,T<:Base.HWReal,A}
    vmap_multithreaded!(f, y, Val{false}(), args...)
end

"""
    vmapnt!(::Function, dest, args...)

This is a vectorized map implementation using nontemporal store operations. This means that the write operations to the destination will not go to the CPU's cache.
If you will not immediately be reading from these values, this can improve performance because the writes won't pollute your cache. This can especially be the case if your arguments are very long.

```julia
julia> using LoopVectorization, BenchmarkTools

julia> x = rand(10^8); y = rand(10^8); z = similar(x);

julia> f(x,y) = exp(-0.5abs2(x - y))
f (generic function with 1 method)

julia> @benchmark map!(f, \$z, \$x, \$y)
BenchmarkTools.Trial:
  memory estimate:  0 bytes
  allocs estimate:  0
  --------------
  minimum time:     439.613 ms (0.00% GC)
  median time:      440.729 ms (0.00% GC)
  mean time:        440.695 ms (0.00% GC)
  maximum time:     441.665 ms (0.00% GC)
  --------------
  samples:          12
  evals/sample:     1

julia> @benchmark vmap!(f, \$z, \$x, \$y)
BenchmarkTools.Trial:
  memory estimate:  0 bytes
  allocs estimate:  0
  --------------
  minimum time:     178.147 ms (0.00% GC)
  median time:      178.381 ms (0.00% GC)
  mean time:        178.430 ms (0.00% GC)
  maximum time:     179.054 ms (0.00% GC)
  --------------
  samples:          29
  evals/sample:     1

julia> @benchmark vmapnt!(f, \$z, \$x, \$y)
BenchmarkTools.Trial:
  memory estimate:  0 bytes
  allocs estimate:  0
  --------------
  minimum time:     144.183 ms (0.00% GC)
  median time:      144.338 ms (0.00% GC)
  mean time:        144.349 ms (0.00% GC)
  maximum time:     144.641 ms (0.00% GC)
  --------------
  samples:          35
  evals/sample:     1
```
"""
function vmapnt!(
    f::F, y::DenseArray{T}, args::Vararg{DenseNativeArray,A}
) where {F,T<:Base.HWReal,A}
    vmap_singlethread!(f, y, Val{true}(), args...)
end

"""
    vmapntt!(::Function, dest, args...)

Like `vmapnt!` (see `vmapnt!`), but uses `Threads.@threads` for parallel execution.
"""
function vmapntt!(
    f::F, y::DenseArray{T}, args::Vararg{DenseNativeArray,A}
) where {F,T<:Base.HWReal,A}
    vmap_multithreaded!(f, y, Val{true}(), args...)
end

# generic fallbacks
@inline vmap!(f, args...) = map!(f, args...)
@inline vmapt!(f, args...) = map!(f, args...)
@inline vmapnt!(f, args...) = map!(f, args...)
@inline vmapntt!(f, args...) = map!(f, args...)

function vmap_call(f::F, vm!::V, args::Vararg{Any,N}) where {V,F,N}
    T = Base._return_type(f, Base.Broadcast.eltypes(args))
    dest = similar(first(args), T)
    vm!(f, dest, args...)
end

"""
    vmap(f, a::AbstractArray)
    vmap(f, a::AbstractArray, b::AbstractArray, ...)

SIMD-vectorized `map`, applying `f` to each element of `a` (or paired elements of `a`, `b`, ...)
and returning a new array.
"""
vmap(f::F, args::Vararg{Any,N}) where {F,N} = vmap_call(f, vmap!, args...)

"""
    vmapt(f, a::AbstractArray)
    vmapt(f, a::AbstractArray, b::AbstractArray, ...)

A threaded variant of [`vmap`](@ref).
"""
vmapt(f::F, args::Vararg{Any,N}) where {F,N} = vmap_call(f, vmapt!, args...)

"""
    vmapnt(f, a::AbstractArray)
    vmapnt(f, a::AbstractArray, b::AbstractArray, ...)

A "non-temporal" variant of [`vmap`](@ref). This can improve performance in cases where
`destination` will not be needed soon.
"""
vmapnt(f::F, args::Vararg{Any,N}) where {F,N} = vmap_call(f, vmapnt!, args...)

"""
    vmapntt(f, a::AbstractArray)
    vmapntt(f, a::AbstractArray, b::AbstractArray, ...)

A threaded variant of [`vmapnt`](@ref).
"""
vmapntt(f::F, args::Vararg{Any,N}) where {F,N} = vmap_call(f, vmapntt!, args...)

# @inline vmap!(f, y, x...) = @avx y .= f.(x...)
# @inline vmap(f, x...) = @avx f.(x...)


text:
# The license for this code is available at https://github.com/avik-pal/FastStyleTransfer.jl/blob/master/LICENSE.md

#------------------------Utilities to Train new models----------------------------

"""
Train a model for style transfer.
"""
function train(train_data_path, batch_size, η, style_image_path, epochs, model_save_path, content_weight, style_weight, model = TransformerNet; images = 10000)
    train_dataset = load_dataset(train_data_path, batch_size, images)
    @info "Loading initial model weights"
    try
        BSON.@load model_save_path transformer
    catch
        transformer = model()
    end
    @info "Model weights to GPU"
    transformer = transformer |> gpu
    optimizer = Flux.ADAM(η)
    @info "Loading style image"
    style = load_image(style_image_path, size_img = 224)
    @info "Style image to GPU"
    style = repeat(reshape(style, size(style)..., 1), outer = (1,1,1,batch_size)) |> gpu
    im_mean2 = reshape([0.485, 0.458, 0.408], (1,1,3,1)) * 255 |> gpu # Reinitialize to avoid gpu error

    @info "Model to GPU"
    vgg = vgg19() |> gpu
    features_style = vgg(style)
    @info "Calculating gram matrix"
    gram_style = [gram_matrix(y) for y in features_style]

    @info "Defining loss function"
    function loss_function(x)
        y = transformer(x)

        y = y .- im_mean2 # No need to do for x as it is already normalized

        features_y = vgg(y)
        features_x = vgg(x)

        # TODO: Train models for other depths by changing the index number
        content_loss = content_weight * Flux.mse(features_y[2], features_x[2])

        style_loss = 0.0
        for i in 1:size(features_style, 1)
            gram_sty = gram_style[i]
            gram_y = gram_matrix(features_y[i])
            style_loss = style_loss + Flux.mse(gram_y, gram_sty)
        end
        style_loss = style_loss * style_weight

        total_loss = content_loss + style_loss
        @info "Content Loss : $(content_loss) || Style Loss : $(style_loss) || Total Loss : $(total_loss)"

        total_loss
    end
    #=
    for (x,y) in train_data
  gs = Flux.gradient(ps) do
    loss(x,y)
  end
  Flux.Optimise.update!(opt, ps, gs)

    =#
    @info "Beginning training cycle"
    ecount = 1
    Flux.@epochs epochs begin
        @info "Epoch $ecount..."
        dcount = 1
        for d in train_dataset
            @info "Data section $dcount..."
            size(d, 4) != batch_size && continue
            gs = Flux.gradient(params(transformer)) do
                loss_function(d |> gpu)
            end
            Flux.Optimise.update!(optimizer, params(model), gs)
        end

        transformer = transformer |> cpu
        BSON.@save model_save_path transformer
        ecount += 1
    end
end

#----------------------------------Utilities to Stylize Images--------------------------------

"""
Stylize an image based on a style model.
"""
function stylize(image_path, model_path = "../models/trained_network_1.bson"; save_path = "", display_img::Bool = true)
    info("Starting to Load Model")
    BSON.@load model_path transformer
    transformer = transformer |> gpu
    Flux.testmode!(transformer)
    @info "Model has been Loaded Successfully"
    img = load_image(image_path)
    img = reshape(img, size(img)..., 1) |> gpu
    @info "Image Loaded Successfully"
    a = time()
    stylized_img = transformer(img)
    @info "Image has been Stylized in $(time()-a) seconds"
    if save_path == ""
        path = rsplit(image_path, ".", limit = 2)
        save_path = "$(path[1])_stylized.$(path[2])"
    end
    stylized_img = stylized_img |> cpu
    save_image(save_path, data(stylized_img), display_img)
    @info "The image has been saved successfully"
end


text:
PSCOPF_TIME_LIMIT_IN_SECONDS = 60.
PSCOPF_REDIRECT_LOG = false

max_stars_repo_name: klorel/pscopf

max_issues_repo_name: klorel/pscopf

max_forks_repo_name: klorel/pscopf


text:
export simple_estimator, improved_estimator, default_estimator

@inline function simple_estimator(model, param::Parameter, _=nothing)
    p = convert_parameter(model,param)
    return simple_estimator(model, p..., nothing)
end

@inline function improved_estimator(model, param::Parameter, extra)
    p = convert_parameter(model, param)
    return improved_estimator(model, p..., extra)
end

@doc doc"""
    default_estimator(model, updatemethod!)

Determines estimator to be used when `param["Estimator"]` is not set.
"""
@inline default_estimator(model::Model, update) = simple_estimator


text:
# %% Plot average winnings over time
# using Distributions
# using DataFrames
using Gadfly
using Colors
import Cairo, Fontconfig
using Printf
# %%

# Returns the value of the steinhaus sequence at position n (1-indexed).
function steinhaus(n)
    d = 1
    while (n % 2 == 0)
        d += 1
        n /= 2
    end
    return 2^d
end

# %%
theme = Theme(major_label_font="PragmataPro Mono",
              minor_label_font="PragmataPro Mono",
              key_title_font="PragmataPro Mono Bold")
Gadfly.push_theme(theme)

x = 1:150

m = layer(x=x,
          y=cumsum(steinhaus.(x)) ./ (1:length(x)),
          Geom.step,
          Theme(default_color=RGBA(0,0,0,0.8)))

f = layer(x=x,
          y=log2.(x).+2,
          Geom.line)

p = plot(f,m,
         Guide.manual_color_key("", ["Cumulative mean", "log2n+2"], [RGBA(0,0,0,0.8), "deepskyblue"]),
         Guide.xlabel("n"),
         Guide.ylabel(nothing),
         Guide.xticks(ticks=0:16:length(x)),
         Guide.yticks(ticks=2:9),
         Coord.cartesian(ymin=2,ymax=9.2),
         Guide.title("Expected Value of Steinhaus Sequence Over n Rounds"))

push!(p,l)

draw(PDF("../../figures/steinhaus.pdf"), p)
# %%

max_stars_repo_name: akoen/petersburg

max_issues_repo_name: akoen/petersburg

max_forks_repo_name: akoen/petersburg


text:
module Utils

if isdefined(Threads, Symbol("@spawn"))
    using Base.Threads: @spawn
else
    macro spawn(ex)
        esc(:($Base.@async $ex))
    end
end

end


text:
downloaddir = joinpath(dirname(@__FILE__),"downloads")
bindir = joinpath(dirname(@__FILE__),"usr","lib")

const weber_sound_version = 4

# remove any old build files
for d in [downloaddir,bindir]
  rm(d,recursive=true,force=true)
  mkpath(d)
end

################################################################################
# install SDL2 and plugins

weber_sound = "UNKNOWN"
portaudio = "UNKNOWN"

@static if is_windows()
  # WinRPM lacks SDL2_ttf and SDL2_mixer binaries, so I'm just directly
  # downloading them from the SDL website.
  function setupbin(library,uri)
    libdir = joinpath(downloaddir,library)
    zipfile = joinpath(downloaddir,library*".zip")
    try
      download(uri,zipfile)
      run(`$(joinpath(JULIA_HOME, "7z.exe")) x $zipfile -y -o$libdir`)
      for lib in filter(s -> endswith(s,".dll"),readdir(libdir))
        cp(joinpath(libdir,lib),joinpath(bindir,lib))
      end
      replace(joinpath(bindir,library*".dll"),"\\","\\\\")
    finally
      rm(libdir,recursive=true,force=true)
      rm(zipfile,force=true)
    end
  end

  weber_build = joinpath(dirname(@__FILE__),"build",
                         "libweber-sound.$(weber_sound_version).dll")
  weber_sound = joinpath(bindir,"libweber-sound.$(weber_sound_version).dll")
  portaudio_build = joinpath(dirname(@__FILE__),"lib","portaudio_x64.dll")
  portaudio = joinpath(bindir,"portaudio_x64.dll")
  if isfile(weber_build)
    info("Using Makefile generated libraries $weber_build and $portaudio_build.")
    mv(weber_build,weber_sound)
    mv(portaudio_build,portaudio)
  else
    download("http://haberdashpi.github.io/libweber-sound."*
             "$(weber_sound_version).dll",weber_sound)
    download("http://haberdashpi.github.io/portaudio_x64.dll",portaudio)
  end

  weber_sound = replace(weber_sound,"\\","\\\\")
  portaudio = replace(portaudio,"\\","\\\\")
elseif is_apple()
  using Homebrew

  Homebrew.add("portaudio")

  prefix = joinpath(Homebrew.prefix(),"lib")
  portaudio = joinpath(prefix,"libportaudio.2.dylib")

  weber_build = joinpath(dirname(@__FILE__),"build",
                         "libweber-sound.$(weber_sound_version).dylib")
  weber_sound = joinpath(bindir,"libweber-sound.$(weber_sound_version).dylib")
  if isfile(weber_build)
    info("Using Makefile generated library $weber_build.")
    cp(weber_build,weber_sound)
  else
    original_path = "/usr/local/opt/portaudio/lib/libportaudio.2.dylib"
    download("http://haberdashpi.github.io/libweber-sound."*
             "$(weber_sound_version).dylib",weber_sound)
    run(`install_name_tool -change $original_path $portaudio $weber_sound`)
  end
elseif is_linux()
    error("Linux is not supported at this time.")
else
  error("Unsupported operating system.")
end

@assert portaudio != "UNKNOWN"
@assert weber_sound != "UNKNOWN"

deps = joinpath(dirname(@__FILE__),"deps.jl")
open(deps,"w") do s
  for (var,val) in [:weber_portaudio => portaudio,
                    :weber_sound => weber_sound]
    println(s,"const $var = \"$val\"")
  end
end


text:
"""
    chcat(x...)

Concatenate the image data along the dimension corresponding to the channels.
Image data should be stored in WHCN order (width, height, channels, batch) or
WHDCN (width, height, depth, channels, batch) in 3D context. Channels are
assumed to be the penultimate dimension.

# Example
```julia
julia> x1 = rand(32, 32, 4, 6); # a batch of 6 images (32x32) with 4 channels

julia> x2 = rand(32, 32, 4, 6); # a batch of 6 images (32x32) with 4 channels

julia> chcat(x1, x2) |> size
(32, 32, 8, 6)
```
"""
chcat(x...) = cat(x...; dims = (x[1] |> size |> length) - 1)

"""
    checksize(sz; padding, nlevels)
Check if an image size is appropriate with a given U-Net architecture. sz could
be either an `Int` or a `Tuple` of `Int`.
"""
function checksize(sz::Int; padding, nlevels) # mod(sz, 2^nlevels) == 0
    # number of trimmed pixels due to convolutions
    pl = padding ? 0 : 4
    chk = true
    sz -= pl
    for l ∈ 1:nlevels
        if iseven(sz)
            sz ÷= 2  # MaxPool
            sz -= pl # pixel trimming
        else
            chk = false
            break
        end
    end
    chk
end

checksize(sz::Tuple; kwargs...) = @. checksize(sz; kwargs...)

"""
    minsize(; padding, nlevels)
    minsize(p, n)
Computes the minimal image size for a given U-Net architecture defined by
`padding` and `nlevels`.
"""
minsize(; padding, nlevels) = padding ? 4 * 2^nlevels : 3 * 2^(nlevels + 2) - 4

minsize(p, n) = minsize(padding = p, nlevels = n)

# Internal use
trim(l, nlvl) = -(2^(l + 2) - 3 * 2^(nlvl + 1)) ÷ 2^(l - 1)

"""
    outputsize(sz; padding, nlevels)
Computes output size for a given U-Net architecture defined by
`padding` and `nlevels`.
"""
function outputsize(sz; padding, nlevels)
    if padding
        os = sz
    else
        tr = trim(1, nlevels)
        os = @. sz - 2 * tr - 8
    end
    os
end

outputsize(sz, p, n) = outputsize(sz; padding = p, nlevels = n)

"""
    adjustsize(sz; padding, nlevels)
Computes an image size compatible with a gigen U-Net architecture, from a given
image size `sz` (`Int` or `Tuple` of `Int`).
"""
function adjustsize(sz::Int; padding, nlevels)
    # Number of trimmed pixels if unpadded convolutions
    trm = padding ? 0 : (2 * trim(1, nlevels) + 8)
    sz += trm
    # Minimal size required for UNet
    smin =  minsize(padding, nlevels)
    if sz < smin
        ns = smin
    else
        # Ensure that each entry in MaxPool is even
        stp = 2^nlevels
        k = ceil(Int, (sz - smin) / stp)
        ns = smin + k * stp
    end
    ns
end

adjustsize(sz::Int, p, n) = adjustsize(sz, padding = p, nlevels = n)

adjustsize(sz::Tuple, p, n) = adjustsize(sz, padding = p, nlevels = n)

adjustsize(sz::Tuple; kwargs...) = @. adjustsize(sz; kwargs...)

"""
    padding(sz; padding, nlevels)
Computes two tuples of padding values for both input image and ground truth image.
- `sz`: size of input/ground truth image
- `padding`: indicates if convolutions are padded or not
- `nlevels`: number of levels in U-Net architecture

# Example
```julia
julia> using Images

julia> using UNet: padding

julia> img = fill(RGB(1, 1, 1), (256, 256));

julia> gth = fill(RGB(1, 1, 1), (256, 256));

julia> ip, gp = padding(size(img), padding = false, nlevels = 4)
(((94, 94), (94, 94)), ((2, 2), (2, 2)))

julia> pimg = padarray(img, Pad(:reflect, ip...));

julia> pgth = padarray(gth, Pad(:reflect, gp...));
```
"""
function padding(sz; padding, nlevels)
    ns = adjustsize(sz, padding, nlevels)
    pa = @. (ns - sz) / 2
    # lower edge padding for input
    ilo = floor.(Int, pa)
    # upper edge padding for input
    ihi = ceil.(Int, pa)
    # Compute output size
    os = padding ? ns : (@. ns - 2 * trim(1, nlevels) - 8)
    pa = @. (os - sz) / 2
    # lower edge padding for ground truth
    glo = floor.(Int, pa)
    # upper edge padding for ground truth
    ghi = ceil.(Int, pa)
    (ilo, ihi), (glo, ghi)
end


text:
using Evolutionary

nworks = 2
distributed_ga(localcpu=nworks)

gene = IntegerGene(10, "index")

npop = 2 * nworks
warmup_pop = Vector{Individual}(undef, npop)
for i in 1:npop
    warmup_pop[i] = AbstractGene[gene]
end

npop = 10 * nworks
pop = Vector{Individual}(undef, npop)
for i in 1:npop
    pop[i] = AbstractGene[gene]
end

@everywhere IntegerGene(:FM)
@everywhere Crossover(:SPX)
@everywhere Selection(:RWS)

@everywhere function objfun(chrom ::Individual)
    return abs( bin(chrom[1]) - 501 )
end

for i in 1:2
    res = ga( objfun, warmup_pop,
              parallel   = true ,
              nworkers   = nworks ,
              iterations = 2 )
end

res = ga( objfun, pop,
          parallel   = true ,
          nworkers   = nworks ,
          iterations = 10 )

nothing


text:
module CellNumberReindexTests

using Test
using Gridap
using Gridap.CellValuesGallery
using Gridap.CellMapApply: IndexCellMapFromKernel
using ..CellValuesMocks

a = [1,2,4,5,2,4,6,7,4,3,5,1,2,3]
ca = CellValueFromArray(a)
b = [10,11,3,1]
cb = CellValueFromArray(b)

cc = reindex(ca,cb)

d = a[b]
test_index_cell_number(cc,d)

b = [10,10,10,10]
cb = TestIterCellValue(10,4)

cc = reindex(ca,cb)
d = a[b]
test_iter_cell_value(cc,d)

end # module


text:
using POMDPs, Crux, Flux, POMDPGym
import POMDPPolicies:FunctionPolicy
import Distributions:Uniform
using Random
using Distributions

## Pendulum
mdp = PendulumPOMDP(actions=[-2., -0.5, 0, 0.5, 2.])
as = [actions(mdp)...]
amin = [-2f0]
amax = [2f0]
rand_policy = FunctionPolicy((s) -> Float32.(rand.(Uniform.(amin, amax))))
S = state_space(mdp, σ=[3.14f0, 8f0])

# Define the networks we will use
QSA() = ContinuousNetwork(Chain(Dense(3, 64, relu), Dense(64, 64, relu), Dense(64, 1)))
QS() = DiscreteNetwork(Chain(Dense(2, 64, relu), Dense(64, 64, relu), Dense(64, length(as))), as)
V() = ContinuousNetwork(Chain(Dense(2, 64, relu), Dense(64, 64, relu), Dense(64, 1)))
A() = ContinuousNetwork(Chain(Dense(2, 64, relu), Dense(64, 64, relu), Dense(64, 1, tanh), x -> 2f0 * x), 1)
SG() = SquashedGaussianPolicy(ContinuousNetwork(Chain(Dense(2, 64, relu), Dense(64, 64, relu), Dense(64, 1))), zeros(Float32, 1), 2f0)

# Solve with REINFORCE (Generally doesn't learn much, ~15 secs)
𝒮_reinforce = REINFORCE(π=SG(), S=S, N=100000, ΔN=2048, a_opt=(batch_size=512,))
@time π_reinforce = solve(𝒮_reinforce, mdp)

# Solve with A2C (Generally doesn't learn much, ~1 min)
𝒮_a2c = A2C(π=ActorCritic(SG(), V()), S=S, N=100000, ΔN=2048, a_opt=(batch_size=512,))
@time π_a2c = solve(𝒮_a2c, mdp)

# Solve with PPO (gets to > -200 reward, ~1.5 min)
𝒮_ppo = PPO(π=ActorCritic(SG(), V()), S=S, N=100000, ΔN=2048, a_opt=(batch_size=512,), λe=0f0)
@time π_ppo = solve(𝒮_ppo, mdp)

# Solve with DQN (gets to > -200 reward, ~30 sec)
𝒮_dqn = DQN(π=QS(), S=S, N=30000)
@time π_dqn = solve(𝒮_dqn, mdp)

off_policy = (S=S,
              ΔN=50,
              N=30000,
              buffer_size=Int(5e5),
              buffer_init=1000,
              c_opt=(batch_size=100, optimizer=ADAM(1e-3)),
              a_opt=(batch_size=100, optimizer=ADAM(1e-3)),
              π_explore=FirstExplorePolicy(1000, rand_policy, GaussianNoiseExplorationPolicy(0.5f0, a_min=[-2.0], a_max=[2.0])))

# Solver with DDPG
𝒮_ddpg = DDPG(;π=ActorCritic(A(), QSA()), off_policy...)
@time π_ddpg = solve(𝒮_ddpg, mdp)

# Solve with TD3
𝒮_td3 = TD3(;π=ActorCritic(A(), DoubleNetwork(QSA(), QSA())), off_policy...)
@time π_td3 = solve(𝒮_td3, mdp)

# Solve with SAC
𝒮_sac = SAC(;π=ActorCritic(SG(), DoubleNetwork(QSA(), QSA())), off_policy...)
@time π_sac = solve(𝒮_sac, mdp)

# Plot the learning curve
p = plot_learning([𝒮_reinforce, 𝒮_a2c, 𝒮_ppo, 𝒮_dqn, 𝒮_ddpg, 𝒮_td3, 𝒮_sac], title="Pendulum Swingup Training Curves", labels=["REINFORCE", "A2C", "PPO", "DQN", "DDPG", "TD3", "SAC"], legend=:right)
Crux.savefig("examples/rl/pendulum_benchmark.pdf")

# Produce a gif with the final policy
gif(mdp, π_dqn, "pendulum.gif", max_steps=200)

## Save data for imitation learning
# using BSON
# s = Sampler(mdp, 𝒮_ppo.π, max_steps=200, required_columns=[:t])
#
# data = steps!(s, Nsteps=10000)
# sum(data[:r])/50
# data[:expert_val] = ones(Float32, 1, 10000)
#
# data = ExperienceBuffer(data)
# BSON.@save "examples/il/expert_data/pendulum.bson" data


text:
@testset "low volume fraction 3D acoustics" begin

## Test low volume fraction

spatial_dim = 3
medium = Acoustic(spatial_dim; ρ=1.2, c=1.5)

volfrac = 0.02
s1 = Specie(
    Acoustic(spatial_dim; ρ=2.2, c=3.1), Sphere(0.4);
    volume_fraction = volfrac / 2.0
)

s2 = Specie(
    Acoustic(spatial_dim; ρ=12.2, c=23.1), Sphere(0.2);
    volume_fraction = volfrac / 2.0
)
species = [s1,s2]

ω = 1.9

kp_lowvol = wavenumber_low_volumefraction(ω, medium, species; basis_order=2)

AP_kps = wavenumbers(ω, medium, species; basis_order=2,
    num_wavenumbers = 2, mesh_size = 2.0, mesh_points = 4,
    symmetry = PlanarAzimuthalSymmetry())

@test abs(AP_kps[1] - kp_lowvol) / abs(kp_lowvol) < 10 * volfrac^3

end

max_stars_repo_name: arturgower/EffectiveWaves


text:
# polygons, part of Luxor module

"""
Draw a polygon.

    poly(pointlist::Array, action = :nothing; close=false, reversepath=false)

A polygon is an Array of Points. By default `poly()` doesn't close or fill the polygon,
to allow for clipping.
"""
function poly(pointlist::Array, action = :nothing; close=false, reversepath=false)
    # where pointlist is array of Points
    if action != :path
        newpath()
    end
    if reversepath
        reverse!(pointlist)
    end
    move(pointlist[1].x, pointlist[1].y)
    for p in pointlist[2:end]
        line(p.x, p.y)
    end
    if close
        closepath()
    end
    do_action(action)
end

"""
Find the bounding box of a polygon (array of points).

    polybbox(pointlist::Array)

Return the two opposite corners (suitable for `box()`, for example).
"""
function polybbox(pointlist::Array)
    lowx, lowy = pointlist[1].x, pointlist[1].y
    highx, highy = pointlist[end].x, pointlist[end].y
    for p in pointlist
        p.x < lowx  && (lowx  = p.x)
        p.y < lowy  && (lowy  = p.y)
        p.x > highx && (highx = p.x)
        p.y > highy && (highy = p.y)
    end
    return [Point(lowx, lowy), Point(highx, highy)]
end

"""
Find the centroid of simple polygon.

    polycentroid(pointlist)

Returns a point. This only works for simple (non-intersecting) polygons.

You could test the point using `isinside()`.
"""
function polycentroid(pointlist)
    # if Points are immutable, then use separate variables for these calculations
    centroid_x = 0
    centroid_y = 0
    signedArea = 0.0
    vertexCount = length(pointlist)
    x0 = 0.0 # Current vertex X
    y0 = 0.0 # Current vertex Y
    x1 = 0.0 # Next vertex X
    y1 = 0.0 # Next vertex Y
    a = 0.0  # Partial signed area

    # For all vertices except last
    i = 1
    for i in 1:vertexCount-1
        x0 = pointlist[i].x
        y0 = pointlist[i].y
        x1 = pointlist[i+1].x
        y1 = pointlist[i+1].y
        a = x0*y1 - x1*y0
        signedArea += a
        centroid_x += (x0 + x1)*a
        centroid_y += (y0 + y1)*a
   end
    # Do last vertex separately to avoid performing an expensive
    # modulus operation in each iteration.
    x0 = pointlist[vertexCount].x
    y0 = pointlist[vertexCount].y
    x1 = pointlist[1].x
    y1 = pointlist[1].y
    a = x0*y1 - x1*y0
    signedArea += a
    centroid_x += (x0 + x1)*a
    centroid_y += (y0 + y1)*a
    signedArea *= 0.5
    centroid_x /= (6.0 * signedArea)
    centroid_y /= (6.0 * signedArea)

    return Point(centroid_x, centroid_y)
end

"""
Sort the points of a polygon into order. Points are sorted according to the angle they make
with a specified point.

    polysortbyangle(pointlist::Array, refpoint=minimum(pointlist))

The `refpoint` can be chosen, but the minimum point is usually OK too:

    polysortbyangle(parray, polycentroid(parray))
"""
function polysortbyangle(pointlist::Array, refpoint=minimum(pointlist))
    angles = Float64[]
    for pt in pointlist
        push!(angles, atan2(refpoint.y - pt.y, refpoint.x - pt.x))
    end
    return pointlist[sortperm(angles)]
end

"""
Sort a polygon by finding the nearest point to the starting point, then
the nearest point to that, and so on.

    polysortbydistance(p, starting::Point)

You can end up with convex (self-intersecting) polygons, unfortunately.
"""
function polysortbydistance(pointlist, starting::Point)
    route = [starting]
    # start with the first point in pointlist
    remaining = setdiff(pointlist, route)
    while length(remaining) > 0
        # find the nearest point to the current position on the route
        nearest = first(sort!(remaining, lt = (x, y) -> norm(route[end], x) < norm(route[end], y)))
        # add this to the route and remove from remaining points
        push!(route, nearest)
        shift!(remaining)
    end
    return route
end

"""
Use a non-recursive Douglas-Peucker algorithm to simplify a polygon. Used by `simplify()`.

    douglas_peucker(pointlist::Array, start_index, last_index, epsilon)
"""
function douglas_peucker(pointlist::Array, start_index, last_index, epsilon)
    temp_stack = Tuple{Int,Int}[] # version 0.4 only?
    push!(temp_stack, (start_index, last_index))
    global_start_index = start_index
    keep_list = trues(length(pointlist))
    while length(temp_stack) > 0
        start_index = first(temp_stack[end])
        last_index =  last(temp_stack[end])
        pop!(temp_stack)
        dmax = 0.0
        index = start_index
        for i in index + 1:last_index - 1
            if (keep_list[i - global_start_index])
                d = point_line_distance(pointlist[i], pointlist[start_index], pointlist[last_index])
                if d > dmax
                    index = i
                    dmax = d
                end
            end
        end
        if dmax > epsilon
            push!(temp_stack, (start_index, index))
            push!(temp_stack, (index, last_index))
        else
            for i in start_index + 2:last_index - 1 # 2 seems to keep the starting point...
                keep_list[i - global_start_index] = false
            end
        end
    end
    return pointlist[keep_list]
end

"""
Simplify a polygon:

    simplify(pointlist::Array, detail=0.1)

`detail` is probably the smallest permitted distance between two points in pixels.
"""

function simplify(pointlist, detail=0.1)
    douglas_peucker(pointlist, 1, length(pointlist), detail)
end

"""
Find the vertices of a regular n-sided polygon centred at `x`, `y`:

    ngon(x, y, radius, sides=5, orientation=0, action=:nothing; vertices=false, reversepath=false)

`ngon()` draws the shapes: if you just want the raw points, use keyword argument `vertices=true`, which returns the array of points instead. Compare:

```julia
ngon(0, 0, 4, 4, 0, vertices=true) # returns the polygon's points:

    4-element Array{Luxor.Point,1}:
    Luxor.Point(2.4492935982947064e-16,4.0)
    Luxor.Point(-4.0,4.898587196589413e-16)
    Luxor.Point(-7.347880794884119e-16,-4.0)
    Luxor.Point(4.0,-9.797174393178826e-16)

whereas

ngon(0, 0, 4, 4, 0, :close) # draws a polygon
```
"""

function ngon(x::Real, y::Real, radius::Real, sides::Int64=5, orientation=0, action=:nothing; vertices=false, reversepath=false)
  ptlist = [Point(x+cos(orientation + n * 2pi/sides) * radius,
                  y+sin(orientation + n * 2pi/sides) * radius) for n in 1:sides]
  if vertices
    return ptlist
  else
    poly(ptlist, action, close=true, reversepath=reversepath)
  end
end

"""
Draw a regular polygon centred at point `p`:

    ngon(centerpos, radius, sides=5, orientation=0, action=:nothing; vertices=false, reversepath=false)

"""

ngon(centrepoint::Point, radius::Real, sides::Int64=5, orientation=0, action=:nothing; kwargs...) = ngon(centrepoint.x, centrepoint.y, radius, sides, orientation, action; kwargs...)

"""
Make a star:

    star(xcenter, ycenter, radius, npoints=5, ratio=0.5, orientation=0, action=:nothing; vertices = false, reversepath=false)

Use `vertices=true` to return the vertices of a star instead of drawing it.
"""

function star(x::Real, y::Real, radius::Real, npoints::Int64=5, ratio::Real=0.5, orientation=0, action=:nothing; vertices = false, reversepath=false)
    outerpoints = [Point(x+cos(orientation + n * 2pi/npoints) * radius,
                    y+sin(orientation + n * 2pi/npoints) * radius) for n in 1:npoints]
    innerpoints = [Point(x+cos(orientation + (n + 1/2) * 2pi/npoints) * (radius * ratio),
                    y+sin(orientation + (n + 1/2) * 2pi/npoints) * (radius * ratio)) for n in 1:npoints]
    result = Point[]
    for i in eachindex(outerpoints)
        push!(result, outerpoints[i])
        push!(result, innerpoints[i])
    end
    if reversepath
        result = reverse(result)
    end
    if vertices
      return result
    else
      poly(result, action, close=true)
    end
end

"""
Draw a star centered at a position:

    star(center, radius, npoints=5, ratio=0.5, orientation=0, action=:nothing; vertices = false, reversepath=false)
"""

star(centerpoint::Point, radius::Real, npoints::Int64=5, ratio::Real=0.5, orientation=0, action=:nothing; vertices = false, reversepath=false) = star(centerpoint.x, centerpoint.y, radius, npoints, ratio, orientation, action; vertices = vertices, reversepath=reversepath)

"""
Is a point `p` inside a polygon `pol`?

    isinside(p, pol)

Returns true or false.

This is an implementation of the Hormann-Agathos (2001) Point in Polygon algorithm
"""
function isinside(p::Point, pointlist::Array)
    c = false
    detq(q1, q2) = (q1.x - p.x) * (q2.y - p.y) - (q2.x - p.x) * (q1.y - p.y)
    for counter in 1:length(pointlist)
        q1 = pointlist[counter]
        # if reached last point, set "next point" to first point
        if counter == length(pointlist)
            q2 = pointlist[1]
        else
            q2 = pointlist[counter + 1]
        end
        if q1 == p
            error("VertexException")
        end
        if q2.y == p.y
            if q2.x == p.x
                error("VertexException")
            elseif (q1.y == p.y) && ((q2.x > p.x) == (q1.x < p.x))
                error("EdgeException")
            end
        end
        if (q1.y < p.y) != (q2.y < p.y) # crossing
            if q1.x >= p.x
                if q2.x > p.x
                    c = !c
                elseif ((detq(q1,q2) > 0) == (q2.y > q1.y)) # right crossing
                    c = !c
                end
            elseif q2.x > p.x
                if ((detq(q1,q2) > 0) == (q2.y > q1.y))     # right crossing
                    c = !c
                end
            end
        end
    end
    return c
end

"""
Split a polygon into two where it intersects with a line:

    polysplit(p, p1, p2)

This doesn't always work, of course. (Tell me you're not surprised.) For example, a polygon the shape of the
letter "E" might end up being divided into more than two parts.
"""
function polysplit(pointlist, p1, p2)
    poly1 = []
    poly2 = []
    i = 1
    for i in 1:length(pointlist)-1
        s = ((p2.x - p1.x) * (pointlist[i].y - p1.y)) - ((p2.y - p1.y) * (pointlist[i].x - p1.x))
        flag, intersectpoint = intersection(pointlist[i], pointlist[i+1], p1, p2)
        if flag
            push!(poly1, intersectpoint)
            push!(poly2, intersectpoint)
        end
        if s > 0
            push!(poly1, pointlist[i])
        elseif isapprox(s, 0.0)
            push!(poly1, pointlist[i])
            push!(poly2, pointlist[i])
        else
            push!(poly2, pointlist[i])
        end
    end
    # don't forget last point to first
    i += 1
    s = ((p2.x - p1.x) * (pointlist[i].y - p1.y)) - ((p2.y - p1.y) * (pointlist[i].x - p1.x))
    flag, intersectpoint = intersection(pointlist[i], pointlist[1], p1, p2)
    if flag
        push!(poly1, intersectpoint)
        push!(poly2, intersectpoint)
    end
    if s > 0
        push!(poly1, pointlist[i])
    elseif isapprox(s, 0.0)
        push!(poly1, pointlist[i])
        push!(poly2, pointlist[i])
    else
        push!(poly2, pointlist[i])
    end

    return(poly1, poly2)
end

"""
Draw the polygon defined by points in `pointlist`, possibly closing and reversing it, using the current parameters,
and then evaluate (using `eval`, *shudder*) the expression at every vertex of the polygon. For example, you can mark each vertex of a polygon with a filled circle.

    prettypoly(pointlist::Array,
      action = :nothing,
      vertex_action::Expr = :(circle(0, 0, 1, :fill));
      close=false,
      reversepath=false)

Example:

    prettypoly(pl, :fill, :(scale(0.1, 0.1);
                            circle(0, 0, 10, :fill)
                           ),
              close=false)

The expression can't use definitions that are not in scope, eg you can't pass a variable in from the calling
function and expect this function to know about it. Yes, not tidy...
"""
function prettypoly(pointlist::Array, action = :nothing, vertex_action::Expr = :(circle(0, 0, 1, :fill)); close=false, reversepath=false)
    # by default doesn't close or fill, to allow for clipping etc
    if action != :path
        newpath()
    end
    if reversepath
        reverse!(pointlist)
    end
    move(pointlist[1].x, pointlist[1].y)
    for p in pointlist[2:end]
        line(p.x, p.y)
    end
    if close
        closepath()
    end
    do_action(action)
    for p in pointlist
        gsave()
        translate(p.x, p.y)
        eval(vertex_action)
        grestore()
    end
end

# end


text:
using InteractiveUtilsPlus
using Test

@testset "InteractiveUtilsPlus.jl" begin
    # Write your tests here.
end


text:
using Calc
using Test

@testset "Calc.jl" begin
    # Write your tests here.
end

max_stars_repo_name: jlvvlj/Calcul

max_issues_repo_name: jlvvlj/Calcul

max_forks_repo_name: jlvvlj/Calcul


text:
#!/usr/bin/env julia

# Uses the EnsembleSampler to explore the posterior.
# In contrast to codes like mach_three.jl, this architecture means that within each likelihood call, the global lnprob for all channels is evaluated in *serial*, while the walkers themselves are parallelized.

using ArgParse

s = ArgParseSettings()
@add_arg_table s begin
    "--p", "-p"
    help = "number of processes to add"
    arg_type = Int
    default = 0
    "--run_index", "-r"
    help = "Output run index"
    arg_type = Int
    "--chain"
    help = "Write the chain to ~/web/ directory?"
    action = :store_true
    "--config"
    help = "a YAML configuration file"
    default = "config.yaml"
    "--cpus"
    help = "Which CPUS to add"
    arg_type = Array{Int, 1}
    eval_arg = true
end

parsed_args = parse_args(ARGS, s)

cpus = parsed_args["cpus"]

if cpus != nothing
    using ClusterManagers
    addprocs(LocalAffinityManager(;affinities=cpus))
end

# Since we've made this a #!/usr/bin/env julia script, we can no longer specify the extra
# processors via the julia executable, so we need to ghost this behavior back in.
if parsed_args["p"] > 0
    addprocs(parsed_args["p"])
end

import YAML
config = YAML.load(open(parsed_args["config"]))

outfmt(run_index::Int) = config["out_base"] * @sprintf("run%02d/", run_index)

# This code is necessary for multiple simultaneous runs on odyssey
# so that different runs do not write into the same output directory
if parsed_args["run_index"] == nothing
    run_index = 0
    outdir = outfmt(run_index)
    while ispath(outdir)
        println(outdir, " exists")
        run_index += 1
        outdir = outfmt(run_index)
    end
else
    run_index = parsed_args["run_index"]
    outdir = outfmt(run_index)
    println("Deleting old $outdir")
    run(`rm -rf $outdir`)
end

# make the output directory
println("Creating ", outdir)
mkdir(outdir)

@everywhere using DiskJockey.constants
@everywhere using DiskJockey.visibilities
@everywhere using DiskJockey.image
@everywhere using DiskJockey.gridding
@everywhere using DiskJockey.tmodel
@everywhere using Base.Test

# load data and figure out how many channels
dvarr = DataVis(config["data_file"])
nchan = length(dvarr)

if haskey(config, "exclude")
    exclude = config["exclude"]
    # which channels of the dset to fit
    keylist = filter(x->(!in(x, exclude)), Int[i for i=1:nchan])
else
    keylist = Int[i for i=1:nchan]
end

# go through any previously created directories and remove them
function cleardirs!(keylist::Vector{Int})
    println("Removing old directories")
    for key in keylist
        keydir = basedir * "jud$key"
        run(`rm -rf $keydir`)
    end
    println("Removed directories")
end

# This program is meant to be started with the -p option.
nchild = nworkers()
println("Workers allocated ", nchild)

# @everywhere using Logging

# Delete the old log file (if it exists)
logf = outdir * "log.log"
if isfile(logf)
    rm(logf)
end

# make the values of run_index and config available on all processes
for process in procs()
    @spawnat process global run_id=run_index
    @spawnat process global cfg=config
    @spawnat process global kl=keylist
    @spawnat process global logfile=logf
end
println("Mapped variables to all processes")

# Add radmc3d everywhere
@everywhere ENV["PATH"] = ENV["PATH"] * ":/n/home07/iczekala/.build/radmc-3d/version_0.38/src"

# change the default logger
# @everywhere Logging.configure(filename=logfile, level=DEBUG)

# debug("Created logfile.")

# Now, redo this to only load the dvarr for the keys that we need, and conjugate
@everywhere dvarr = DataVis(cfg["data_file"], kl)
@everywhere visibilities.conj!(dvarr)
@everywhere nchan = length(dvarr)
@everywhere max_base = max_baseline(dvarr)
# Convert this to dRA
@everywhere dRA_max = 1/(nyquist_factor * max_base * 1e3) / arcsec # [arcsec]

@everywhere const global species = cfg["species"]

@everywhere basefmt(id::Int) = cfg["base_dir"] * @sprintf("run%02d/", id)

@everywhere const global basedir = basefmt(run_id)

@everywhere const global npix = cfg["npix"] # number of pixels, can alternatively specify x and y separately

# Keep track of the current home directory
@everywhere const global homedir = pwd() * "/"

# make the internal Judith directory, if it doesn't exist
if !ispath(basedir)
    println("Creating ", basedir)
    mkdir(basedir)
end

# Clear all directories
cleardirs!(keylist)

# Create the model grid
@everywhere grd = cfg["grid"]

# Calculate the lnprior based upon the current parameter values
@everywhere function lnprior(pars::Parameters)

    # distance prior now specified from config file.
    mu_d, sig_d = cfg["parameters"]["dpc"]

    dlow = mu_d - 3. * sig_d
    dhigh = mu_d + 3. * sig_d

    # and we have a hard +/- 3 sigma cutoff
    if (pars.dpc < dlow) || (pars.dpc > dhigh)
        return -Inf
    end

    # Geometrical inclination prior
    return -0.5 * (pars.dpc - mu_d)^2 / sig_d^2 + log10(0.5 * sind(pars.incl))
end

# Only calculate the interpolation closures if we are fixing distance.
if cfg["fix_d"]

    angular_width = (1.1 * 2 * grd["r_out"])/cfg["parameters"]["dpc"][1] # [radians]

    # npix = get_nyquist_pixel(max_base, angular_width)

    # Simply calculate pix_AU as 1.1 * (2 * r_out) / npix
    # This is assuming that RADMC always calculates the image as 110% the full extent of the grid
    @everywhere pix_AU = (1.1 * 2 * grd["r_out"]) / npix # [AU/pixel]

    # Ignore the sin, since we use small angle approximation
    @everywhere dl = pix_AU/cfg["parameters"]["dpc"][1] * arcsec

    @everywhere uu = fftshift(fftfreq(npix, dl)) * 1e-3 # [kλ]
    @everywhere vv = fftshift(fftfreq(npix, dl)) * 1e-3 # [kλ]

    # For each channel, also calculate the interpolation closures
    @everywhere int_arr = Array(Function, nchan)
    @everywhere for (i, dset) in enumerate(dvarr)
        int_arr[i] = plan_interpolate(dset, uu, vv)
    end
end

# This function is fed to the EnsembleSampler
# That means, using the currently available global processes, like the data visibilities,
# and it must create it's own temporary directory to write the necessary files for
# RADMC to run.
@everywhere function fprob(p::Vector{Float64})

    # Fix the following arguments: gamma, dpc
    gamma = cfg["parameters"]["gamma"][1] # surface temperature gradient exponent

    if cfg["fix_d"]
        dpc = cfg["parameters"]["dpc"][1] # [pc] distance
        M_star, r_in, r_out, T_10, q, logM_gas, ksi, incl, PA, vel, mu_RA, mu_DEC = p
    else
        M_star, r_in, r_out, T_10, q, logM_gas, ksi, dpc, incl, PA, vel, mu_RA, mu_DEC = p
    end

    # Enforce hard priors on physical parameters
    # Short circuit evaluation if we know the RADMC won't be valid.
    if M_star <= 0.0 || ksi <= 0. || T_10 <= 0. || r_in <= 0.0 || r_in > r_out || T_10 > 1500. || q < 0. || q > 1.0
        return -Inf
    end

    if r_in > grd["r_out"] || r_out > grd["r_out"] || r_in < grd["r_in"]
        return -Inf
    end

    if incl < 0. || incl > 180.
        return -Inf
    end

    if PA < 0. || PA > 360.
        return -Inf
    end

    M_gas = 10^logM_gas

    # If we are going to fit with some parameters dropped out, here's the place to do it
    pars = Parameters(M_star, r_in, r_out, T_10, q, gamma, M_gas, ksi, dpc, incl, PA, vel, mu_RA, mu_DEC)

    lnpr = lnprior(pars)
    if lnpr == -Inf
        return -Inf
    end

    # Then to an upper limit on the physical width of the image, given the current distance.
    phys_width_lim = pars.dpc * dRA_max * npix # [AU]

    # Now see if the image is larger than this
    if (1.1 * 2 * grd["r_out"]) > phys_width_lim
        println("Proposed disk r_out too large for given distance and number of pixels. Increase number of pixels in image to sample sufficiently high spatial frequencies. ", pars.dpc, " ", grd["r_out"], " ", phys_width_lim)
        return -Inf
    end

    # Now that we've decided to go ahead, we need to create a temporary directory

    # debug("p :", p)
    # Each walker needs to create it's own temporary directory
    # where all RADMC files will reside and be driven from
    # It only needs to last for the duration of this function, so let's use a tempdir
    keydir = mktempdir() * "/"

    # Copy all relevant configuration scripts to this subdirectory
    # these are mainly setup files that will be static throughout the run
    # they were written by DJInitialize.jl and write_grid()
    for fname in ["radmc3d.inp", "wavelength_micron.inp", "lines.inp", "molecule_" * molnames[species] * ".inp"]
        ff = homedir * fname
        run(`cp $ff $keydir`)
    end

    # change the subprocess to reside in this directory for the remainder of the run
    # where it will drive its own independent RADMC3D process for a subset of channels
    cd(keydir)

    grid = Grid(grd["nr"], grd["ntheta"], grd["r_in"], grd["r_out"], true)
    write_grid(keydir, grid)

    # Compute parameter file using model.jl, write to disk in current directory
    write_model(pars, keydir, grid, species)

    # We are using the following conventions: inclination ranges from
    # 0 to 180 degrees. 0 means face on, angular momentum vector pointing
    # at observer; 90 means edge on; and 180 means face on, angular momentum
    # vector pointing away from observer.
    # These are the same as the RADMC-3D conventions.
    incl = pars.incl # [deg]

    # We also adopt the RADMC-3D convention for position angle, which defines position angle
    # by the angular momentum vector.
    # A positive PA angle means the disk angular momentum vector will be
    # rotated counter clockwise (from North towards East).
    PA = pars.PA # [deg]

    vel = pars.vel # [km/s]

    # Doppler shift the dataset wavelengths to rest-frame wavelength
    beta = vel/c_kms # relativistic Doppler formula
    lams = Array(Float64, nchan)
    for i=1:nchan
        lams[i] =  dvarr[i].lam * sqrt((1. - beta) / (1. + beta)) # [microns]
    end

    write_lambda(lams, keydir) # write into current directory

    # Run RADMC-3D, redirect output to /dev/null
    run(pipeline(`radmc3d image incl $incl posang $PA npix $npix loadlambda`, DevNull))

    # println("Successfully ran RADMC")
    # Read the RADMC-3D images from disk (we should already be in sub-directory)
    # im = imread()
    im = try
        imread()
    # If the synthesized image is screwed up, just say there is zero probability.
    catch SystemError
        println("Failed to read synthesized image for parameters ", p)
        -Inf
    end

    if im == -Inf
        run(`rm -rf $keydir`)
        return -Inf
    end

    if cfg["fix_d"]
        # After the fact, we should be able to check that the pixel size of the image is the
        # same as the one we originally calculated from the outer disk radius.
        @assert abs((im.pixsize_x/AU  - pix_AU)/pix_AU) < 1e-5

        # If we aren't fixing distance, then the pixel size is read directly from the calculated image.
    end

    # Convert raw images to the appropriate distance
    skim = imToSky(im, pars.dpc)

    # Apply the gridding correction function before doing the FFT
    # No shift needed, since we will shift the resampled visibilities
    corrfun!(skim)

    lnprobs = Array(Float64, nchan)
    # Do the Fourier domain stuff per channel
    for i=1:nchan
        dv = dvarr[i]
        # FFT the appropriate image channel
        vis_fft = transform(skim, i)

        if cfg["fix_d"]
            # Interpolate the `vis_fft` to the same locations as the DataSet
            mvis = int_arr[i](dv, vis_fft)
        else
            mvis = ModelVis(dv, vis_fft)
        end

        # Apply the phase shift here
        phase_shift!(mvis, pars.mu_RA, pars.mu_DEC)

        # Calculate chi^2 between these two
        lnprobs[i] = lnprob(dv, mvis)
    end

    # remove the temporary directory in which we currently reside
    run(`rm -rf $keydir`)

    # Sum them all together and feed back to the master process
    lnp = sum(lnprobs) + lnpr

    return lnp

end

using NPZ

pos0 = npzread(config["pos0"])
ndim, nwalkers = size(pos0)

# Use the EnsembleSampler to do the optimization
using DiskJockey.EnsembleSampler

sampler = Sampler(nwalkers, ndim, fprob)

# make sure that we've loaded a pos0 with the right dimensions.
@assert ndim < nwalkers "More dimensions than walkers. Are you sure you loaded pos0 correctly?"

run_schedule(sampler, pos0, config["samples"], config["loops"], outdir)

write_samples(sampler, outdir)

max_stars_repo_name: elnjensen/DiskJockey

max_issues_repo_name: elnjensen/DiskJockey

max_forks_repo_name: elnjensen/DiskJockey


text:
function fixedpoint(Γ, x, iterations = 10^5, r_norm = norm, r_abstol = sqrt(eps(eltype(x))))
    f = Γ(x)
    fnext = Γ(f)
    for i = 1:iterations
        if r_norm(fnext-f) <= r_abstol
            return fnext, f, :success
        end
        f = copy(fnext)
        fnext = Γ(f)
    end
    if r_norm(fnext-f) <= r_abstol
        return fnext, f, :success
    end
    fnext, f, :failure
end


text:
function is_int(s)
	i = firstindex(s)
	l = lastindex(s)
	@goto S0

	@label S0
	if i > l
		@goto S4
	elseif s[i] == '+' || s[i] == '-'
		i = nextind(s, i)
		@goto S1
	elseif '0' <= s[i] && s[i] <= '9'
		i = nextind(s, i)
		@goto S2
	else
		@goto S4
	end

	@label S1

	@label S2

	@label S3
	return true

	@label S4
	return false
end

tests = [
	 ("", false)
	 (" ", false)
	 ("+", false)
	 ("-", false)
	 ("++", false)
	 ("--", false)
	 ("+0+", false)
	 ("-0-", false)
	 ("+0123456789", true)
	 ("-0123456789", true)
	 ("0123456789", true)
	 ]

for t in tests
    println("$(t[2] == is_int(t[1]) ? "OK" : "NG")\t'$(t[1])'")
end


text:
# Hacks that can be ripped out once we support device overrides

function LinearAlgebra.norm(v::ROCArray{T}, p::Real=2) where {T}
    if p == Inf
        maximum(abs.(v))
    elseif p == -Inf
        minimum(abs.(v))
    else
        mapreduce(x->AMDGPU.pow(AMDGPU.abs(x), p), +, v; init=zero(T))^(1/p)
    end
end

@inline function ssqs(x::T, y::T) where T<:Real
    k::Int = 0
    ρ = x*x + y*y
    if isfinite(ρ) && (isinf(x) || isinf(y))
        ρ = convert(T, Inf)
    elseif isinf(ρ) || (ρ==0 && (x!=0 || y!=0)) || ρ<nextfloat(zero(T))/(2*eps(T)^2)
        m::T = max(abs(x), abs(y))
        k = m==0 ? m : exponent(m)
        xk, yk = ldexp(x,-k), ldexp(y,-k)
        ρ = xk*xk + yk*yk
    end
    ρ, k
end

@inline function sqrt(z::Complex)
    z = float(z)
    x, y = reim(z)
    if x==y==0
        return Complex(zero(x),y)
    end
    ρ, k::Int = ssqs(x, y)
    if isfinite(x)
         ρ=ldexp(abs(x),-k)+sqrt(ρ)
    end
    if isodd(k)
        k = div(k-1,2)
    else
        k = div(k,2)-1
        ρ += ρ
    end
    ρ = ldexp(sqrt(ρ),k) #sqrt((abs(z)+abs(x))/2) without over/underflow
    ξ = ρ
    η = y
    if ρ != 0
        if isfinite(η)
            η=(η/ρ)/2
        end
        if x<0
            ξ = abs(η)
            η = copysign(ρ,y)
        end
    end
    Complex(ξ,η)
end

import Statistics
function Statistics.corzm(x::ROCArray{<:Any, 2}, vardim::Int=1)
    c = Statistics.unscaled_covzm(x, vardim)
    return Statistics.cov2cor!(c, sqrt.(LinearAlgebra.diag(c)))
end

import Random
function Random.randn!(rng::GPUArrays.RNG, A::ROCArray{T}) where T<:Union{Float16, Float32, Float64}
    elements = (length(A) - 1) ÷ 2 + 1
    length(A) == 0 && return
    function _randn!_kernel(ctx, a, randstates)
        idx = 2*(GPUArrays.linear_index(ctx) - 1) + 1
        U1 = GPUArrays.gpu_rand(T, ctx, randstates)
        U2 = GPUArrays.gpu_rand(T, ctx, randstates)
        Z0 = sqrt(T(-2.0)*log(U1))*cos(T(2pi)*U2)
        Z1 = sqrt(T(-2.0)*log(U1))*sin(T(2pi)*U2)
        @inbounds a[idx] = Z0
        idx + 1 > length(a) && return
        @inbounds a[idx + 1] = Z1
        return
    end
    gpu_call(ROCArrayBackend(), _randn!_kernel, (A, rng.state); elements)
    A
end


text:
using OpenQuantumBase, Test

η = 1e-4;T = 16
X = ConstantCouplings(["Z"])
bath_x = Ohmic(η, 1, T)
Z = ConstantCouplings(["X"])
bath_z = Ohmic(η, 4, T)

inter_x = Interaction(X, bath_x)
inter_z = Interaction(Z, bath_z)

inter_set = InteractionSet(inter_x, inter_z)

U(t) = exp(-1.0im * σz * t)
CGL = OpenQuantumBase.cg_from_interactions(inter_set, U, 10, 10, 1e-4, 1e-4)
@test length(CGL) == 1
@test CGL[1].kernels[1][2] == X
@test CGL[1].kernels[2][2] == Z
@test CGL[1].kernels[1][3][1,1](0.2, 0.1) ≈ correlation(0.1, bath_x)


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

mutable struct VpnClientRevokedCertificatePropertiesFormat <: SwaggerModel
    thumbprint::Any # spec type: Union{ Nothing, String } # spec name: thumbprint
    provisioningState::Any # spec type: Union{ Nothing, String } # spec name: provisioningState

    function VpnClientRevokedCertificatePropertiesFormat(;thumbprint=nothing, provisioningState=nothing)
        o = new()
        validate_property(VpnClientRevokedCertificatePropertiesFormat, Symbol("thumbprint"), thumbprint)
        setfield!(o, Symbol("thumbprint"), thumbprint)
        validate_property(VpnClientRevokedCertificatePropertiesFormat, Symbol("provisioningState"), provisioningState)
        setfield!(o, Symbol("provisioningState"), provisioningState)
        o
    end
end # type VpnClientRevokedCertificatePropertiesFormat

const _property_map_VpnClientRevokedCertificatePropertiesFormat = Dict{Symbol,Symbol}(Symbol("thumbprint")=>Symbol("thumbprint"), Symbol("provisioningState")=>Symbol("provisioningState"))
const _property_types_VpnClientRevokedCertificatePropertiesFormat = Dict{Symbol,String}(Symbol("thumbprint")=>"String", Symbol("provisioningState")=>"String")
Base.propertynames(::Type{ VpnClientRevokedCertificatePropertiesFormat }) = collect(keys(_property_map_VpnClientRevokedCertificatePropertiesFormat))
Swagger.property_type(::Type{ VpnClientRevokedCertificatePropertiesFormat }, name::Symbol) = Union{Nothing,eval(Meta.parse(_property_types_VpnClientRevokedCertificatePropertiesFormat[name]))}
Swagger.field_name(::Type{ VpnClientRevokedCertificatePropertiesFormat }, property_name::Symbol) =  _property_map_VpnClientRevokedCertificatePropertiesFormat[property_name]

function check_required(o::VpnClientRevokedCertificatePropertiesFormat)
    true
end

function validate_property(::Type{ VpnClientRevokedCertificatePropertiesFormat }, name::Symbol, val)
end


text:
function Base.show(io::IO, m::Gurobi.Model)

    @printf "%0s \n" "Gurobi Model"
    @printf "   %-15s : %10s \n" "sense " Gurobi.model_sense(m) == :maximize ? "maximize" : "minimize"
    @printf "   %-15s = %10s \n" "variables" Gurobi.num_vars(m)
    @printf "   %-15s = %10s \n" "constraints" Gurobi.num_constrs(m)
    @printf "   %-15s = %10s \n" "coefficients" Gurobi.num_cnzs(m)
end

function change_objective_coef(lp::Gurobi.Model, objective::Number, value::Number = 1.0)
	obj = zeros(Float64, Gurobi.num_vars(lp))
	obj[objective] = value
	Gurobi.set_objcoeffs!(lp, obj)
	update_model!(lp)
end

function change_objective_coef{T <: Number}(lp::Gurobi.Model, objective::Array{T}, value::Array=[])
	if value == []
		value = ones(Float64, length(objective))
	end
	obj = zeros(Float64, Gurobi.num_vars(lp))
	obj[objective] = value
	Gurobi.set_objcoeffs!(lp, obj)
	update_model!(lp)
end

function get_variable_bounds(lp::Gurobi.Model)
	lb = Gurobi.get_dblattrarray(lp, "lb", 1, Gurobi.num_vars(lp))
	ub = Gurobi.get_dblattrarray(lp, "ub", 1, Gurobi.num_vars(lp))
	return lb, ub
end

function get_variable_bounds(lp::Gurobi.Model, index::Number)
	lb = Gurobi.get_dblattrarray(lp, "lb", index, index)[1]
	ub = Gurobi.get_dblattrarray(lp, "ub", index, index)[1]
	return lb, ub
end

function get_constraint_bounds(lp::Gurobi.Model)
	b = Gurobi.get_dblattrarray(lp, "RHS", 1, Gurobi.num_constrs(lp))
	return b,b
end

function get_constraint_matrix(lp::Gurobi.Model)
	return Gurobi.get_constrmatrix(lp)
end

function get_direction(lp::Gurobi.Model)
	Gurobi.model_sense(lp) == :maximize ? "maximize" : "minimize"
end

function get_objective_value(lp::Gurobi.Model)
	return Gurobi.get_objval(lp)
end

function get_reduced_costs(lp::Gurobi.Model)
	Gurobi.get_dblattrarray(lp, "RC", 1, Gurobi.num_vars(lp))
end

function get_solution(lp::Gurobi.Model)
	return Gurobi.get_solution(lp)
end

function get_solution_status(lp::Gurobi.Model)
	code = get_solution_status_code(lp)
	if code == 2
		return "Optimal"
	elseif code == 3
		return "Infeasible"
	elseif code == 4
		return "Infeasible or Unbounded"
	elseif code == 5
		return "Unbound"
	elseif code == 13 #SUBOPTIMAL
		return "Feasible"
	else
		return warn(string("Unknown status code: ", code))
	end
end

function get_solution_status_code(lp::Gurobi.Model)
	return Gurobi.get_status_code(lp)
end

function get_slack(lp::Gurobi.Model)
	Gurobi.get_dblattrarray(lp, "Pi", 1,Gurobi.num_constrs(lp))
end

function get_objective(lp::Gurobi.Model)
	Gurobi.get_dblattrarray(lp, "Obj", 1, Gurobi.num_vars(lp))
end

function set_direction(lp::Gurobi.Model, direction::AbstractString)
	lowercase(direction) == "max" ? Gurobi.set_sense!(lp, :maximize) : Gurobi.set_sense!(lp, :minimize)
	update_model!(lp)
end

function set_col_bounds(lp::Gurobi.Model, index::Number, lb::Number, ub::Number)
	lower, upper = get_variable_bounds(lp)
	lower[index] = lb
	upper[index] = ub
	Gurobi.set_dblattrarray!(lp, "LB", 1, num_vars(lp), lower)
	Gurobi.set_dblattrarray!(lp, "UB", 1, num_vars(lp), upper)
	update_model!(lp)
end

function set_col_bounds(lp::Gurobi.Model, index::Number, fixed_value::Number)
	set_col_bounds(lp, index, fixed_value, fixed_value)
end

function set_objective(lp::Gurobi.Model, objective::Number, value::Number = 1.0)
	obj = Gurobi.get_dblattrarray(lp, "Obj", 1, num_vars(lp))
	obj[objective] = value
	Gurobi.set_dblattrarray!(lp, "Obj", 1, num_vars(lp), obj)
	update_model!(lp)
end

function setup_gurobi(model::Model, objective::AbstractString = "max")
	env = Gurobi.Env()
	setparam!(env,"OutputFlag",0)
	setparam!(env,"Method",0)

	lp = Gurobi.Model(env, "god", :maximize)

	add_cvars!(lp, model.c, model.lb, model.ub)
	update_model!(lp)

	add_constrs!(lp, model.S, fill('=', length(model.b)), model.b)

	update_model!(lp)

	return lp
end

#function setup_gurobi{T <: Number}(c::Array{T}, lb::Array{T}, ub::Array{T}, b::Array{T}, S::SparseMatrixCSC, objective::AbstractString = "max")
#function setup_gurobi{T <: Number}(c::Array{T}, lb::Array{T}, ub::Array{T}, beq::Array{T}, Seq::SparseMatrixCSC, bineq::Array{T}, Sineq::SparseMatrixCSC, objective::AbstractString = "max")

function solve(lp::Gurobi.Model)
	return Gurobi.optimize(lp)
end

function solver_status(lp::Gurobi.Model)
    string(Gurobi.status_symbols[get_solution_status_code(lp)])
end

max_stars_repo_name: isebarn/CBM

max_issues_repo_name: isebarn/CBM

max_forks_repo_name: isebarn/CBM


text:
(function()
  local x::Int64 = 0x02
  local y = 0x02
  @assert typeof(x) == Int64  # The UInt8 was converted
  @assert typeof(y) == UInt8  # No annotations, no coversion

  # There's no conversion from String to Int64
  @assert isa(try x = "Oh no" catch (e) e end, Exception)
end)()

max_stars_repo_name: idrougge/ple

max_issues_repo_name: idrougge/ple

max_forks_repo_name: idrougge/ple


text:
##
##  Java Information Dynamics Toolkit (JIDT)
##  Copyright (C) 2012, Joseph T. Lizier
##
##  This program is free software: you can redistribute it and/or modify
##  it under the terms of the GNU General Public License as published by
##  the Free Software Foundation, either version 3 of the License, or
##  (at your option) any later version.
##
##  This program is distributed in the hope that it will be useful,
##  but WITHOUT ANY WARRANTY; without even the implied warranty of
##  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
##  GNU General Public License for more details.
##
##  You should have received a copy of the GNU General Public License
##  along with this program.  If not, see <http://www.gnu.org/licenses/>.
##

# Example 6 - Mutual information calculation with dynamic specification of calculator

# This example shows how to write Julia code to take advantage of the
#  common interfaces defined for various information-theoretic calculators.
# Here, we use the common form of the infodynamics.measures.continuous.MutualInfoCalculatorMultiVariate
#  interface (which is never named here) to write common code into which we can plug
#  one of three concrete implementations (kernel estimator, Kraskov estimator or
#  linear-Gaussian estimator) by dynamically supplying the class name of
#  the concrete implementation.

# Import the JavaCall package:
using JavaCall;

# Change location of jar to match yours:
jarLocation = "../../infodynamics.jar";
# Start the JVM supplying classpath and heap size
#  (increase memory here if you get crashes due to not enough space)
JavaCall.init(["-Djava.class.path=$(jarLocation)", "-Xmx128M"]);

#---------------------
# 1. Properties for the calculation (these are dynamically changeable, you could
#    load them in from another properties file):
# The name of the data file (relative to this directory)
datafile = "../data/4ColsPairedNoisyDependence-1.txt";
# List of column numbers for variables 1 and 2:
#  (you can select any columns you wish to be contained in each variable)
variable1Columns = [1,2]; # array indices start from 1 in Julia
variable2Columns = [3,4];
# The name of the concrete implementation of the interface
#  infodynamics.measures.continuous.MutualInfoCalculatorMultiVariate
#  which we wish to use for the calculation.
# Note that one could use any of the following calculators (try them all!):
#  implementingClass = "infodynamics.measures.continuous.kraskov.MutualInfoCalculatorMultiVariateKraskov1"; % MI([1,2], [3,4]) = 0.36353
#  implementingClass = "infodynamics.measures.continuous.kernel.MutualInfoCalculatorMultiVariateKernel";
#  implementingClass = "infodynamics.measures.continuous.gaussian.MutualInfoCalculatorMultiVariateGaussian";
implementingClass = "infodynamics.measures.continuous.kraskov.MutualInfoCalculatorMultiVariateKraskov1";

#---------------------
# 2. Load in the data
data = readdlm(datafile, ' ', '\n')
# Pull out the columns from the data set which correspond to each of variable 1 and 2:
variable1 = data[:, variable1Columns];
variable2 = data[:, variable2Columns];

#---------------------
# 3. Dynamically instantiate an object of the given class:
# Since @jimport uses the provided text directly (rather than evaluating a variable)
#  we need to do some Julia interpolation of $implementingClass to get our
#  dynamic reference to the class.
miCalcClass = eval(:(@jimport $implementingClass));
miCalc = miCalcClass(());

#---------------------
# 4. Start using the MI calculator, paying attention to only
#  call common methods defined in the interface type
#  infodynamics.measures.continuous.MutualInfoCalculatorMultiVariate
#  not methods only defined in a given implementation class.
# a. Initialise the calculator to use the required number of
#   dimensions for each variable:
jcall(miCalc, "initialise", Void, (jint,jint), length(variable1Columns), length(variable2Columns));
# b. Supply the observations to compute the PDFs from:

# For the moment we have to exit this example here::
@printf("We're stuck at this point until support for multidimensional arrays is included in JavaCall");
exit();

jcall(miCalc, "setObservations", Void, (Array{jdouble,2}, Array{jdouble,2}), variable1, variable2);
# c. Make the MI calculation:
miValue = jcall(miCalc, "computeAverageLocalOfObservations", jdouble, ());
@printf("MI calculator %s\ncomputed the joint MI as %.5f\n",
		implementingClass, miValue);

max_issues_repo_name: jmmccracken/ECA


text:
module TR55

# Calculates the runoff (in) based off:
# S (potential maximum retention after runoff begins)
# P (rainfall (in))
function runoff(S::Number, P::Number)
    Q = (P - (0.2 * S))^2 / (P + (0.8 * S))

    return round(Q, 2)
end

# Calculates the potential maximum retention
# after runoff begins based off:
# CN (runoff curve number)
function max_retention(CN::Int64)
    S = (1000 / CN) - 10

    return round(S, 2)
end

# Calculates the weighted curve number
# for a watershed.
# region - array of dicts w/ the following structure:
#   [
#       {
#           "cn" => 61,
#           "area" => 30
#       },
#       {
#           "cn" => 74,
#           "area" => 70
#       },
#   ]
# area_is_percent - boolean indicating whether or not
# the region areas are measured in percent of area,
# instead of acres or sq mi, etc.
function weighted_cn(regions::Array{Dict{Any,Any}},
                     area_is_percent::Bool)

    total_area = reduce(+, map(x -> x["area"], regions))

    if area_is_percent && total_area != 100
        error("Using percents areas requires that " *
              "region areas sum to 100")
    end

    total_product = reduce(+, map(x -> x["area"] * x["cn"], regions))
    weighted_CN = total_product / total_area

    return convert(Int64, round(weighted_CN))
end

end # module


text:
############
# BuildRef #
############

mutable struct BuildRef
    repo::String  # the build repo
    sha::String   # the build + status SHA
    vinfo::String # versioninfo() taken during the build
end

BuildRef(repo, sha) = BuildRef(repo, sha, "retrieving versioninfo() failed")

function Base.:(==)(a::BuildRef, b::BuildRef)
    return (a.repo == b.repo &&
            a.sha == b.sha &&
            a.vinfo == b.vinfo)
end

Base.summary(build::BuildRef) = string(build.repo, SHA_SEPARATOR, snipsha(build.sha))

# reduce download bandwidth and time by keeping copies after the build
# TODO: intercept JLDOWNLOAD instead?
function sync_srcs!(fromdir, todir, link::Bool)
    mkpath(fromdir)
    mkpath(todir)
    for n in readdir(fromdir)
        endswith(n, ".tmp") && continue
        src = abspath(fromdir, n)
        dst = abspath(todir, n)
        if isfile(src) && !islink(src) && !ispath(dst)
            if link
                symlink(src, dst)
            else
                dsttmp = dst * ".tmp"
                cp(src, dsttmp, force=true)
                chmod(dsttmp, 0o444)
                Base.Filesystem.rename(dsttmp, dst, force=true) # mv is implemented badly in Base, so avoid it
            end
        end
    end
end

# if a PR number is included, attempt to build from the PR's merge commit
# FIXME: re-use PkgEval's BinaryBuilder-based build
function build_julia!(config::Config, build::BuildRef, logpath, prnumber::Union{Int,Nothing}=nothing)
    # make a temporary workdir for our build
    builddir = mktempdir(workdir(config))
    mirrordir = joinpath(workdir(config), "mirrors", config.trackrepo)
    mkpidlock(mirrordir * ".lock") do
        if ispath(joinpath(mirrordir))
            run(setenv(`git fetch --quiet --all`; dir=mirrordir))
        else
            mkpath(mirrordir)
            gitclone!(config.trackrepo, mirrordir, `--mirror`)
        end
    end

    # clone/fetch the appropriate Julia version
    if prnumber !== nothing
        # clone from `trackrepo`, not `build.repo`, since that's where the merge commit is
        gitclone!(config.trackrepo, builddir, `--reference $mirrordir --dissociate`)
        try
            run(setenv(`git fetch --quiet origin +refs/pull/$(prnumber)/merge:`; dir=builddir))
        catch
            # if there's not a merge commit on the remote (likely due to
            # merge conflicts) then fetch the head commit instead.
            run(setenv(`git fetch --quiet origin +refs/pull/$(prnumber)/head:`; dir=builddir))
        end
        run(setenv(`git checkout --quiet --force FETCH_HEAD`; dir=builddir))
        build.sha = readchomp(setenv(`git rev-parse HEAD`; dir=builddir))
    else
        gitclone!(build.repo, builddir, `--reference $mirrordir --dissociate`)
        run(setenv(`git checkout --quiet $(build.sha)`; dir=builddir))
    end

    # set up logs for STDOUT and STDERR
    logname = string(build.sha, "_build")
    outfile = joinpath(logpath, string(logname, ".out"))
    errfile = joinpath(logpath, string(logname, ".err"))

    mirrordir1 = joinpath(workdir(config), "srccache", "deps")
    srccache1 = joinpath(builddir, "deps", "srccache")
    mirrordir2 = joinpath(workdir(config), "srccache", "stdlib")
    srccache2 = joinpath(builddir, "stdlib", "srccache")

    # TODO: support user build flags (like PkgEval)
    buildflags = ["JULIA_PRECOMPILE=0"]

    # run the build
    cpus = mycpus(config)
    sync_srcs!(mirrordir1, srccache1, true)
    sync_srcs!(mirrordir2, srccache2, true)
    run(pipeline(setenv(`make -j$(length(cpus)) --output-sync=target $buildflags`; dir=builddir), stdout=outfile, stderr=errfile))
    sync_srcs!(srccache1, mirrordir1, false)
    sync_srcs!(srccache2, mirrordir2, false)
    return builddir
end


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

"""
    CopyBackupToRegion()

Copy an AWS CloudHSM cluster backup to a different region.

# Required Parameters
- `BackupId`: The ID of the backup that will be copied to the destination region.
- `DestinationRegion`: The AWS region that will contain your copied CloudHSM cluster backup.

# Optional Parameters
- `TagList`: Tags to apply to the destination backup during creation. If you specify tags, only these tags will be applied to the destination backup. If you do not specify tags, the service copies tags from the source backup to the destination backup.
"""
copy_backup_to_region(BackupId, DestinationRegion; aws_config::AWSConfig=global_aws_config()) = cloudhsm_v2("CopyBackupToRegion", Dict{String, Any}("BackupId"=>BackupId, "DestinationRegion"=>DestinationRegion); aws_config=aws_config)
copy_backup_to_region(BackupId, DestinationRegion, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = cloudhsm_v2("CopyBackupToRegion", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("BackupId"=>BackupId, "DestinationRegion"=>DestinationRegion), args)); aws_config=aws_config)

"""
    CreateCluster()

Creates a new AWS CloudHSM cluster.

# Required Parameters
- `HsmType`: The type of HSM to use in the cluster. Currently the only allowed value is hsm1.medium.
- `SubnetIds`: The identifiers (IDs) of the subnets where you are creating the cluster. You must specify at least one subnet. If you specify multiple subnets, they must meet the following criteria:   All subnets must be in the same virtual private cloud (VPC).   You can specify only one subnet per Availability Zone.

# Optional Parameters
- `BackupRetentionPolicy`: A policy that defines how the service retains backups.
- `SourceBackupId`: The identifier (ID) of the cluster backup to restore. Use this value to restore the cluster from a backup instead of creating a new cluster. To find the backup ID, use DescribeBackups.
- `TagList`: Tags to apply to the CloudHSM cluster during creation.
"""
create_cluster(HsmType, SubnetIds; aws_config::AWSConfig=global_aws_config()) = cloudhsm_v2("CreateCluster", Dict{String, Any}("HsmType"=>HsmType, "SubnetIds"=>SubnetIds); aws_config=aws_config)
create_cluster(HsmType, SubnetIds, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = cloudhsm_v2("CreateCluster", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("HsmType"=>HsmType, "SubnetIds"=>SubnetIds), args)); aws_config=aws_config)

"""
    CreateHsm()

Creates a new hardware security module (HSM) in the specified AWS CloudHSM cluster.

# Required Parameters
- `AvailabilityZone`: The Availability Zone where you are creating the HSM. To find the cluster's Availability Zones, use DescribeClusters.
- `ClusterId`: The identifier (ID) of the HSM's cluster. To find the cluster ID, use DescribeClusters.

# Optional Parameters
- `IpAddress`: The HSM's IP address. If you specify an IP address, use an available address from the subnet that maps to the Availability Zone where you are creating the HSM. If you don't specify an IP address, one is chosen for you from that subnet.
"""
create_hsm(AvailabilityZone, ClusterId; aws_config::AWSConfig=global_aws_config()) = cloudhsm_v2("CreateHsm", Dict{String, Any}("AvailabilityZone"=>AvailabilityZone, "ClusterId"=>ClusterId); aws_config=aws_config)
create_hsm(AvailabilityZone, ClusterId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = cloudhsm_v2("CreateHsm", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("AvailabilityZone"=>AvailabilityZone, "ClusterId"=>ClusterId), args)); aws_config=aws_config)

"""
    DeleteBackup()

Deletes a specified AWS CloudHSM backup. A backup can be restored up to 7 days after the DeleteBackup request is made. For more information on restoring a backup, see RestoreBackup.

# Required Parameters
- `BackupId`: The ID of the backup to be deleted. To find the ID of a backup, use the DescribeBackups operation.

"""
delete_backup(BackupId; aws_config::AWSConfig=global_aws_config()) = cloudhsm_v2("DeleteBackup", Dict{String, Any}("BackupId"=>BackupId); aws_config=aws_config)
delete_backup(BackupId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = cloudhsm_v2("DeleteBackup", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("BackupId"=>BackupId), args)); aws_config=aws_config)

"""
    DeleteCluster()

Deletes the specified AWS CloudHSM cluster. Before you can delete a cluster, you must delete all HSMs in the cluster. To see if the cluster contains any HSMs, use DescribeClusters. To delete an HSM, use DeleteHsm.

# Required Parameters
- `ClusterId`: The identifier (ID) of the cluster that you are deleting. To find the cluster ID, use DescribeClusters.

"""
delete_cluster(ClusterId; aws_config::AWSConfig=global_aws_config()) = cloudhsm_v2("DeleteCluster", Dict{String, Any}("ClusterId"=>ClusterId); aws_config=aws_config)
delete_cluster(ClusterId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = cloudhsm_v2("DeleteCluster", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ClusterId"=>ClusterId), args)); aws_config=aws_config)

"""
    DeleteHsm()

Deletes the specified HSM. To specify an HSM, you can use its identifier (ID), the IP address of the HSM's elastic network interface (ENI), or the ID of the HSM's ENI. You need to specify only one of these values. To find these values, use DescribeClusters.

# Required Parameters
- `ClusterId`: The identifier (ID) of the cluster that contains the HSM that you are deleting.

# Optional Parameters
- `EniId`: The identifier (ID) of the elastic network interface (ENI) of the HSM that you are deleting.
- `EniIp`: The IP address of the elastic network interface (ENI) of the HSM that you are deleting.
- `HsmId`: The identifier (ID) of the HSM that you are deleting.
"""
delete_hsm(ClusterId; aws_config::AWSConfig=global_aws_config()) = cloudhsm_v2("DeleteHsm", Dict{String, Any}("ClusterId"=>ClusterId); aws_config=aws_config)
delete_hsm(ClusterId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = cloudhsm_v2("DeleteHsm", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ClusterId"=>ClusterId), args)); aws_config=aws_config)

"""
    DescribeBackups()

Gets information about backups of AWS CloudHSM clusters. This is a paginated operation, which means that each response might contain only a subset of all the backups. When the response contains only a subset of backups, it includes a NextToken value. Use this value in a subsequent DescribeBackups request to get more backups. When you receive a response with no NextToken (or an empty or null value), that means there are no more backups to get.

# Optional Parameters
- `Filters`: One or more filters to limit the items returned in the response. Use the backupIds filter to return only the specified backups. Specify backups by their backup identifier (ID). Use the sourceBackupIds filter to return only the backups created from a source backup. The sourceBackupID of a source backup is returned by the CopyBackupToRegion operation. Use the clusterIds filter to return only the backups for the specified clusters. Specify clusters by their cluster identifier (ID). Use the states filter to return only backups that match the specified state. Use the neverExpires filter to return backups filtered by the value in the neverExpires parameter. True returns all backups exempt from the backup retention policy. False returns all backups with a backup retention policy defined at the cluster.
- `MaxResults`: The maximum number of backups to return in the response. When there are more backups than the number you specify, the response contains a NextToken value.
- `NextToken`: The NextToken value that you received in the previous response. Use this value to get more backups.
- `SortAscending`: Designates whether or not to sort the return backups by ascending chronological order of generation.
"""
describe_backups(; aws_config::AWSConfig=global_aws_config()) = cloudhsm_v2("DescribeBackups"; aws_config=aws_config)
describe_backups(args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = cloudhsm_v2("DescribeBackups", args; aws_config=aws_config)

"""
    DescribeClusters()

Gets information about AWS CloudHSM clusters. This is a paginated operation, which means that each response might contain only a subset of all the clusters. When the response contains only a subset of clusters, it includes a NextToken value. Use this value in a subsequent DescribeClusters request to get more clusters. When you receive a response with no NextToken (or an empty or null value), that means there are no more clusters to get.

# Optional Parameters
- `Filters`: One or more filters to limit the items returned in the response. Use the clusterIds filter to return only the specified clusters. Specify clusters by their cluster identifier (ID). Use the vpcIds filter to return only the clusters in the specified virtual private clouds (VPCs). Specify VPCs by their VPC identifier (ID). Use the states filter to return only clusters that match the specified state.
- `MaxResults`: The maximum number of clusters to return in the response. When there are more clusters than the number you specify, the response contains a NextToken value.
- `NextToken`: The NextToken value that you received in the previous response. Use this value to get more clusters.
"""
describe_clusters(; aws_config::AWSConfig=global_aws_config()) = cloudhsm_v2("DescribeClusters"; aws_config=aws_config)
describe_clusters(args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = cloudhsm_v2("DescribeClusters", args; aws_config=aws_config)

"""
    InitializeCluster()

Claims an AWS CloudHSM cluster by submitting the cluster certificate issued by your issuing certificate authority (CA) and the CA's root certificate. Before you can claim a cluster, you must sign the cluster's certificate signing request (CSR) with your issuing CA. To get the cluster's CSR, use DescribeClusters.

# Required Parameters
- `ClusterId`: The identifier (ID) of the cluster that you are claiming. To find the cluster ID, use DescribeClusters.
- `SignedCert`: The cluster certificate issued (signed) by your issuing certificate authority (CA). The certificate must be in PEM format and can contain a maximum of 5000 characters.
- `TrustAnchor`: The issuing certificate of the issuing certificate authority (CA) that issued (signed) the cluster certificate. You must use a self-signed certificate. The certificate used to sign the HSM CSR must be directly available, and thus must be the root certificate. The certificate must be in PEM format and can contain a maximum of 5000 characters.

"""
initialize_cluster(ClusterId, SignedCert, TrustAnchor; aws_config::AWSConfig=global_aws_config()) = cloudhsm_v2("InitializeCluster", Dict{String, Any}("ClusterId"=>ClusterId, "SignedCert"=>SignedCert, "TrustAnchor"=>TrustAnchor); aws_config=aws_config)
initialize_cluster(ClusterId, SignedCert, TrustAnchor, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = cloudhsm_v2("InitializeCluster", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ClusterId"=>ClusterId, "SignedCert"=>SignedCert, "TrustAnchor"=>TrustAnchor), args)); aws_config=aws_config)

"""
    ListTags()

Gets a list of tags for the specified AWS CloudHSM cluster. This is a paginated operation, which means that each response might contain only a subset of all the tags. When the response contains only a subset of tags, it includes a NextToken value. Use this value in a subsequent ListTags request to get more tags. When you receive a response with no NextToken (or an empty or null value), that means there are no more tags to get.

# Required Parameters
- `ResourceId`: The cluster identifier (ID) for the cluster whose tags you are getting. To find the cluster ID, use DescribeClusters.

# Optional Parameters
- `MaxResults`: The maximum number of tags to return in the response. When there are more tags than the number you specify, the response contains a NextToken value.
- `NextToken`: The NextToken value that you received in the previous response. Use this value to get more tags.
"""
list_tags(ResourceId; aws_config::AWSConfig=global_aws_config()) = cloudhsm_v2("ListTags", Dict{String, Any}("ResourceId"=>ResourceId); aws_config=aws_config)
list_tags(ResourceId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = cloudhsm_v2("ListTags", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ResourceId"=>ResourceId), args)); aws_config=aws_config)

"""
    ModifyBackupAttributes()

Modifies attributes for AWS CloudHSM backup.

# Required Parameters
- `BackupId`: The identifier (ID) of the backup to modify. To find the ID of a backup, use the DescribeBackups operation.
- `NeverExpires`: Specifies whether the service should exempt a backup from the retention policy for the cluster. True exempts a backup from the retention policy. False means the service applies the backup retention policy defined at the cluster.

"""
modify_backup_attributes(BackupId, NeverExpires; aws_config::AWSConfig=global_aws_config()) = cloudhsm_v2("ModifyBackupAttributes", Dict{String, Any}("BackupId"=>BackupId, "NeverExpires"=>NeverExpires); aws_config=aws_config)
modify_backup_attributes(BackupId, NeverExpires, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = cloudhsm_v2("ModifyBackupAttributes", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("BackupId"=>BackupId, "NeverExpires"=>NeverExpires), args)); aws_config=aws_config)

"""
    ModifyCluster()

Modifies AWS CloudHSM cluster.

# Required Parameters
- `BackupRetentionPolicy`: A policy that defines how the service retains backups.
- `ClusterId`: The identifier (ID) of the cluster that you want to modify. To find the cluster ID, use DescribeClusters.

"""
modify_cluster(BackupRetentionPolicy, ClusterId; aws_config::AWSConfig=global_aws_config()) = cloudhsm_v2("ModifyCluster", Dict{String, Any}("BackupRetentionPolicy"=>BackupRetentionPolicy, "ClusterId"=>ClusterId); aws_config=aws_config)
modify_cluster(BackupRetentionPolicy, ClusterId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = cloudhsm_v2("ModifyCluster", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("BackupRetentionPolicy"=>BackupRetentionPolicy, "ClusterId"=>ClusterId), args)); aws_config=aws_config)

"""
    RestoreBackup()

Restores a specified AWS CloudHSM backup that is in the PENDING_DELETION state. For mor information on deleting a backup, see DeleteBackup.

# Required Parameters
- `BackupId`: The ID of the backup to be restored. To find the ID of a backup, use the DescribeBackups operation.

"""
restore_backup(BackupId; aws_config::AWSConfig=global_aws_config()) = cloudhsm_v2("RestoreBackup", Dict{String, Any}("BackupId"=>BackupId); aws_config=aws_config)
restore_backup(BackupId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = cloudhsm_v2("RestoreBackup", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("BackupId"=>BackupId), args)); aws_config=aws_config)

"""
    TagResource()

Adds or overwrites one or more tags for the specified AWS CloudHSM cluster.

# Required Parameters
- `ResourceId`: The cluster identifier (ID) for the cluster that you are tagging. To find the cluster ID, use DescribeClusters.
- `TagList`: A list of one or more tags.

"""
tag_resource(ResourceId, TagList; aws_config::AWSConfig=global_aws_config()) = cloudhsm_v2("TagResource", Dict{String, Any}("ResourceId"=>ResourceId, "TagList"=>TagList); aws_config=aws_config)
tag_resource(ResourceId, TagList, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = cloudhsm_v2("TagResource", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ResourceId"=>ResourceId, "TagList"=>TagList), args)); aws_config=aws_config)

"""
    UntagResource()

Removes the specified tag or tags from the specified AWS CloudHSM cluster.

# Required Parameters
- `ResourceId`: The cluster identifier (ID) for the cluster whose tags you are removing. To find the cluster ID, use DescribeClusters.
- `TagKeyList`: A list of one or more tag keys for the tags that you are removing. Specify only the tag keys, not the tag values.

"""
untag_resource(ResourceId, TagKeyList; aws_config::AWSConfig=global_aws_config()) = cloudhsm_v2("UntagResource", Dict{String, Any}("ResourceId"=>ResourceId, "TagKeyList"=>TagKeyList); aws_config=aws_config)
untag_resource(ResourceId, TagKeyList, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = cloudhsm_v2("UntagResource", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ResourceId"=>ResourceId, "TagKeyList"=>TagKeyList), args)); aws_config=aws_config)


text:
# ---
# title: 1311. Get Watched Videos by Your Friends
# id: problem1311
# author: Tian Jun
# date: 2020-10-31
# difficulty: Medium
# categories: Hash Table, String, Breadth-first Search
# link: <https://leetcode.com/problems/get-watched-videos-by-your-friends/description/>
# hidden: true
# ---
#
# There are `n` people, each person has a unique _id_ between `0` and `n-1`.
# Given the arrays `watchedVideos` and `friends`, where `watchedVideos[i]` and
# `friends[i]` contain the list of watched videos and the list of friends
# respectively for the person with `id = i`.
#
# Level **1** of videos are all watched videos by your friends, level **2** of
# videos are all watched videos by the friends of your friends and so on. In
# general, the level `k` of videos are all watched videos by people with the
# shortest path **exactly** equal to `k` with you. Given your `id` and the
# `level` of videos, return the list of videos ordered by their frequencies
# (increasing). For videos with the same frequency order them alphabetically
# from least to greatest.
#
#
#
# **Example 1:**
#
# **![](https://assets.leetcode.com/uploads/2020/01/02/leetcode_friends_1.png)**
#
#
#
#     Input: watchedVideos = [["A","B"],["C"],["B","C"],["D"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 1
#     Output: ["B","C"]
#     Explanation:
#     You have id = 0 (green color in the figure) and your friends are (yellow color in the figure):
#     Person with id = 1 -> watchedVideos = ["C"]
#     Person with id = 2 -> watchedVideos = ["B","C"]
#     The frequencies of watchedVideos by your friends are:
#     B -> 1
#     C -> 2
#
#
# **Example 2:**
#
# **![](https://assets.leetcode.com/uploads/2020/01/02/leetcode_friends_2.png)**
#
#
#
#     Input: watchedVideos = [["A","B"],["C"],["B","C"],["D"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 2
#     Output: ["D"]
#     Explanation:
#     You have id = 0 (green color in the figure) and the only friend of your friends is the person with id = 3 (yellow color in the figure).
#
#
#
#
# **Constraints:**
#
#   * `n == watchedVideos.length == friends.length`
#   * `2 <= n <= 100`
#   * `1 <= watchedVideos[i].length <= 100`
#   * `1 <= watchedVideos[i][j].length <= 8`
#   * `0 <= friends[i].length < n`
#   * `0 <= friends[i][j] < n`
#   * `0 <= id < n`
#   * `1 <= level < n`
#   * if `friends[i]` contains `j`, then `friends[j]` contains `i`
#
#
## @lc code=start
using LeetCode

## add your code here:
## @lc code=end