text:
## custom samplers for generating binomially distributed CuArrays

## COV_EXCL_START

function stirling_approx_tail(k)::Float32
    if k == 0
        return 0.0810614667953272f0
    elseif k == 1
        return 0.0413406959554092f0
    elseif k == 2
        return 0.0276779256849983f0
    elseif k == 3
        return 0.0207906721037650f0
    elseif k == 4
        return 0.0166446911898211f0
    elseif k == 5
        return 0.0138761288230707f0
    elseif k == 6
        return 0.0118967099458917f0
    elseif k == 7
        return 0.0104112652619720f0
    elseif k == 8
        return 0.00925546218271273f0
    elseif k == 9
        return 0.00833056343336287f0
    end
    kp1sq = (k + 1f0)^2;
    return (1.0f0 / 12 - (1.0f0 / 360 - 1.0f0 / 1260 / kp1sq) / kp1sq) / (k + 1)
end

# BTRS algorithm, adapted from the tensorflow library
# (github.com/tensorflow/tensorflow/blob/master/tensorflow/core/kernels/random_binomial_op.cc)
function kernel_BTRS!(
    A, count, prob,
    R1, R2, Rp, Ra,
    count_dim_larger_than_prob_dim,
    seed::UInt32
)
    i = (blockIdx().x - 1) * blockDim().x + threadIdx().x

    @inbounds Random.seed!(seed)

    @inbounds if i <= length(A)
        I  = Ra[i]
        Ip = Rp[I[1]]
        I1 = R1[Ip[1]]
        I2 = R2[Ip[2]]

        if count_dim_larger_than_prob_dim
            n = count[CartesianIndex(I1, I2)]
            p = prob[I1]
        else
            n = count[I1]
            p = prob[CartesianIndex(I1, I2)]
        end

        # edge cases
        if p <= 0 || n <= 0
            A[i] = 0
            return
        elseif p >= 1
            A[i] = n
            return
        end

        # Use naive algorithm for n <= 17
        if n <= 17
            k = 0
            ctr = 1
            while ctr <= n
                rand(Float32) < p && (k += 1)
                ctr += 1
            end
            A[i] = k
            return
        end

        # Use inversion algorithm for n*p < 10
        if n * p < 10f0
            logp = log(1f0-p)
            geom_sum = 0f0
            num_geom = 0
            while true
                geom      = ceil(log(rand(Float32)) / logp)
                geom_sum += geom
                geom_sum > n && break
                num_geom += 1
            end
            A[i] = num_geom
            return
        end

        # BTRS algorithm
        # BTRS approximations work well for p <= 0.5
        (invert = p > 0.5f0) && (p = 1f0 - p)

        r       = p/(1f0-p)
        s       = p*(1f0-p)

        stddev  = sqrt(n * s)
        b       = 1.15f0 + 2.53f0 * stddev
        a       = -0.0873f0 + 0.0248f0 * b + 0.01f0 * p
        c       = n * p + 0.5f0
        v_r     = 0.92f0 - 4.2f0 / b

        alpha   = (2.83f0 + 5.1f0 / b) * stddev;
        m       = floor((n + 1) * p)

        while true
            usample = rand(Float32) - 0.5f0
            vsample = rand(Float32)

            us = 0.5f0 - abs(usample)
            ks = floor((2 * a / us + b) * usample + c)

            if us >= 0.07f0 && vsample <= v_r
                break
            end

            if ks < 0 || ks > n
                continue
            end

            v2 = log(vsample * alpha / (a / (us * us) + b))
            ub = (m + 0.5f0) * log((m + 1) / (r * (n - m + 1))) +
                 (n + 1) * log((n - m + 1) / (n - ks + 1)) +
                 (ks + 0.5f0) * log(r * (n - ks + 1) / (ks + 1)) +
                 stirling_approx_tail(m) + stirling_approx_tail(n - m) -
                 stirling_approx_tail(ks) - stirling_approx_tail(n - ks)
            if v2 <= ub
                break
            end
        end

        # if p = 1 - p[i] was used, undo inversion
        invert && (ks = n - ks)
        A[i] = Int(ks);
        nothing
    end#if
    return
end

## COV_EXCL_STOP


text:
function rhs!(dxyz::Array{T,1},x::T,y::T,z::T,ρ::T,β::T,s_inv::T) where {T<:AbstractFloat}
    @inbounds dxyz[1] = y-x
    @inbounds dxyz[2] = x*(ρ-z*s_inv) - y
    @inbounds dxyz[3] = x*(y*s_inv) - β*z
    return dxyz
end

ext: jl


text:
using Vec
using Test
import LinearAlgebra: norm, normalize, dot
import Random: seed!

@test invlerp(0.0,1.0,0.5) ≈ 0.5
@test invlerp(0.0,1.0,0.4) ≈ 0.4
@test invlerp(0.0,1.0,0.7) ≈ 0.7
@test invlerp(10.0,20.0,12.0) ≈ 0.2

include("test_vecE2.jl")
include("test_vecE3.jl")
include("test_vecSE2.jl")
include("test_quat.jl")

include("test_coordinate_transforms.jl")
include("test_geomE2.jl")

include("test_diff.jl")


text:
using PSIS
using Test

@testset "PSIS.jl" begin
    include("utils.jl")
    include("generalized_pareto.jl")
    include("core.jl")
    include("ess.jl")
    include("plotting_backend.jl")
    include("plots.jl")
    include("makie.jl")
end


text:
module Pipeline

using ..RvSpectML

using RvSpectMLBase

using CSV, DataFrames #, Query
using Dates # for timing

include("extract_orders.jl")
export extract_orders

using ..EchelleCCFs
using ..EchelleInstruments
include("prep_line_list.jl")
export prepare_line_list

CCFs = EchelleCCFs
include("ccf_total.jl")
export ccf_total

include("ccf_orders.jl")
export ccf_orders

using ..EchelleCCFs.RVFromCCF
using Statistics
include("calc_rvs_from_ccf_total.jl")
export calc_rvs_from_ccf_total

end # module Pipeline


text:
# Autogenerated wrapper script for Libksba_jll for x86_64-apple-darwin
export libksba

using Libgpg_error_jll
JLLWrappers.@generate_wrapper_header("Libksba")
JLLWrappers.@declare_library_product(libksba, "@rpath/libksba.8.dylib")
function __init__()
    JLLWrappers.@generate_init_header(Libgpg_error_jll)
    JLLWrappers.@init_library_product(
        libksba,
        "lib/libksba.8.dylib",
        RTLD_LAZY | RTLD_DEEPBIND,
    )

    JLLWrappers.@generate_init_footer()
end  # __init__()


text:
using DSP

export dpDirect,
       RTMimaging

include("dpDirect.jl")
include("RTMimaging.jl")

max_stars_repo_name: WneleiGao/AcousticWaveLab

max_issues_repo_name: WneleiGao/AcousticWaveLab

max_forks_repo_name: WneleiGao/AcousticWaveLab


text:
@testmodule DataStreamTest begin
  using MLLibrary

  function test_DataSetCount()

    path = joinpath(Pkg.dir("MLLibrary"),"resources","datasets")
    @test MLLibrary.DataParser.DataStream.getDataSetCount(joinpath(path,"abalone.data")) ==4177
    @test MLLibrary.DataParser.DataStream.getDataSetCount(joinpath(path,"3percent-miscategorization.csv")) ==10000
    @test MLLibrary.DataParser.DataStream.getDataSetCount(joinpath(path,"10percent-miscatergorization.csv")) ==10000
    @test MLLibrary.DataParser.DataStream.getDataSetCount(joinpath(path,"Seperable.csv")) ==10000

  end

  function test_getFeatureCount()
    path = joinpath(Pkg.dir("MLLibrary"),"resources","datasets")
    @test MLLibrary.DataParser.DataStream.getFeatureCount(joinpath(path,"abalone.data")) ==9
    @test MLLibrary.DataParser.DataStream.getFeatureCount(joinpath(path,"3percent-miscategorization.csv")) ==10
    @test MLLibrary.DataParser.DataStream.getFeatureCount(joinpath(path,"10percent-miscatergorization.csv")) ==10
    @test MLLibrary.DataParser.DataStream.getFeatureCount(joinpath(path,"Seperable.csv")) ==10
  end

end

max_stars_repo_name: ajermaky/CustomMLLibrary

max_issues_repo_name: ajermaky/CustomMLLibrary

max_forks_repo_name: ajermaky/CustomMLLibrary


text:
"""
    Zero()
The additive identity for differentials.
This is basically the same as `0`.
"""
struct Zero <: AbstractDifferential end

extern(x::Zero) = false  # false is a strong 0. E.g. `false * NaN = 0.0`

Base.Broadcast.broadcastable(::Zero) = Ref(Zero())

Base.iterate(x::Zero) = (x, nothing)
Base.iterate(::Zero, ::Any) = nothing


text:
module TestExperiment

import Reproduce: Reproduce, experiment_wrapper
import ExampleExperiment: ExampleExperiment, Macros
import .Macros:  @generate_config_funcs, @info_str
import Random
import ProgressMeter: ProgressMeter, Progress

@generate_config_funcs begin

    info"""
    ## Document your config!
    - `seed::Int`: Seed of RNG.
    """
    "seed" => 1
    "steps" => 50

    info"""
    ## Agent params
    - `learning_update::String`: The update function.
    More params can be found with [`construct_learning_update`](@ref)

    """
    "learning_update" => "QLearning"
    "gamma" => 0.9

end

function main_experiment(config; progress=false, testing=false)
    Reproduce.experiment_wrapper(config; use_git_info=false, testing=testing) do config

        Random.seed!(config["seed"])

        results = zeros(config["steps"])
        lu = ExampleExperiment.construct_learning_update(config)

        prg_bar = Progress(config["steps"], desc="MyProgBar")
        for i in 1:config["steps"]
            results[i] = rand()
            sleep(0.1)
            if progress
                ProgressMeter.next!(prg_bar)
            end
        end

        results = (rews=rand(config["steps"]))
        (;save_results=results, learning_update=lu)
    end
end

function working_experiment(; kwargs...)

    config = default_config()
    for (k, v) in kwargs
        config[string(k)] = v
    end

    main_experiment(config; progress=true, testing=true)
end

end


text:
# Test Bayesian Detctor
include("./lib/metadata.jl")
include("./2bayes_detector_replica.jl")
include("./lib/SignalGenerator.jl")
include("./lib/roc.jl")

using SignalGenerator
using BayesChpOrig
using Metadata
using Roc

function run_sig_gen()
    ret = genSig(5, 100.0, 1.0, 2.0, 0.5, 1)
    sig = ret["sig"]
    chps= ret["changes"]
    writedlm(outdir*"testsig.txt", sig)
    writedlm(outdir*"testsigchps.txt", chps)
    print("run1")
end

function run_detector()
    # genSig(n, mu, sigma, changeStep, sigStd, errRate)
    # ret = genSig(5, 100.0, 2.0, 1.0, 0.5, 1)
    # ret = genSig(5, 100.0, 2.0, 0.15, 0.75, 1)
    ret = genSig(10, 100.0, 10.0, 1.3, 0.75, 1)
    # ret=genSig(5, 100.0, 2.0, 1.15, 1.0, 1)
    sig = ret["sig"]
    chps= ret["changes"]
    #matrix_max_vals, matrix = bayes_detector(sig, lambda=150)
    matrix_max_vals, matrix = bayes_detector(sig, lambda = 120)
    detections = extract_changes(matrix_max_vals)

    max_delay = 30
    tpr = tpRate(detections, chps, max_delay)
    fpr = faRateScaled(detections, chps, max_delay, length(sig), tn_price_scale=0.1)

    println("... test_bd > TPrate = ", tpr, " / FArate = ", fpr)

    writedlm(outdir*"test_bd_detections.txt", detections)
    writedlm(outdir*"test_bd_signal.txt", sig)
    writedlm(outdir*"test_bd_changes.txt", chps)
    writedlm(outdir*"test_bd_matrix.txt", matrix, ",")
    writedlm(outdir*"test_bd_matrix_max_vals.txt", matrix_max_vals, ",")

    # println("... test_bd > changes:", chps)
    # println("... test_bd > detections:", detections)
end
run_detector()

max_stars_repo_name: av-maslov/Recurrency

max_issues_repo_name: av-maslov/Recurrency

max_forks_repo_name: av-maslov/Recurrency


text:
using ModelStatisticsLH
using Test, Random

GS = ModelStatisticsLH;

@testset "All" begin
    include("var_info_test.jl")
    include("group_stats_test.jl");
    include("stats_collection_test.jl");
    include("reductions_test.jl");
end

# -----------


text:
"""
    MatAcoustFluidModule

Module for acoustic-fluid  material.
"""
module MatAcoustFluidModule

using FinEtools.FTypesModule: FInt, FFlt, FCplxFlt, FFltVec, FIntVec, FFltMat, FIntMat, FMat, FVec, FDataDict

# Class for acoustic fluid models of Mats.
struct MatAcoustFluid
  bulk_modulus::FFlt;# Bulk modulus
  mass_density::FFlt;# Mass density
end

# function update(self, ms, gradtheta, Rm; output = nothing, outputRm =nothing)
#   # # _Update_ material state.
#   # #
#   # # function [out, newms] = update (self, ms, context)
#   # #
#   # # Update material state.  Return the updated material state, and the
#   # # requested quantity (default is the heat flux).
#   # #
#   # # Arguments
#   # #     m=material
#   # #     ms = material state
#   # #     gradtheta= temperature gradient in the local material
#   # #           directions (which may be the same as the global coordinate
#   # #           directions)
#   # #     Rm = material orientation  matrix, may be supplied as empty  if it
#   # #           corresponds to an identity.
#   # #     and optional arguments
#   # #         output=type of quantity to output, and interpreted by the
#   # #           particular material; [] is returned when the material does not
#   # #           recognize the requested quantity to indicate uninitialized
#   # #           value.  It can be tested with isempty ().
#   # #              output ='flux' - heat flux vector in the local material
#   # #                      directions; this is the default
#   # #                      when output type is not specified.
#   # #         outputRm = orientation matrix  of the coordinate system in which
#   # #           the output should be calculated;  if this matrix is not supplied,
#   # #           it is assumed that the output is to be provided  in the local
#   # #           material coordinate system; otherwise the output is first
#   # #           transformed to the global coordinate system, and then to the
#   # #           output coordinate system.
#   # # Output
#   # #     out=requested quantity
#   # #     newms=new material state; don't forget that if the update is final
#   # #           the material state newms must be assigned and stored.  Otherwise
#   # #           the material update is lost!
#   # #
#   kappa = self.property.thermal_conductivity;
#   gradtheta = reshape (context.gradtheta, [],1);# make column vector
#   flux = - kappa * gradtheta;# in local material orientation coordinates
#   if outputRm!= nothing #  output coordinate system supplied?
#     if Rm!=nothing
#       flux = (Rm*flux);# in global coordinate system
#     end
#     flux = outputRm'*flux;# in output coordinate system
#   end
#   if output!= nothing
#     if output=="flux"
#       out = flux;
#     else
#       out = nothing;
#     end
#   else
#     out = flux;
#   end
#   return out, ms
# end

end


text:
"""
    DTensor{T,N} <: AbstractTensor{T,N}

wrapper for generic Array{T,N} to represent dense tensors.
"""
struct DTensor{T,N} <: AbstractTensor{T,N}
    array::Array{T,N}
end

DTensor(T::Type = ComplexF64) = DTensor{T,0}(Array{T,0}(undef))
DTensor{T,N}(ds::NTuple{N,Int}) where {T,N} = DTensor{T,N}(Array{T,N}(undef, ds...))
DTensor{T}(ds::NTuple{N,Int}) where {T,N} = DTensor{T,N}(ds)

function Base.show(io::IO, A::DTensor)
    print(io, typeof(A))
    print(io, A.array)
end

Base.ndims(A::DTensor) = ndims(A.array)
Base.getindex(A::DTensor, args...) = getindex(A.array, args...)
Base.setindex!(A::DTensor, args...) = setindex!(A.array, args...)
Base.size(A::DTensor,i...) = size(A.array,i...)
Base.isapprox(A::DTensor, B::DTensor) = A.array ≈ B.array
Base.:(==)(A::DTensor, B::DTensor) = A.array == B.array
Base.similar(A::DTensor, args...) = DTensor(Base.similar(A.array, args...))
Base.copy(A::DTensor) = DTensor(copy(A.array))
Base.copy!(dest::DTensor, source::DTensor) = DTensor(copy!(dest.array, source.array))
Base.copyto!(dest::DTensor, source::DTensor) = (Base.copyto!(dest.array, source.array); dest)
Base.eltype(A::DTensor{T,N}) where {T,N} = T
LA.diag(a::DTensor) = LA.diag(a.array,0)
toarray(a::DTensor) = a.array

function initwith!(A::DTensor{T,N}, fun) where {T,N}
    A.array .= fun(T, size(A))
    return A
end

initwithzero!(A::DTensor) = initwith!(A, zeros)
initwithrand!(A::DTensor) = initwith!(A, rand)


text:
@testset "NetCDF IO" begin

@testset "vector2range" begin
    th = collect(thourly)
    th2 = ClimateBase.vector2range(th)
    @test th2 isa AbstractRange
    @test th2 == th
end

@testset "NetCDF standard tests" begin
    globat = Dict("history" => "test")
    ncwrite("test.nc", (A, B); globalattr = globat)
    Aloaded = ncread("test.nc", "insolation")
    Bloaded = ncread("test.nc", "x2")

    @test A.data == Aloaded.data
    @test DimensionalData.metadata(dims(Aloaded, Lon))["units"] == "degrees_east"
    @test B.data == Bloaded.data
    @test string(Bloaded.name) == "x2"
    @test DimensionalData.metadata(dims(Bloaded, Time))["standard_name"] == "time"

    Bpartly = ncread("test.nc", "x2", ([1,4,5], :, 1:3))
    @test Bpartly.data[:, :, :] == Bloaded.data[[1,4,5], :, 1:3]

    ds = NCDataset("test.nc")
    @test ds.attrib["history"] == "test"
    close(ds)
    rm("test.nc")
end

@testset "NetCDF Coord tests" begin
    ncwrite("test.nc", C)
    n = string(DimensionalData.name(C))
    Cloaded = ncread("test.nc", "has_coords")
    @test size(Cloaded) == size(C)
    @test hasdim(Cloaded, Coord)
    @test gnv(dims(Cloaded, Coord)) == gnv(dims(C, Coord))
    @test gnv(Cloaded) == gnv(C)

    # TODO: Here we need a lot of tests for all the super weird different
    # ways that there are to save a Coord datafile... But we can't creat them.
    # So we need to upload files somewhere and load them here.
end

@testset "Missings handling" begin
    m = rand(Float64, length.((lons, lats)))
    midx = CartesianIndices(m)[1:2, :]
    L = length(midx)
    m[midx] .= -99.9
    M = ClimArray(m, (Lon(lons), Lat(lats)); attrib = Dict("_FillValue" => -99.9), name = "M")
    ncwrite("missing_test.nc", M)
    M2 = ncread("missing_test.nc", "M")
    for i in midx; @test ismissing(M2[i]); end
    # now test `missing_weights`
    B, W = missing_weights(M2)
    @test all(iszero, W.data[midx])
    @test all(isequal(-99.9), B.data[midx])
    mmean = mean(skipmissing(M2.data))
    bmean = mean(B, StatsBase.weights(W))
    @test bmean == mmean
    # test `missing_weights` application to zonal mean
    C = B[3:end, :]
    z1 = zonalmean(C)
    z2 = zonalmean(B, W)
    @test all(z1.data .≈ z2.data)
    rm("missing_test.nc")
end

end # NetCDF tests


text:
push!(LOAD_PATH,"../src/")

using TheDancer
using Plots
gr()

N, Edisorder, Jdisorder, modelJ, B, dipolestrength, r = init!(50, 0.0, 0.0, 0.5, 298, 7.5)

function main()
    S,E,H,psi,dipoles=prepare_model()
    density = abs.(psi.^2)
    dampening = 0.05

    SCFcycles=200
    Unitarycycles=500
    TotCycles = SCFcycles+Unitarycycles

    Energies = SCFthenUnitary(dampening, SCFcycles, Unitarycycles,true)

    plot(Energies'[1:TotCycles])
      for i in 2:10
          plot!(Energies'[i*TotCycles+1:(i+1)*TotCycles])
      end
     gui()
end

main()


text:
const INITIALIZERS_FOLDER = "initializers"

const DOC_ROOT_PATH   = "public"
const CONFIG_PATH     = "config"
const ENV_PATH        = joinpath(CONFIG_PATH, "env")
const APP_PATH        = "app"
const RESOURCES_PATH  = joinpath(APP_PATH, "resources")
const TEST_PATH       = "test"
const TEST_PATH_UNIT  = joinpath(TEST_PATH, "unit")
const LIB_PATH        = "lib"
const HELPERS_PATH    = joinpath(APP_PATH, "helpers")
const LOG_PATH        = "log"
const LAYOUTS_PATH    = joinpath(APP_PATH, "layouts")
const TASKS_PATH      = "tasks"
const BUILD_PATH      = "build"
const PLUGINS_PATH    = "plugins"
const SESSIONS_PATH   = "sessions"
const CACHE_PATH      = "cache"
const INITIALIZERS_PATH = joinpath(CONFIG_PATH, INITIALIZERS_FOLDER)
const DB_PATH         = "db"
const BIN_PATH        = "bin"
const SRC_PATH        = "src"
const NEW_APP_PATH    = joinpath("files", "new_app")

const GENIE_CONTROLLER_FILE_POSTFIX     = "Controller.jl"

const ROUTES_FILE_NAME  = "routes.jl"
const ASSETS_FINGERPRINT_INITIALIZER_FILE_NAME = "assets_fingerprint.jl"
const SEARCHLIGHT_INITIALIZER_FILE_NAME = "searchlight.jl"
const SECRETS_FILE_NAME = "secrets.jl"
const BOOTSTRAP_FILE_NAME = "bootstrap.jl"
const ENV_FILE_NAME = "env.jl"
const GENIE_FILE_NAME = "genie.jl"
const GLOBAL_ENV_FILE_NAME = "global.jl"
const TESTS_FILE_NAME = "runtests.jl"

const PARAMS_REQUEST_KEY    = :REQUEST
const PARAMS_RESPONSE_KEY   = :RESPONSE
const PARAMS_SESSION_KEY    = :SESSION
const PARAMS_FLASH_KEY      = :FLASH
const PARAMS_POST_KEY       = :POST
const PARAMS_GET_KEY        = :GET
const PARAMS_WS_CLIENT      = :WS_CLIENT
const PARAMS_JSON_PAYLOAD   = :JSON_PAYLOAD
const PARAMS_RAW_PAYLOAD    = :RAW_PAYLOAD
const PARAMS_FILES          = :FILES
const PARAMS_ROUTE_KEY      = :ROUTE
const PARAMS_CHANNELS_KEY   = :CHANNEL

const TEST_FILE_IDENTIFIER = "_test.jl"

const VIEWS_FOLDER = "views"
const LAYOUTS_FOLDER = "layouts"


text:
# This file was formerly a part of Julia. License is MIT: https://julialang.org/license

include("ZMQCM.jl")
start_broker()

max_stars_repo_name: vtjnash/Examples

max_issues_repo_name: JuliaArchive/Examples

max_forks_repo_name: JuliaArchive/Examples


text:
export BrickletSolidStateRelayMonoflop
struct BrickletSolidStateRelayMonoflop
    state::Bool
    time::Integer
    time_remaining::Integer
end

export BrickletSolidStateRelayIdentity
struct BrickletSolidStateRelayIdentity
    uid::String
    connected_uid::String
    position::Char
    hardware_version::Vector{Integer}
    firmware_version::Vector{Integer}
    device_identifier::Integer
end

export BrickletSolidStateRelay
"""
Controls AC and DC Solid State Relays
"""
mutable struct BrickletSolidStateRelay <: TinkerforgeDevice
    ipcon::IPConnection
    deviceInternal::PyObject

    """
    Creates an object with the unique device ID *uid* and adds it to
    the IP Connection *ipcon*.
    """
    function BrickletSolidStateRelay(uid::String, ipcon::IPConnection)
        package = pyimport("tinkerforge.bricklet_solid_state_relay")
        deviceInternal = package.BrickletSolidStateRelay(uid, ipcon.ipconInternal)

        return new(ipcon, deviceInternal)
    end
end

export set_state
"""
    $(SIGNATURES)

Sets the state of the relays *true* means on and *false* means off.

A running monoflop timer will be aborted if this function is called.
"""
function set_state(device::BrickletSolidStateRelay, state)
    device.deviceInternal.set_state(state)
end

export get_state
"""
    $(SIGNATURES)

Returns the state of the relay, *true* means on and *false* means off.
"""
function get_state(device::BrickletSolidStateRelay)
    return device.deviceInternal.get_state()
end

export set_monoflop
"""
    $(SIGNATURES)

The first parameter  is the desired state of the relay (*true* means on
and *false* means off). The second parameter indicates the time that
the relay should hold the state.

If this function is called with the parameters (true, 1500):
The relay will turn on and in 1.5s it will turn off again.

A monoflop can be used as a failsafe mechanism. For example: Lets assume you
have a RS485 bus and a Solid State Relay Bricklet connected to one of the slave
stacks. You can now call this function every second, with a time parameter
of two seconds. The relay will be on all the time. If now the RS485
connection is lost, the relay will turn off in at most two seconds.
"""
function set_monoflop(device::BrickletSolidStateRelay, state, time)
    device.deviceInternal.set_monoflop(state, time)
end

export get_monoflop
"""
    $(SIGNATURES)

Returns the current state and the time as set by
:func:`Set Monoflop` as well as the remaining time until the state flips.

If the timer is not running currently, the remaining time will be returned
as 0.
"""
function get_monoflop(device::BrickletSolidStateRelay)
    return device.deviceInternal.get_monoflop()
end

export get_identity
"""
    $(SIGNATURES)

Returns the UID, the UID where the Bricklet is connected to,
the position, the hardware and firmware version as well as the
device identifier.

The position can be 'a', 'b', 'c', 'd', 'e', 'f', 'g' or 'h' (Bricklet Port).
A Bricklet connected to an :ref:`Isolator Bricklet <isolator_bricklet>` is always at
position 'z'.

The device identifier numbers can be found :ref:`here <device_identifier>`.
|device_identifier_constant|
"""
function get_identity(device::BrickletSolidStateRelay)
    return device.deviceInternal.get_identity()
end

export register_callback
"""
Registers the given *function* with the given *callback_id*.
"""
function register_callback(device::BrickletSolidStateRelay, callback_id, function_)
    if isnothing(function_)
        device.registered_callbacks.pop(callback_id, None)
    else
        device.registered_callbacks[callback_id] = function_
    end
end


text:
#Test DataHR manipulations
#-------------------------------------------------------------------------------

using MDDatasets
using Test

#==Input data
===============================================================================#
#Sample DataF1 leaf dataset:
d1 = DataF1([1,2,3], [4,5,6])
sweeplist1 = PSweep[
	PSweep("v1", [1,2])
	PSweep("v2", [4,5])
]
sweeplist2 = PSweep[ #2nd sweep is different variable than sweeplist1
	PSweep("v1", [1,2])
	PSweep("v4", [4,5])
]
sweeplist3 = PSweep[ #Points of 2nd sweep are different than sweeplist1
	PSweep("v1", [1,2])
	PSweep("v2", [3,4])
]

dhr1 = DataHR(sweeplist1,DataF1[d1 d1; d1 d1])
dhr2 = DataHR(sweeplist2,DataF1[d1 d1; d1 d1])
dhr3 = DataHR(sweeplist3,DataF1[d1 d1; d1 d1])

#==Tests
===============================================================================#
@testset "Broadcast operations on DataHR" begin
	s1 = dhr1 + dhr1
	@testset "Validate s1 = dhr1+dhr2" begin
		for (es1, e1) in zip(s1.elem, dhr1.elem)
			@test es1.x == e1.x
			@test es1.y == (e1.y .+ e1.y)
		end
	end
	@test_throws ArgumentError dhr1+dhr2 #Mismatched sweeps
	@test_throws ArgumentError dhr1+dhr3 #Mismatched sweeps
end

@testset "DataHR => DataRS conversion" begin
	drs1 = DataRS(dhr1)

	#Verify that the sweeps match:
	@test drs1.sweep == dhr1.sweeps[1]
	@test drs1.elem[1].sweep == dhr1.sweeps[2]
	@test drs1.elem[2].sweep == dhr1.sweeps[2]

	#Verify that each element of the two data structures match:
	a = dhr1.sweeps
	for i in 1:length(a[1]), j in 1:length(a[2])
		_drs = drs1.elem[i].elem[j]; _dhr = dhr1.elem[i,j]
		@test _drs.x == _dhr.x
		@test _drs.y == _dhr.y
	end
end

:Test_Complete


text:
#=

 Test cases for interval inverse tangent function with two arguments.

 Copyright 2015-2016 Oliver Heimlich (oheim@posteo.de)

 Copying and distribution of this file, with or without modification,
 are permitted in any medium without royalty provided the copyright
 notice and this notice are preserved.  This file is offered as-is,
 without any warranty.

=#
#Language imports

#Test library imports
using Test

#Arithmetic library imports
using IntervalArithmetic

#Preamble
setprecision(53)
setprecision(Interval, Float64)
setrounding(Interval, :tight)
# Set full format, and show decorations
@format full

@testset "minimal.atan2_test" begin
    @test atan2(∅, ∅) == ∅
    @test atan2(∅, entireinterval(Float64)) == ∅
    @test atan2(entireinterval(Float64), ∅) == ∅
    @test atan2(Interval(0.0, 0.0), Interval(0.0, 0.0)) == ∅
    @test atan2(entireinterval(Float64), entireinterval(Float64)) == Interval(-0x1.921fb54442d19p1, +0x1.921fb54442d19p1)
    @test atan2(Interval(0.0, 0.0), Interval(-Inf, 0.0)) == Interval(0x1.921fb54442d18p1, 0x1.921fb54442d19p1)
    @test atan2(Interval(0.0, 0.0), Interval(0.0, Inf)) == Interval(0.0, 0.0)
    @test atan2(Interval(0.0, Inf), Interval(0.0, 0.0)) == Interval(0x1.921fb54442d18p0, 0x1.921fb54442d19p0)
    @test atan2(Interval(-Inf, 0.0), Interval(0.0, 0.0)) == Interval(-0x1.921fb54442d19p0, -0x1.921fb54442d18p0)
    @test atan2(Interval(-0x1p-1022, 0.0), Interval(-0x1p-1022, -0x1p-1022)) == Interval(-0x1.921fb54442d19p1, +0x1.921fb54442d19p1)
    @test atan2(Interval(1.0, 1.0), Interval(-1.0, -1.0)) == Interval(0x1.2d97c7f3321d2p1, 0x1.2d97c7f3321d3p1)
    @test atan2(Interval(1.0, 1.0), Interval(1.0, 1.0)) == Interval(0x1.921fb54442d18p-1, 0x1.921fb54442d19p-1)
    @test atan2(Interval(-1.0, -1.0), Interval(1.0, 1.0)) == Interval(-0x1.921fb54442d19p-1, -0x1.921fb54442d18p-1)
    @test atan2(Interval(-1.0, -1.0), Interval(-1.0, -1.0)) == Interval(-0x1.2d97c7f3321d3p1, -0x1.2d97c7f3321d2p1)
    @test atan2(Interval(-0x1p-1022, 0x1p-1022), Interval(-0x1p-1022, -0x1p-1022)) == Interval(-0x1.921fb54442d19p1, +0x1.921fb54442d19p1)
    @test atan2(Interval(-0x1p-1022, 0x1p-1022), Interval(0x1p-1022, 0x1p-1022)) == Interval(-0x1.921fb54442d19p-1, +0x1.921fb54442d19p-1)
    @test atan2(Interval(-0x1p-1022, -0x1p-1022), Interval(-0x1p-1022, 0x1p-1022)) == Interval(-0x1.2d97c7f3321d3p1, -0x1.921fb54442d18p-1)
    @test atan2(Interval(0x1p-1022, 0x1p-1022), Interval(-0x1p-1022, 0x1p-1022)) == Interval(0x1.921fb54442d18p-1, 0x1.2d97c7f3321d3p1)
    @test atan2(Interval(-2.0, 2.0), Interval(-3.0, -1.0)) == Interval(-0x1.921fb54442d19p1, +0x1.921fb54442d19p1)
    @test atan2(Interval(0.0, 2.0), Interval(-3.0, -1.0)) == Interval(0x1.0468a8ace4df6p1, 0x1.921fb54442d19p1)
    @test atan2(Interval(1.0, 3.0), Interval(-3.0, -1.0)) == Interval(0x1.e47df3d0dd4dp0, 0x1.68f095fdf593dp1)
    @test atan2(Interval(1.0, 3.0), Interval(-2.0, 0.0)) == Interval(0x1.921fb54442d18p0, 0x1.56c6e7397f5afp1)
    @test atan2(Interval(1.0, 3.0), Interval(-2.0, 2.0)) == Interval(0x1.dac670561bb4fp-2, 0x1.56c6e7397f5afp1)
    @test atan2(Interval(1.0, 3.0), Interval(0.0, 2.0)) == Interval(0x1.dac670561bb4fp-2, 0x1.921fb54442d19p0)
    @test atan2(Interval(1.0, 3.0), Interval(1.0, 3.0)) == Interval(0x1.4978fa3269ee1p-2, 0x1.3fc176b7a856p0)
    @test atan2(Interval(0.0, 2.0), Interval(1.0, 3.0)) == Interval(0x0p0, 0x1.1b6e192ebbe45p0)
    @test atan2(Interval(-2.0, 2.0), Interval(1.0, 3.0)) == Interval(-0x1.1b6e192ebbe45p0, +0x1.1b6e192ebbe45p0)
    @test atan2(Interval(-2.0, 0.0), Interval(1.0, 3.0)) == Interval(-0x1.1b6e192ebbe45p0, 0x0p0)
    @test atan2(Interval(-3.0, -1.0), Interval(1.0, 3.0)) == Interval(-0x1.3fc176b7a856p0, -0x1.4978fa3269ee1p-2)
    @test atan2(Interval(-3.0, -1.0), Interval(0.0, 2.0)) == Interval(-0x1.921fb54442d19p0, -0x1.dac670561bb4fp-2)
    @test atan2(Interval(-3.0, -1.0), Interval(-2.0, 2.0)) == Interval(-0x1.56c6e7397f5afp1, -0x1.dac670561bb4fp-2)
    @test atan2(Interval(-3.0, -1.0), Interval(-2.0, 0.0)) == Interval(-0x1.56c6e7397f5afp1, -0x1.921fb54442d18p0)
    @test atan2(Interval(-3.0, -1.0), Interval(-3.0, -1.0)) == Interval(-0x1.68f095fdf593dp1, -0x1.e47df3d0dd4dp0)
    @test atan2(Interval(-2.0, 0.0), Interval(-3.0, -1.0)) == Interval(-0x1.921fb54442d19p1, +0x1.921fb54442d19p1)
    @test atan2(Interval(-5.0, 0.0), Interval(-5.0, 0.0)) == Interval(-0x1.921fb54442d19p1, +0x1.921fb54442d19p1)
    @test atan2(Interval(0.0, 5.0), Interval(-5.0, 0.0)) == Interval(0x1.921fb54442d18p0, 0x1.921fb54442d19p1)
    @test atan2(Interval(0.0, 5.0), Interval(0.0, 5.0)) == Interval(0x0p0, 0x1.921fb54442d19p0)
    @test atan2(Interval(-5.0, 0.0), Interval(0.0, 5.0)) == Interval(-0x1.921fb54442d19p0, 0x0p0)
end
# FactCheck.exitstatus()


text:
# This file is auto-generated by AWSMetadata.jl
using AWS
using AWS.AWSServices: batch
using AWS.Compat
using AWS.UUIDs
"""
    CancelJob()

Cancels a job in an AWS Batch job queue. Jobs that are in the SUBMITTED, PENDING, or RUNNABLE state are cancelled. Jobs that have progressed to STARTING or RUNNING are not cancelled (but the API operation still succeeds, even if no job is cancelled); these jobs must be terminated with the TerminateJob operation.

# Required Parameters
- `jobId`: The AWS Batch job ID of the job to cancel.
- `reason`: A message to attach to the job that explains the reason for canceling it. This message is returned by future DescribeJobs operations on the job. This message is also recorded in the AWS Batch activity logs.

"""

cancel_job(jobId, reason; aws_config::AWSConfig=global_aws_config()) = batch("POST", "/v1/canceljob", Dict{String, Any}("jobId"=>jobId, "reason"=>reason); aws_config=aws_config)
cancel_job(jobId, reason, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = batch("POST", "/v1/canceljob", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("jobId"=>jobId, "reason"=>reason), args)); aws_config=aws_config)

"""
    CreateComputeEnvironment()

Creates an AWS Batch compute environment. You can create MANAGED or UNMANAGED compute environments. In a managed compute environment, AWS Batch manages the capacity and instance types of the compute resources within the environment. This is based on the compute resource specification that you define or the launch template that you specify when you create the compute environment. You can choose to use Amazon EC2 On-Demand Instances or Spot Instances in your managed compute environment. You can optionally set a maximum price so that Spot Instances only launch when the Spot Instance price is below a specified percentage of the On-Demand price.  Multi-node parallel jobs are not supported on Spot Instances.  In an unmanaged compute environment, you can manage your own compute resources. This provides more compute resource configuration options, such as using a custom AMI, but you must ensure that your AMI meets the Amazon ECS container instance AMI specification. For more information, see Container Instance AMIs in the Amazon Elastic Container Service Developer Guide. After you have created your unmanaged compute environment, you can use the DescribeComputeEnvironments operation to find the Amazon ECS cluster that is associated with it. Then, manually launch your container instances into that Amazon ECS cluster. For more information, see Launching an Amazon ECS Container Instance in the Amazon Elastic Container Service Developer Guide.  AWS Batch does not upgrade the AMIs in a compute environment after it is created (for example, when a newer version of the Amazon ECS-optimized AMI is available). You are responsible for the management of the guest operating system (including updates and security patches) and any additional application software or utilities that you install on the compute resources. To use a new AMI for your AWS Batch jobs:   Create a new compute environment with the new AMI.   Add the compute environment to an existing job queue.   Remove the old compute environment from your job queue.   Delete the old compute environment.

# Required Parameters
- `computeEnvironmentName`: The name for your compute environment. Up to 128 letters (uppercase and lowercase), numbers, hyphens, and underscores are allowed.
- `serviceRole`: The full Amazon Resource Name (ARN) of the IAM role that allows AWS Batch to make calls to other AWS services on your behalf. If your specified role has a path other than /, then you must either specify the full role ARN (this is recommended) or prefix the role name with the path.  Depending on how you created your AWS Batch service role, its ARN may contain the service-role path prefix. When you only specify the name of the service role, AWS Batch assumes that your ARN does not use the service-role path prefix. Because of this, we recommend that you specify the full ARN of your service role when you create compute environments.
- `type`: The type of the compute environment. For more information, see Compute Environments in the AWS Batch User Guide.

# Optional Parameters
- `computeResources`: Details of the compute resources managed by the compute environment. This parameter is required for managed compute environments. For more information, see Compute Environments in the AWS Batch User Guide.
- `state`: The state of the compute environment. If the state is ENABLED, then the compute environment accepts jobs from a queue and can scale out automatically based on queues.
- `tags`: The tags that you apply to the compute environment to help you categorize and organize your resources. Each tag consists of a key and an optional value. For more information, see Tagging AWS Resources in AWS General Reference. These tags can be updated or removed using the TagResource and UntagResource API operations. These tags do not propagate to the underlying compute resources.
"""

create_compute_environment(computeEnvironmentName, serviceRole, type; aws_config::AWSConfig=global_aws_config()) = batch("POST", "/v1/createcomputeenvironment", Dict{String, Any}("computeEnvironmentName"=>computeEnvironmentName, "serviceRole"=>serviceRole, "type"=>type); aws_config=aws_config)
create_compute_environment(computeEnvironmentName, serviceRole, type, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = batch("POST", "/v1/createcomputeenvironment", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("computeEnvironmentName"=>computeEnvironmentName, "serviceRole"=>serviceRole, "type"=>type), args)); aws_config=aws_config)

"""
    CreateJobQueue()

Creates an AWS Batch job queue. When you create a job queue, you associate one or more compute environments to the queue and assign an order of preference for the compute environments. You also set a priority to the job queue that determines the order in which the AWS Batch scheduler places jobs onto its associated compute environments. For example, if a compute environment is associated with more than one job queue, the job queue with a higher priority is given preference for scheduling jobs to that compute environment.

# Required Parameters
- `computeEnvironmentOrder`: The set of compute environments mapped to a job queue and their order relative to each other. The job scheduler uses this parameter to determine which compute environment should execute a given job. Compute environments must be in the VALID state before you can associate them with a job queue. You can associate up to three compute environments with a job queue.
- `jobQueueName`: The name of the job queue.
- `priority`: The priority of the job queue. Job queues with a higher priority (or a higher integer value for the priority parameter) are evaluated first when associated with the same compute environment. Priority is determined in descending order, for example, a job queue with a priority value of 10 is given scheduling preference over a job queue with a priority value of 1.

# Optional Parameters
- `state`: The state of the job queue. If the job queue state is ENABLED, it is able to accept jobs. If the job queue state is DISABLED, new jobs cannot be added to the queue, but jobs already in the queue can finish.
- `tags`: The tags that you apply to the job queue to help you categorize and organize your resources. Each tag consists of a key and an optional value. For more information, see Tagging AWS Resources in AWS General Reference.
"""

create_job_queue(computeEnvironmentOrder, jobQueueName, priority; aws_config::AWSConfig=global_aws_config()) = batch("POST", "/v1/createjobqueue", Dict{String, Any}("computeEnvironmentOrder"=>computeEnvironmentOrder, "jobQueueName"=>jobQueueName, "priority"=>priority); aws_config=aws_config)
create_job_queue(computeEnvironmentOrder, jobQueueName, priority, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = batch("POST", "/v1/createjobqueue", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("computeEnvironmentOrder"=>computeEnvironmentOrder, "jobQueueName"=>jobQueueName, "priority"=>priority), args)); aws_config=aws_config)

"""
    DeleteComputeEnvironment()

Deletes an AWS Batch compute environment. Before you can delete a compute environment, you must set its state to DISABLED with the UpdateComputeEnvironment API operation and disassociate it from any job queues with the UpdateJobQueue API operation.

# Required Parameters
- `computeEnvironment`: The name or Amazon Resource Name (ARN) of the compute environment to delete.

"""

delete_compute_environment(computeEnvironment; aws_config::AWSConfig=global_aws_config()) = batch("POST", "/v1/deletecomputeenvironment", Dict{String, Any}("computeEnvironment"=>computeEnvironment); aws_config=aws_config)
delete_compute_environment(computeEnvironment, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = batch("POST", "/v1/deletecomputeenvironment", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("computeEnvironment"=>computeEnvironment), args)); aws_config=aws_config)

"""
    DeleteJobQueue()

Deletes the specified job queue. You must first disable submissions for a queue with the UpdateJobQueue operation. All jobs in the queue are terminated when you delete a job queue. It is not necessary to disassociate compute environments from a queue before submitting a DeleteJobQueue request.

# Required Parameters
- `jobQueue`: The short name or full Amazon Resource Name (ARN) of the queue to delete.

"""

delete_job_queue(jobQueue; aws_config::AWSConfig=global_aws_config()) = batch("POST", "/v1/deletejobqueue", Dict{String, Any}("jobQueue"=>jobQueue); aws_config=aws_config)
delete_job_queue(jobQueue, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = batch("POST", "/v1/deletejobqueue", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("jobQueue"=>jobQueue), args)); aws_config=aws_config)

"""
    DeregisterJobDefinition()

Deregisters an AWS Batch job definition. Job definitions will be permanently deleted after 180 days.

# Required Parameters
- `jobDefinition`: The name and revision (name:revision) or full Amazon Resource Name (ARN) of the job definition to deregister.

"""

deregister_job_definition(jobDefinition; aws_config::AWSConfig=global_aws_config()) = batch("POST", "/v1/deregisterjobdefinition", Dict{String, Any}("jobDefinition"=>jobDefinition); aws_config=aws_config)
deregister_job_definition(jobDefinition, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = batch("POST", "/v1/deregisterjobdefinition", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("jobDefinition"=>jobDefinition), args)); aws_config=aws_config)

"""
    DescribeComputeEnvironments()

Describes one or more of your compute environments. If you are using an unmanaged compute environment, you can use the DescribeComputeEnvironment operation to determine the ecsClusterArn that you should launch your Amazon ECS container instances into.

# Optional Parameters
- `computeEnvironments`: A list of up to 100 compute environment names or full Amazon Resource Name (ARN) entries.
- `maxResults`: The maximum number of cluster results returned by DescribeComputeEnvironments in paginated output. When this parameter is used, DescribeComputeEnvironments only returns maxResults results in a single page along with a nextToken response element. The remaining results of the initial request can be seen by sending another DescribeComputeEnvironments request with the returned nextToken value. This value can be between 1 and 100. If this parameter is not used, then DescribeComputeEnvironments returns up to 100 results and a nextToken value if applicable.
- `nextToken`: The nextToken value returned from a previous paginated DescribeComputeEnvironments request where maxResults was used and the results exceeded the value of that parameter. Pagination continues from the end of the previous results that returned the nextToken value. This value is null when there are no more results to return.  This token should be treated as an opaque identifier that is only used to retrieve the next items in a list and not for other programmatic purposes.
"""

describe_compute_environments(; aws_config::AWSConfig=global_aws_config()) = batch("POST", "/v1/describecomputeenvironments"; aws_config=aws_config)
describe_compute_environments(args::AbstractDict{String, Any}; aws_config::AWSConfig=global_aws_config()) = batch("POST", "/v1/describecomputeenvironments", args; aws_config=aws_config)

"""
    DescribeJobDefinitions()

Describes a list of job definitions. You can specify a status (such as ACTIVE) to only return job definitions that match that status.

# Optional Parameters
- `jobDefinitionName`: The name of the job definition to describe.
- `jobDefinitions`: A list of up to 100 job definition names or full Amazon Resource Name (ARN) entries.
- `maxResults`: The maximum number of results returned by DescribeJobDefinitions in paginated output. When this parameter is used, DescribeJobDefinitions only returns maxResults results in a single page along with a nextToken response element. The remaining results of the initial request can be seen by sending another DescribeJobDefinitions request with the returned nextToken value. This value can be between 1 and 100. If this parameter is not used, then DescribeJobDefinitions returns up to 100 results and a nextToken value if applicable.
- `nextToken`: The nextToken value returned from a previous paginated DescribeJobDefinitions request where maxResults was used and the results exceeded the value of that parameter. Pagination continues from the end of the previous results that returned the nextToken value. This value is null when there are no more results to return.  This token should be treated as an opaque identifier that is only used to retrieve the next items in a list and not for other programmatic purposes.
- `status`: The status with which to filter job definitions.
"""

describe_job_definitions(; aws_config::AWSConfig=global_aws_config()) = batch("POST", "/v1/describejobdefinitions"; aws_config=aws_config)
describe_job_definitions(args::AbstractDict{String, Any}; aws_config::AWSConfig=global_aws_config()) = batch("POST", "/v1/describejobdefinitions", args; aws_config=aws_config)

"""
    DescribeJobQueues()

Describes one or more of your job queues.

# Optional Parameters
- `jobQueues`: A list of up to 100 queue names or full queue Amazon Resource Name (ARN) entries.
- `maxResults`: The maximum number of results returned by DescribeJobQueues in paginated output. When this parameter is used, DescribeJobQueues only returns maxResults results in a single page along with a nextToken response element. The remaining results of the initial request can be seen by sending another DescribeJobQueues request with the returned nextToken value. This value can be between 1 and 100. If this parameter is not used, then DescribeJobQueues returns up to 100 results and a nextToken value if applicable.
- `nextToken`: The nextToken value returned from a previous paginated DescribeJobQueues request where maxResults was used and the results exceeded the value of that parameter. Pagination continues from the end of the previous results that returned the nextToken value. This value is null when there are no more results to return.  This token should be treated as an opaque identifier that is only used to retrieve the next items in a list and not for other programmatic purposes.
"""

describe_job_queues(; aws_config::AWSConfig=global_aws_config()) = batch("POST", "/v1/describejobqueues"; aws_config=aws_config)
describe_job_queues(args::AbstractDict{String, Any}; aws_config::AWSConfig=global_aws_config()) = batch("POST", "/v1/describejobqueues", args; aws_config=aws_config)

"""
    DescribeJobs()

Describes a list of AWS Batch jobs.

# Required Parameters
- `jobs`: A list of up to 100 job IDs.

"""

describe_jobs(jobs; aws_config::AWSConfig=global_aws_config()) = batch("POST", "/v1/describejobs", Dict{String, Any}("jobs"=>jobs); aws_config=aws_config)
describe_jobs(jobs, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = batch("POST", "/v1/describejobs", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("jobs"=>jobs), args)); aws_config=aws_config)

"""
    ListJobs()

Returns a list of AWS Batch jobs. You must specify only one of the following:   a job queue ID to return a list of jobs in that job queue   a multi-node parallel job ID to return a list of that job's nodes   an array job ID to return a list of that job's children   You can filter the results by job status with the jobStatus parameter. If you do not specify a status, only RUNNING jobs are returned.

# Optional Parameters
- `arrayJobId`: The job ID for an array job. Specifying an array job ID with this parameter lists all child jobs from within the specified array.
- `jobQueue`: The name or full Amazon Resource Name (ARN) of the job queue with which to list jobs.
- `jobStatus`: The job status with which to filter jobs in the specified queue. If you do not specify a status, only RUNNING jobs are returned.
- `maxResults`: The maximum number of results returned by ListJobs in paginated output. When this parameter is used, ListJobs only returns maxResults results in a single page along with a nextToken response element. The remaining results of the initial request can be seen by sending another ListJobs request with the returned nextToken value. This value can be between 1 and 100. If this parameter is not used, then ListJobs returns up to 100 results and a nextToken value if applicable.
- `multiNodeJobId`: The job ID for a multi-node parallel job. Specifying a multi-node parallel job ID with this parameter lists all nodes that are associated with the specified job.
- `nextToken`: The nextToken value returned from a previous paginated ListJobs request where maxResults was used and the results exceeded the value of that parameter. Pagination continues from the end of the previous results that returned the nextToken value. This value is null when there are no more results to return.  This token should be treated as an opaque identifier that is only used to retrieve the next items in a list and not for other programmatic purposes.
"""

list_jobs(; aws_config::AWSConfig=global_aws_config()) = batch("POST", "/v1/listjobs"; aws_config=aws_config)
list_jobs(args::AbstractDict{String, Any}; aws_config::AWSConfig=global_aws_config()) = batch("POST", "/v1/listjobs", args; aws_config=aws_config)

"""
    ListTagsForResource()

List the tags for an AWS Batch resource. AWS Batch resources that support tags are compute environments, jobs, job definitions, and job queues. ARNs for child jobs of array and multi-node parallel (MNP) jobs are not supported.

# Required Parameters
- `resourceArn`: The Amazon Resource Name (ARN) that identifies the resource for which to list the tags. AWS Batch resources that support tags are compute environments, jobs, job definitions, and job queues. ARNs for child jobs of array and multi-node parallel (MNP) jobs are not supported.

"""

list_tags_for_resource(resourceArn; aws_config::AWSConfig=global_aws_config()) = batch("GET", "/v1/tags/$(resourceArn)"; aws_config=aws_config)
list_tags_for_resource(resourceArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = batch("GET", "/v1/tags/$(resourceArn)", args; aws_config=aws_config)

"""
    RegisterJobDefinition()

Registers an AWS Batch job definition.

# Required Parameters
- `jobDefinitionName`: The name of the job definition to register. Up to 128 letters (uppercase and lowercase), numbers, hyphens, and underscores are allowed.
- `type`: The type of job definition.

# Optional Parameters
- `containerProperties`: An object with various properties specific to single-node container-based jobs. If the job definition's type parameter is container, then you must specify either containerProperties or nodeProperties.
- `nodeProperties`: An object with various properties specific to multi-node parallel jobs. If you specify node properties for a job, it becomes a multi-node parallel job. For more information, see Multi-node Parallel Jobs in the AWS Batch User Guide. If the job definition's type parameter is container, then you must specify either containerProperties or nodeProperties.
- `parameters`: Default parameter substitution placeholders to set in the job definition. Parameters are specified as a key-value pair mapping. Parameters in a SubmitJob request override any corresponding parameter defaults from the job definition.
- `retryStrategy`: The retry strategy to use for failed jobs that are submitted with this job definition. Any retry strategy that is specified during a SubmitJob operation overrides the retry strategy defined here. If a job is terminated due to a timeout, it is not retried.
- `tags`: The tags that you apply to the job definition to help you categorize and organize your resources. Each tag consists of a key and an optional value. For more information, see Tagging AWS Resources in AWS General Reference.
- `timeout`: The timeout configuration for jobs that are submitted with this job definition, after which AWS Batch terminates your jobs if they have not finished. If a job is terminated due to a timeout, it is not retried. The minimum value for the timeout is 60 seconds. Any timeout configuration that is specified during a SubmitJob operation overrides the timeout configuration defined here. For more information, see Job Timeouts in the Amazon Elastic Container Service Developer Guide.
"""

register_job_definition(jobDefinitionName, type; aws_config::AWSConfig=global_aws_config()) = batch("POST", "/v1/registerjobdefinition", Dict{String, Any}("jobDefinitionName"=>jobDefinitionName, "type"=>type); aws_config=aws_config)
register_job_definition(jobDefinitionName, type, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = batch("POST", "/v1/registerjobdefinition", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("jobDefinitionName"=>jobDefinitionName, "type"=>type), args)); aws_config=aws_config)

"""
    SubmitJob()

Submits an AWS Batch job from a job definition. Parameters specified during SubmitJob override parameters defined in the job definition.

# Required Parameters
- `jobDefinition`: The job definition used by this job. This value can be one of name, name:revision, or the Amazon Resource Name (ARN) for the job definition. If name is specified without a revision then the latest active revision is used.
- `jobName`: The name of the job. The first character must be alphanumeric, and up to 128 letters (uppercase and lowercase), numbers, hyphens, and underscores are allowed.
- `jobQueue`: The job queue into which the job is submitted. You can specify either the name or the Amazon Resource Name (ARN) of the queue.

# Optional Parameters
- `arrayProperties`: The array properties for the submitted job, such as the size of the array. The array size can be between 2 and 10,000. If you specify array properties for a job, it becomes an array job. For more information, see Array Jobs in the AWS Batch User Guide.
- `containerOverrides`: A list of container overrides in JSON format that specify the name of a container in the specified job definition and the overrides it should receive. You can override the default command for a container (that is specified in the job definition or the Docker image) with a command override. You can also override existing environment variables (that are specified in the job definition or Docker image) on a container or add new environment variables to it with an environment override.
- `dependsOn`: A list of dependencies for the job. A job can depend upon a maximum of 20 jobs. You can specify a SEQUENTIAL type dependency without specifying a job ID for array jobs so that each child array job completes sequentially, starting at index 0. You can also specify an N_TO_N type dependency with a job ID for array jobs. In that case, each index child of this job must wait for the corresponding index child of each dependency to complete before it can begin.
- `nodeOverrides`: A list of node overrides in JSON format that specify the node range to target and the container overrides for that node range.
- `parameters`: Additional parameters passed to the job that replace parameter substitution placeholders that are set in the job definition. Parameters are specified as a key and value pair mapping. Parameters in a SubmitJob request override any corresponding parameter defaults from the job definition.
- `retryStrategy`: The retry strategy to use for failed jobs from this SubmitJob operation. When a retry strategy is specified here, it overrides the retry strategy defined in the job definition.
- `tags`: The tags that you apply to the job request to help you categorize and organize your resources. Each tag consists of a key and an optional value. For more information, see Tagging AWS Resources in AWS General Reference.
- `timeout`: The timeout configuration for this SubmitJob operation. You can specify a timeout duration after which AWS Batch terminates your jobs if they have not finished. If a job is terminated due to a timeout, it is not retried. The minimum value for the timeout is 60 seconds. This configuration overrides any timeout configuration specified in the job definition. For array jobs, child jobs have the same timeout configuration as the parent job. For more information, see Job Timeouts in the Amazon Elastic Container Service Developer Guide.
"""

submit_job(jobDefinition, jobName, jobQueue; aws_config::AWSConfig=global_aws_config()) = batch("POST", "/v1/submitjob", Dict{String, Any}("jobDefinition"=>jobDefinition, "jobName"=>jobName, "jobQueue"=>jobQueue); aws_config=aws_config)
submit_job(jobDefinition, jobName, jobQueue, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = batch("POST", "/v1/submitjob", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("jobDefinition"=>jobDefinition, "jobName"=>jobName, "jobQueue"=>jobQueue), args)); aws_config=aws_config)

"""
    TagResource()

Associates the specified tags to a resource with the specified resourceArn. If existing tags on a resource are not specified in the request parameters, they are not changed. When a resource is deleted, the tags associated with that resource are deleted as well. AWS Batch resources that support tags are compute environments, jobs, job definitions, and job queues. ARNs for child jobs of array and multi-node parallel (MNP) jobs are not supported.

# Required Parameters
- `resourceArn`: The Amazon Resource Name (ARN) of the resource to which to add tags. AWS Batch resources that support tags are compute environments, jobs, job definitions, and job queues. ARNs for child jobs of array and multi-node parallel (MNP) jobs are not supported.
- `tags`: The tags that you apply to the resource to help you categorize and organize your resources. Each tag consists of a key and an optional value. For more information, see Tagging AWS Resources in AWS General Reference.

"""

tag_resource(resourceArn, tags; aws_config::AWSConfig=global_aws_config()) = batch("POST", "/v1/tags/$(resourceArn)", Dict{String, Any}("tags"=>tags); aws_config=aws_config)
tag_resource(resourceArn, tags, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = batch("POST", "/v1/tags/$(resourceArn)", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("tags"=>tags), args)); aws_config=aws_config)

"""
    TerminateJob()

Terminates a job in a job queue. Jobs that are in the STARTING or RUNNING state are terminated, which causes them to transition to FAILED. Jobs that have not progressed to the STARTING state are cancelled.

# Required Parameters
- `jobId`: The AWS Batch job ID of the job to terminate.
- `reason`: A message to attach to the job that explains the reason for canceling it. This message is returned by future DescribeJobs operations on the job. This message is also recorded in the AWS Batch activity logs.

"""

terminate_job(jobId, reason; aws_config::AWSConfig=global_aws_config()) = batch("POST", "/v1/terminatejob", Dict{String, Any}("jobId"=>jobId, "reason"=>reason); aws_config=aws_config)
terminate_job(jobId, reason, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = batch("POST", "/v1/terminatejob", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("jobId"=>jobId, "reason"=>reason), args)); aws_config=aws_config)

"""
    UntagResource()

Deletes specified tags from an AWS Batch resource.

# Required Parameters
- `resourceArn`: The Amazon Resource Name (ARN) of the resource from which to delete tags. AWS Batch resources that support tags are compute environments, jobs, job definitions, and job queues. ARNs for child jobs of array and multi-node parallel (MNP) jobs are not supported.
- `tagKeys`: The keys of the tags to be removed.

"""

untag_resource(resourceArn, tagKeys; aws_config::AWSConfig=global_aws_config()) = batch("DELETE", "/v1/tags/$(resourceArn)", Dict{String, Any}("tagKeys"=>tagKeys); aws_config=aws_config)
untag_resource(resourceArn, tagKeys, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = batch("DELETE", "/v1/tags/$(resourceArn)", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("tagKeys"=>tagKeys), args)); aws_config=aws_config)

"""
    UpdateComputeEnvironment()

Updates an AWS Batch compute environment.

# Required Parameters
- `computeEnvironment`: The name or full Amazon Resource Name (ARN) of the compute environment to update.

# Optional Parameters
- `computeResources`: Details of the compute resources managed by the compute environment. Required for a managed compute environment.
- `serviceRole`: The full Amazon Resource Name (ARN) of the IAM role that allows AWS Batch to make calls to other AWS services on your behalf. If your specified role has a path other than /, then you must either specify the full role ARN (this is recommended) or prefix the role name with the path.  Depending on how you created your AWS Batch service role, its ARN may contain the service-role path prefix. When you only specify the name of the service role, AWS Batch assumes that your ARN does not use the service-role path prefix. Because of this, we recommend that you specify the full ARN of your service role when you create compute environments.
- `state`: The state of the compute environment. Compute environments in the ENABLED state can accept jobs from a queue and scale in or out automatically based on the workload demand of its associated queues.
"""

update_compute_environment(computeEnvironment; aws_config::AWSConfig=global_aws_config()) = batch("POST", "/v1/updatecomputeenvironment", Dict{String, Any}("computeEnvironment"=>computeEnvironment); aws_config=aws_config)
update_compute_environment(computeEnvironment, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = batch("POST", "/v1/updatecomputeenvironment", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("computeEnvironment"=>computeEnvironment), args)); aws_config=aws_config)

"""
    UpdateJobQueue()

Updates a job queue.

# Required Parameters
- `jobQueue`: The name or the Amazon Resource Name (ARN) of the job queue.

# Optional Parameters
- `computeEnvironmentOrder`: Details the set of compute environments mapped to a job queue and their order relative to each other. This is one of the parameters used by the job scheduler to determine which compute environment should execute a given job.
- `priority`: The priority of the job queue. Job queues with a higher priority (or a higher integer value for the priority parameter) are evaluated first when associated with the same compute environment. Priority is determined in descending order, for example, a job queue with a priority value of 10 is given scheduling preference over a job queue with a priority value of 1.
- `state`: Describes the queue's ability to accept new jobs. If the job queue state is ENABLED, it is able to accept jobs. If the job queue state is DISABLED, new jobs cannot be added to the queue, but jobs already in the queue can finish.
"""

update_job_queue(jobQueue; aws_config::AWSConfig=global_aws_config()) = batch("POST", "/v1/updatejobqueue", Dict{String, Any}("jobQueue"=>jobQueue); aws_config=aws_config)
update_job_queue(jobQueue, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = batch("POST", "/v1/updatejobqueue", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("jobQueue"=>jobQueue), args)); aws_config=aws_config)


text:
function get_rotate_offsets(initial_rotation::Int, final_rotation::Int, is_even_width::Bool)
  tmp_array = [initial_rotation, final_rotation]
  cur_key = sort(tmp_array)

  if first(diff(cur_key)) == 1
    is_clockwise = ( cur_key == tmp_array )
  else
    is_clockwise = ( cur_key != tmp_array )
  end

  if is_even_width
    cur_offsets = even_offsets[cur_key]
  else
    cur_offsets = odd_offsets[cur_key]
  end

  is_clockwise && return cur_offsets

  cur_offsets = map(
    cur_offset -> map(
      cur_value -> ( cur_value * -1 ),
      cur_offset
    ),
    cur_offsets
  )

  return cur_offsets
end


text:
using AsyPlots
using ConformalMaps

struct ConformalMapVisualization
    domain::AsyPlots.Plot2D
    range::AsyPlots.Plot2D
end

show(io::IO,C::ConformalMapVisualization) = print(io,
                                        "ConformalMapVisualization()")

#-----------------------------------------------------------------------------
# FUNCTIONS FOR DISPLAY VISUALIZING CONFORMAL MAPS
#-----------------------------------------------------------------------------

function closepath(γ::Array{<:Complex,1})
    return closepath(map(AsyPlots.Vec2,γ))
end

function closepath(γ::Array{<:AsyPlots.Vec2})
    if γ[1] == γ[end]
        return γ
    else
        return [γ;[γ[1]]]
    end
end

function makegrid(zvals;ringcolor="blue",raycolor="red",args...)
    lines = Path2D[]
    ringpen = Pen(color=ringcolor)
    for i=1:size(zvals)[1]
        push!(lines,Path2D(hcat(real(zvals[i,:])',
                                imag(zvals[i,:])');pen=ringpen,args...))
    end
    raypen = Pen(color=raycolor)
    for j=1:size(zvals)[2]
        push!(lines,Path2D(hcat(real(zvals[:,j]),
                                imag(zvals[:,j]));pen=raypen,args...))
    end
    return lines
end

function hyperbolictiling(f::Union{Function,InverseConformalMap};
                          rings::Integer=9,
                          rays::Integer=16,
                          rotation::Real=0.0,
                          innerradius::Real=1.0/3.0,
                          lwfunction=(i->2^(-i/2)),
                          ringcolor="blue",
                          raycolor="red",
                          spline=true)

   points = [[f((1-(1-innerradius)/2^(k-1))*cos(θ+rotation) +
                  im*(1-(1-innerradius)/2^(k-1))*sin(θ+rotation))
                       for θ=range(0, stop=2π, length=1+rays*2^(k-1))] for k=1:rings]
   return Plot([
            (isa(f,InverseConformalMap) ? domain(f) :
             [Point2D(f(0.0),linewidth=2),
              Polygon2D([f(cis(θ)) for θ=range(0, stop=2π, length=250)];linewidth=0.3)]);
             [Path2D([points[i][k],points[i+1][2*k-1]];
                     color=raycolor,linewidth=lwfunction(i))
                          for i=1:length(points)-1 for k=1:length(points[i])-1]
             [Polygon2D(points[i][1:end-1];
                    color=ringcolor,linewidth=lwfunction(i),spline=spline)
                    for i=1:length(points)]])
end

function domain(f::Union{ConformalMap,InverseConformalMap})
    return [Point2D(f.center,linewidth=2),Path2D(closepath(f.domain),linewidth=0.3)]
end

"""
    intersectQ(p,q,r,s)

Determine whether the segment [p,q] intersects
the segment [r,s].

The four points can be 2-tuples of `Real`s, or
`Complex`es.

    intersectQ(p,q,γ)

Determine whether the segment from p to q intersects
the polygonal path γ
"""
function intersectQ(p::Tuple{<:Real,<:Real},
                    q::Tuple{<:Real,<:Real},
                    r::Tuple{<:Real,<:Real},
                    s::Tuple{<:Real,<:Real})
    a = -((p[2]*(r[1] - s[1]) + r[2]*s[1] - r[1]*s[2] +
          p[1]*(-r[2] + s[2]))/((-p[2] + q[2])*(r[1] - s[1]) + (p[1] -
                 q[1])*(r[2] - s[2])))
    b = (-q[2]*r[1] + p[2]*(-q[1] + r[1]) + p[1]*(q[2] - r[2]) +
         q[1]*r[2])/((p[2] - q[2])*(r[1] - s[1]) - (p[1] - q[1])*(r[2] - s[2]))
    return 0 <= a <= 1 && 0 <= b <= 1
end

function intersectQ(p::Complex,q::Complex,r::Complex,s::Complex)
    # Determines whether the segment from p to q intersects the
    # segment from r to s
    p,q,r,s = map(reim,(p,q,r,s))
    return intersectQ(p,q,r,s)
end

function intersectQ(p::Complex,q::Complex,gamma::Array{<:Complex,1})
    for i=1:length(gamma)-1
        if intersectQ(p,q,gamma[i],gamma[i+1])
            return true
        end
    end
    return false
end

function intersectQ(p::AsyPlots.Vec2,
                    q::AsyPlots.Vec2,
                    γ::Array{<:AsyPlots.Vec2,1})
    intersectQ(map(complex,(p,q))...,map(complex,γ))
end

function makegrid(boundary::Array{<:AsyPlots.Vec2,1},n::Integer)
    grid  = Tuple[]
    xvals = [P.x for P in boundary]
    yvals = [P.y for P in boundary]
    ϵ = max(maximum(xvals)-minimum(xvals),maximum(yvals)-minimum(yvals))/(n-1)
    m = length(minimum(xvals):ϵ:maximum(xvals))
    n = length(minimum(yvals):ϵ:maximum(yvals))
    totalgrid = [(x,y) for
        x = range(minimum(xvals), stop=maximum(xvals), length=m),
        y = range(minimum(yvals), stop=maximum(yvals), length=n)]
    pointsinside = [iswellinside(AsyPlots.Vec2(totalgrid[i,j]),
                                boundary;epsilon=1e-3) ? 1 : 0 for i=1:m,j=1:n]
    lines = Tuple{Tuple{Int64,Int64},Tuple{Int64,Int64}}[]
    for i=1:m
        for j=1:n
            for v in [(i+1,j),(i-1,j),(i,j+1),(i,j-1)]
                if 1 <= v[1] <= m && 1 <= v[2] <= n &&
                    pointsinside[i,j] == 1 && pointsinside[v...] == 1 &&
                       ~intersectQ(AsyPlots.Vec2(totalgrid[i,j]),
                                   AsyPlots.Vec2(totalgrid[v...]),
                                   boundary)
                    push!(lines,((i,j),v))
                end
            end
        end
    end
    return totalgrid, pointsinside, lines
end

makegrid(boundary::Array{T,1},n::Integer) where {T<:Complex} =
    makegrid(hcat(reim(boundary)...),n)

function grid(domain,totalgrid,pointsinside,lines,center)
    return AsyPlots.Plot([[AsyPlots.Point(real(center),imag(center)),
    AsyPlots.Path(closepath(domain))];
    [AsyPlots.Path([totalgrid[line[1]...],
                    totalgrid[line[2]...]],linewidth=0.2) for line in lines]])
end

function gridimage(f,totalgrid,pointsinside,lines,center)
    return Plot([[AsyPlots.Point(0.0,0.0),AsyPlots.Circle((0.0,0.0),1,linewidth=0.3)];
     [AsyPlots.Path([f(totalgrid[line[1]...]),
                     f(totalgrid[line[2]...])],linewidth=0.1) for line in lines]])
end

function visualize(CM::ConformalMap,n::Integer=25)
    totalgrid,pointsinside,lines = makegrid(closepath(CM.domain),n)
    return ConformalMapVisualization(
        grid(closepath(CM.domain),totalgrid,pointsinside,lines,CM.center),
        gridimage(p->CM(p[1] + im*p[2]),totalgrid,pointsinside,lines,CM.center)
    )
end

function visualize(ICM::InverseConformalMap;kwargs...)
    return ConformalMapVisualization(
        hyperbolictiling(z->z;kwargs...),hyperbolictiling(ICM;kwargs...)
    )
end

function combine(V::ConformalMapVisualization;kwargs...)
    domainbb = AsyPlots.boundingbox(V.domain)
    rangebb = AsyPlots.boundingbox(V.range)
    totalwidth = domainbb.xmax - domainbb.xmin + rangebb.xmax - rangebb.xmin
    xshift = domainbb.xmax - rangebb.xmin + 0.2*totalwidth
    domainycenter = mean([domainbb.ymax,domainbb.ymin])
    rangeycenter = mean([rangebb.ymax,rangebb.ymin])
    yshift = domainycenter - rangeycenter
    fullpicture = V.domain + Shift(xshift,yshift)*V.range
    bb = AsyPlots.boundingbox(fullpicture)
    midheight = mean([bb.ymax,bb.ymin])
    arrow = Path([domainbb.xmax+0.04*totalwidth midheight;
                  domainbb.xmax+0.16*totalwidth midheight];arrow=AsyPlots.Arrow(4))
    fullpicture += Plot(arrow)
    Plot(fullpicture.elements;kwargs...)
end

function Base.show(io::IO,mime::MIME"text/plain",V::ConformalMapVisualization)
    Base.show(io,mime,combine(V))
end

function Base.show(io::IO, mime::MIME"image/svg+xml", V::ConformalMapVisualization)
    Base.show(io,mime,combine(V))
end

function Base.show(io::IO, mime::MIME"image/png", V::ConformalMapVisualization)
    Base.show(io,mime,combine(V))
end

#-----------------------------------------------------------------------------


text:
using Base.Test
using Holidays
@test 1 == 1


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

@doc raw"""ServiceAccountTokenProjection represents a projected service account token volume. This projection can be used to insert a service account token into the pods runtime filesystem for use against APIs (Kubernetes API Server or otherwise).

    IoK8sApiCoreV1ServiceAccountTokenProjection(;
        audience=nothing,
        expirationSeconds=nothing,
        path=nothing,
    )

    - audience::String : Audience is the intended audience of the token. A recipient of a token must identify itself with an identifier specified in the audience of the token, and otherwise should reject the token. The audience defaults to the identifier of the apiserver.
    - expirationSeconds::Int64 : ExpirationSeconds is the requested duration of validity of the service account token. As the token approaches expiration, the kubelet volume plugin will proactively rotate the service account token. The kubelet will start trying to rotate the token if the token is older than 80 percent of its time to live or if the token is older than 24 hours.Defaults to 1 hour and must be at least 10 minutes.
    - path::String : Path is the path relative to the mount point of the file to project the token into.
"""
mutable struct IoK8sApiCoreV1ServiceAccountTokenProjection <: SwaggerModel
    audience::Any # spec type: Union{ Nothing, String } # spec name: audience
    expirationSeconds::Any # spec type: Union{ Nothing, Int64 } # spec name: expirationSeconds
    path::Any # spec type: Union{ Nothing, String } # spec name: path

    function IoK8sApiCoreV1ServiceAccountTokenProjection(;audience=nothing, expirationSeconds=nothing, path=nothing)
        o = new()
        validate_property(IoK8sApiCoreV1ServiceAccountTokenProjection, Symbol("audience"), audience)
        setfield!(o, Symbol("audience"), audience)
        validate_property(IoK8sApiCoreV1ServiceAccountTokenProjection, Symbol("expirationSeconds"), expirationSeconds)
        setfield!(o, Symbol("expirationSeconds"), expirationSeconds)
        validate_property(IoK8sApiCoreV1ServiceAccountTokenProjection, Symbol("path"), path)
        setfield!(o, Symbol("path"), path)
        o
    end
end # type IoK8sApiCoreV1ServiceAccountTokenProjection

const _property_map_IoK8sApiCoreV1ServiceAccountTokenProjection = Dict{Symbol,Symbol}(Symbol("audience")=>Symbol("audience"), Symbol("expirationSeconds")=>Symbol("expirationSeconds"), Symbol("path")=>Symbol("path"))
const _property_types_IoK8sApiCoreV1ServiceAccountTokenProjection = Dict{Symbol,String}(Symbol("audience")=>"String", Symbol("expirationSeconds")=>"Int64", Symbol("path")=>"String")
Base.propertynames(::Type{ IoK8sApiCoreV1ServiceAccountTokenProjection }) = collect(keys(_property_map_IoK8sApiCoreV1ServiceAccountTokenProjection))
Swagger.property_type(::Type{ IoK8sApiCoreV1ServiceAccountTokenProjection }, name::Symbol) = Union{Nothing,eval(Base.Meta.parse(_property_types_IoK8sApiCoreV1ServiceAccountTokenProjection[name]))}
Swagger.field_name(::Type{ IoK8sApiCoreV1ServiceAccountTokenProjection }, property_name::Symbol) =  _property_map_IoK8sApiCoreV1ServiceAccountTokenProjection[property_name]

function check_required(o::IoK8sApiCoreV1ServiceAccountTokenProjection)
    (getproperty(o, Symbol("path")) === nothing) && (return false)
    true
end

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


text:
const go = AutoHOOT.graphops

# Used to cache the tensor network expressions
# net_sums: An array of NetworkSum. Each element is an array of AutoHOOT nodes (einsum expressions)
# index_dict: A dictionary mapping each AutoHOOT node to the index of the tensor in the input array.
struct NetworkCache
  net_sums::Array{<:NetworkSum}
  index_dict::Dict
end

NetworkCache() = NetworkCache([NetworkSum([])], Dict())

function NetworkCache(networks::Vector{<:Vector{<:AbstractTensor}})
  nodes, node_dict = generate_einsum_expr(networks; optimize=true)
  net_sums = [NetworkSum([n]) for n in nodes]
  node_index_dict = generate_node_index_dict(node_dict, networks)
  return NetworkCache(net_sums, node_index_dict)
end

@non_differentiable NetworkCache(networks::Vector{<:Vector{<:AbstractTensor}})

function NetworkCache(trees::Vector{SubNetwork})
  nodes, node_dict = generate_einsum_expr(trees; optimize=true)
  net_sums = [NetworkSum([n]) for n in nodes]
  node_index_dict = generate_node_index_dict(node_dict, get_leaves(trees))
  return NetworkCache(net_sums, node_index_dict)
end

@non_differentiable NetworkCache(trees::Vector{SubNetwork})

"""
Generate a cached network, under the constraint that tensors in contract_order will be
contracted based on the order from Array start to the end.
"""
# NOTE: this function is experimental and it hasn't been used in experiments yet.
function NetworkCache(
  networks::Vector{<:Vector{<:AbstractTensor}}, contract_order::Vector{<:AbstractTensor}
)
  nodes, node_dict = generate_einsum_expr(networks)
  constrained_nodes = [retrieve_key(node_dict, t) for t in contract_order]
  function contraction_path(node)
    constrained_inputs = [n for n in constrained_nodes if n in node.inputs]
    out = go.generate_optimal_tree_w_constraint(node, constrained_inputs)
    return out
  end
  net_sums = [NetworkSum([contraction_path(n)]) for n in nodes]
  node_index_dict = generate_node_index_dict(node_dict, networks)
  return NetworkCache(net_sums, node_index_dict)
end

@non_differentiable NetworkCache(
  networks::Vector{<:Vector{<:AbstractTensor}}, contract_order::Vector{<:AbstractTensor}
)


text:
include("Dataset.jl")
import .Dataset

root = "build"
gem5b = Dataset.get_gem5build(root)

dataset_path = joinpath(root,"dataset")
mkpath(dataset_path)

Dataset.exec_gem5opt_command(
gem5b, Dataset.base_cacheconfig, joinpath(dataset_path,"gem5out"),
joinpath(root,"MiBench","build","gcc","automotive","bitcount","bitcnts"),
"75000", Int64(1e7)
)

max_stars_repo_name: emcores/CacheConfigurations

max_issues_repo_name: emcores/CacheConfigurations

max_forks_repo_name: emcores/CacheConfigurations


text:
module GraphMakie

using NetworkLayout
using Graphs
using Makie
using LinearAlgebra

import Makie: DocThemer, ATTRIBUTES, project, automatic

include("beziercurves.jl")
include("recipes.jl")
include("interaction.jl")
include("utils.jl")

end


text:
using JuMP, EAGO

                     m = Model()

                     EAGO.register_eago_operators!(m)

                     @variable(m, -1 <= x[i=1:2] <= 1)

                     @variable(m, -5.483106975000851 <= q <= 6.193029789058127)

                     add_NL_constraint(m, :(log(1 + exp(0.7547513043737739 + -0.48113681936364117*log(1 + exp(-0.10262045764995253 + -0.12743000480166566*log(1 + exp(0.5778005478095731 + 0.8852363638482865*log(1 + exp(0.4643971142728849 + -0.24024828850470392*$(x[1]) + -0.4967453535429427*$(x[2]))) + -0.8793054881197468*log(1 + exp(-0.24055139829732441 + -0.12659057285603792*$(x[1]) + -0.42759160850418754*$(x[2]))))) + -0.1298782680512347*log(1 + exp(0.07154777431849713 + -0.5862593464659436*log(1 + exp(0.4643971142728849 + -0.24024828850470392*$(x[1]) + -0.4967453535429427*$(x[2]))) + 0.9939436563912345*log(1 + exp(-0.24055139829732441 + -0.12659057285603792*$(x[1]) + -0.42759160850418754*$(x[2]))))))) + -0.9820460002458025*log(1 + exp(0.1263157800600383 + 0.1285425867505281*log(1 + exp(0.5778005478095731 + 0.8852363638482865*log(1 + exp(0.4643971142728849 + -0.24024828850470392*$(x[1]) + -0.4967453535429427*$(x[2]))) + -0.8793054881197468*log(1 + exp(-0.24055139829732441 + -0.12659057285603792*$(x[1]) + -0.42759160850418754*$(x[2]))))) + -0.6128023058992138*log(1 + exp(0.07154777431849713 + -0.5862593464659436*log(1 + exp(0.4643971142728849 + -0.24024828850470392*$(x[1]) + -0.4967453535429427*$(x[2]))) + 0.9939436563912345*log(1 + exp(-0.24055139829732441 + -0.12659057285603792*$(x[1]) + -0.42759160850418754*$(x[2]))))))))) + log(1 + exp(-0.6861294460251406 + 0.36167652828680286*log(1 + exp(-0.10262045764995253 + -0.12743000480166566*log(1 + exp(0.5778005478095731 + 0.8852363638482865*log(1 + exp(0.4643971142728849 + -0.24024828850470392*$(x[1]) + -0.4967453535429427*$(x[2]))) + -0.8793054881197468*log(1 + exp(-0.24055139829732441 + -0.12659057285603792*$(x[1]) + -0.42759160850418754*$(x[2]))))) + -0.1298782680512347*log(1 + exp(0.07154777431849713 + -0.5862593464659436*log(1 + exp(0.4643971142728849 + -0.24024828850470392*$(x[1]) + -0.4967453535429427*$(x[2]))) + 0.9939436563912345*log(1 + exp(-0.24055139829732441 + -0.12659057285603792*$(x[1]) + -0.42759160850418754*$(x[2]))))))) + -0.5440699588803759*log(1 + exp(0.1263157800600383 + 0.1285425867505281*log(1 + exp(0.5778005478095731 + 0.8852363638482865*log(1 + exp(0.4643971142728849 + -0.24024828850470392*$(x[1]) + -0.4967453535429427*$(x[2]))) + -0.8793054881197468*log(1 + exp(-0.24055139829732441 + -0.12659057285603792*$(x[1]) + -0.42759160850418754*$(x[2]))))) + -0.6128023058992138*log(1 + exp(0.07154777431849713 + -0.5862593464659436*log(1 + exp(0.4643971142728849 + -0.24024828850470392*$(x[1]) + -0.4967453535429427*$(x[2]))) + 0.9939436563912345*log(1 + exp(-0.24055139829732441 + -0.12659057285603792*$(x[1]) + -0.42759160850418754*$(x[2]))))))))) - $q <= 0.0))

                     @objective(m, Min, q)

                     return m

max_stars_repo_name: PSORLab/RSActivationFunctions

max_issues_repo_name: PSORLab/RSActivationFunctions

max_forks_repo_name: PSORLab/RSActivationFunctions


text:
# test deprecated functions

T = Float32
fs = 100.  # sampling rate
N = 2^14   # number of points
Nwin = 10
freqmin = 10. # minimum frequency
freqmax = 20. # maximum frequency
corners = 4   # number of corners
zerophase = true # do zerophase filtering
maxlag = 20.     # maximum lag time in coda
starttime = d2u(DateTime(Date(now()))) # starttime for SeisChanel / SeisData

# test FFTData creation with compute_fft
@testset "compute fft" begin

    cc_len = 10.24
    cc_step = 5.12
    C = SeisChannel()
    C.x = rand(T,N)
    C.fs = fs
    C.id = "MZ.KTFD.08.ENZ"
    C.t = [1 (starttime + 0.004) * 1e6;N 0]
    R = RawData(C,cc_len,cc_step)
    R.gain = 1.234234e6
    F = compute_fft(R)
    @test F.name == C.id == R.name
    @test F.id == R.id
    @test F.loc == R.loc
    @test F.fs == R.fs
    @test F.gain == R.gain
    @test F.freqmin == R.freqmin
    @test F.freqmax == F.freqmax
    @test F.cc_len == R.cc_len == cc_len
    @test F.cc_step == R.cc_step == cc_step
    @test F.whitened == R.whitened
    @test F.time_norm == R.time_norm
    @test F.resp == R.resp
    @test F.t == R.t
    @test length(F.t) == size(F.fft,2)
end

# test correlation with FFTData
@testset "compute cc" begin
    cc_len = 40.96 # length of noise window
    cc_step = 40.96 # step between windows
    Ch = SeisIO.RandSeis.randSeisChannel(c=false,s=true)
    ungap!(Ch)
    Ch.x = rand(T,Int(cc_len*Nwin*fs +1)) .- T(0.5)
    Ch.fs = fs
    Ch.t = [1 starttime * 1e6;length(Ch.x) 0]
    Ch.loc = GeoLoc()
    R = RawData(Ch,cc_len,cc_step)
    F = rfft(R)
    C = compute_cc(F,F,maxlag)
    @test isa(C,CorrData) # test return type
    @test C.comp == repeat(Ch.id[end],2) # test component name
    @test size(C.corr) == (Int(2 * maxlag * fs) + 1,Nwin) # test size
    @test eltype(C.corr) == eltype(Ch.x) # test type stability
    t = -maxlag:1/fs:maxlag
    maxinds = argmax(C.corr,dims=1)
    @test all([t[maxinds[ii][1]] == 0 for ii in length(maxinds)]) # test max args
    @test C.rotated == false # test rotation
    @test C.corr_type == "CC" # test cross-correlation

    # test with no intersecting windows
    F1 = deepcopy(F)
    F2 = deepcopy(F)
    F2.t = rand(eltype(F2.t),size(F2.fft,2))
    @test_throws ArgumentError compute_cc(F1,F2,maxlag)

end


text:
export DepParser

abstract ParserType
type Unlabeled <: ParserType end
type Labeled <: ParserType end

type DepParser{T <: ParserType}
    words::IdDict{String}
    tags::IdDict{String}
    labels::IdDict{String}
    parsertype::Type{T}
    model
    labeler

    function DepParser(words, tags, labels, parsertype)
        new(words, tags, labels, parsertype)
    end
end

function DepParser{T <: ParserType}(parsertype::Type{T}, path::String)
    words = load(IdDict, path)
    tags = IdDict{String}()
    labels = IdDict{String}()
    push!(tags, "NONE")
    # push!(labels, "NONE")
    DepParser{T}(words, tags, labels, parsertype)
end

function (parser::DepParser){T}(sents::Vector{Vector{T}})
    model_t = typeof(parser.model)
    decode(model_t, parser, sents)
end

function (parser::DepParser)(filepath::String)
    sents = readconll(parser, filepath, train=false)
    model_t = typeof(parser.model)
    decode(model_t, parser, sents)
end

max_stars_repo_name: hshindo/JukaiNLP

max_issues_repo_name: hshindo/JukaiNLP

max_forks_repo_name: hshindo/JukaiNLP


text:
using ArrowMacros
using Test

mutable struct A
    a
    b
end

mutable struct B
    c
    d
end

@testset "↓" begin
    s = A(1, [2, 3])
    @↓ a = s
    @test a == 1

    @↓ a, b = s
    @test (a, b) == (1, [2, 3])

    @↓ a ← b .+ 2 = s
    @test a == [4, 5]

    @↓ a ← 2a, b = s
    @test (a, b) == (2, [2, 3])

    @↓ c ← (@. abs(3a + 2b)) = s
    @test c == [7, 9]

    s = A(1, B(2, [3, 4]))
    @↓ c, d = s.b
    @test (c, d) == (2, [3, 4])

    v = [A(1, [2, 3])]
    @↓ a, b = v[1]
    @test (a, b) == (1, [2, 3])
end

@testset "↑" begin
    a = 1
    s = A(0, 0)
    @↑ s = a
    @test s.a == 1

    b = [2, 3]
    @↑ s = a, b
    @test (s.a, s.b) == (1, [2, 3])

    @↑ s = a ← b .+ 2
    @test s.a == [4, 5]

    @↑ s = a ← 2a, b
    @test (s.a, s.b) == (2, [2, 3])

    @↑ s = b ← (@. abs(3a + 2b))
    @test s.b == [7, 9]

    s.b = B(0, 0)
    @↑ s.b = c ← 2, d ← [3, 4]
    @test (s.b.c, s.b.d) == (2, [3, 4])

    v = [s]
    @↑ v[1] = a ← 2, b ← [3, 4]
    @test (v[1].a, v[1].b) == (2, [3, 4])
end

@testset "⤓" begin
    s = A(1, [2, 3])
    @⤓ a = s
    @test a == 1

    @⤓ a, b = s
    @test (a, b) == (1, [2, 3])

    @⤓ a ← b .+ 2 = s
    @test a == [4, 5]

    @⤓ a ← 2a, b = s
    @test (a, b) == (2, [2, 3])

    @⤓ c ← (@. abs(3a + 2b)) = s
    @test c == [7, 9]

    s = A(1, B(2, [3, 4]))
    @⤓ c, d = s
    @test (c, d) == (2, [3, 4])

    v = [A(1, [2, 3])]
    @⤓ a, b = v[1]
    @test (a, b) == (1, [2, 3])
end

@testset "⤒" begin
    a = 1
    s = A(0, 0)
    @⤒ s = a
    @test s.a == 1

    b = [2, 3]
    @⤒ s = a, b
    @test (s.a, s.b) == (1, [2, 3])

    @⤒ s = a ← b .+ 2
    @test s.a == [4, 5]

    @⤒ s = a ← 2a, b
    @test (s.a, s.b) == (2, [2, 3])

    @⤒ s = b ← (@. abs(3a + 2b))
    @test s.b == [7, 9]

    s.b = B(0, 0)
    @⤒ s = c ← 2, d ← [3, 4]
    @test (s.b.c, s.b.d) == (2, [3, 4])

    v = [s]
    @⤒ v[1] = a ← 2, b ← [3, 4]
    @test (v[1].a, v[1].b) == (2, [3, 4])
end

@testset "←" begin
    f(b) = b
    @← a = f(1)
    @test a == 1

    v = [0, 0]
    @← v[1] = f(1)
    @test v[1] == 1

    a = [0, 0]
    function g(a, b)
        a[1] = b
        return a
    end
    @← a = g(1)
    @test a == [1, 0]

    v = [[0], [0]]
    @← v[1] = g(1)
    @test v[1] == [1]

    function h!(a, b)
        a[1] = b
        return a
    end
    @← a = h(2)
    @test a == [2, 0]

    v = [[0], [0]]
    @← v[1] = h(2)
    @test v[1] == [2]
end


text:
using PyCall

# Check devito version and update if necessary
struct DevitoException <: Exception
    msg::String
end

pk = pyimport("pkg_resources")
python = PyCall.pyprogramname

################## Devito ##################
# pip command
cmd = Cmd([python, "-m", "pip", "install", "-U", "--user", "devito>=4.4"])

try
    dv_ver = split(pk.get_distribution("devito").versionn, "+")[1]
    if cmp(dv_ver, "4.4") < 0
        @info "Devito  version too low, updating to >=4.4"
        run(cmd)
    end
catch e
    @info "Devito not installed, installing with PyCall python"
    run(cmd)
end

################## Matplotlib ##################
# pip command
cmd = Cmd([python, "-m", "pip", "install", "--user", "matplotlib"])
try
    mpl = pyimport("matplotlib")
catch e
    run(cmd)
end

include("install_global.jl")


text:
using Revise
using PyPlot
using PyCall
using Statistics
using LinearAlgebra
using PolygonOps
using StaticArrays
using Infiltrator
using Bem2d

function twopanel(xgrid, ygrid, npts, U, S, idx, els)
    # Start of nice visualization
    figure(figsize=(12,3))
    subplot(1, 2, 1)
    field = sqrt.(U[:, 1].^2 + U[:, 2].^2)
    ncontours = 10
    lowfield = 0
    highfield = 100
    ncontours = LinRange(lowfield, highfield, 11)

    xlim = [-20000 20000]
    ylim = [-20000 2000]
    scale = 1.0
    fieldmax = maximum(@.abs(field))
    contourf(reshape(xgrid, npts, npts), reshape(ygrid, npts, npts),
             reshape(field, npts, npts), ncontours,
             vmin=lowfield, vmax=highfield,
             cmap = get_cmap("magma"))
    clim(lowfield, highfield)
    colorbar(fraction=0.020, pad=0.05, extend = "both", label = L"$||u||$ (m)")
    contour(reshape(xgrid, npts, npts), reshape(ygrid, npts, npts),
            reshape(field, npts, npts), ncontours,
            vmin=lowfield, vmax=highfield,
            linewidths=0.25, colors="w")
    plotelements(els)
    gca().set_aspect("equal")
    gca().set_xlim([xlim[1], xlim[2]])
    gca().set_ylim([ylim[1], ylim[2]])
    gca().set_xticks([-20000, -10000, 0, 10000, 20000])
    gca().set_yticks([-20000, -10000, 0])
    xlabel(L"$x$ (m)")
    ylabel(L"$y$ (m)")
    xv = [els.x1[idx["T"]] ; els.x2[idx["T"]][end] ; 20000 ; -20000]
    yv = [els.y1[idx["T"]] ; els.y2[idx["T"]][end]; 2000 ; 2000]
    fill(xv, yv, "lightgray", zorder=30)

    # Find principle stress orientations
    stressdiff = zeros(length(U[:, 1]))
    for i in 1:length(U[:,1])
        mat = [S[i, 1] S[i, 3]; S[i, 3] S[i, 2]]
        ev = eigvals(mat)
        stressdiff[i] = log10(abs(ev[2]-ev[1]))
    end

    subplot(1, 2, 2)
    field = stressdiff
    xlim = [-20000 20000]
    ylim = [-20000 2000]
    lowfield = 5
    highfield = 10
    ncontours = LinRange(lowfield,highfield, 11)
    contourf(reshape(xgrid, npts, npts), reshape(ygrid, npts, npts),
             reshape(field, npts, npts), ncontours,
             vmin=lowfield, vmax=highfield,
             cmap=get_cmap("viridis"))
    clim(lowfield, highfield)
    colorbar(fraction=0.020, pad=0.05, extend="both",
             label=L"$\Delta \sigma$ (Pa)")
    contour(reshape(xgrid, npts, npts), reshape(ygrid, npts, npts),
            reshape(field, npts, npts), ncontours,
            vmin=lowfield, vmax=highfield,
            linewidths=0.25, colors="w")
    plotelements(els)
    gca().set_aspect("equal")
    gca().set_xlim([xlim[1], xlim[2]])
    gca().set_ylim([ylim[1], ylim[2]])
    gca().set_xticks([-20000, -10000, 0, 10000, 20000])
    gca().set_yticks([-20000, -10000, 0])
    xlabel(L"$x$ (m)")
    ylabel(L"$y$ (m)")
    xv = [els.x1[idx["T"]] ; els.x2[idx["T"]][end] ; 20000 ; -20000]
    yv = [els.y1[idx["T"]] ; els.y2[idx["T"]][end]; 2000 ; 2000]
    fill(xv, yv, "lightgray", zorder=30)
    tight_layout()
    return nothing
end

"""
    faultboxgravity()

Comparing half-space and dislocaiton in a box solutions
"""
function faultboxgravity()
    close("all")
    mu = 30e9
    lambda = 30e9
    nu = 0.25
    g = 9.81
    rho = 2700
    alpha = 1e-7 # scalar preconditioner
    npts = 200
    offset = 1
    B = -20e3 # Bottom
    R = 20e3 # Right
    T = 0e3 # Top
    L = -20e3 # Left

    # Element geometries and data structures for the box case
    elsbox = Elements(Int(1e5))
    nfault = 1
    nside = 50

    # From thrust fault example
    x1T, y1T, x2T, y2T = discretizedline(-20e3, 0, 20e3, 0, nside)
    y1T = -1e3 * atan.(x1T / 1e3)
    y2T = -1e3 * atan.(x2T / 1e3)
    # y1T = zeros(length(y1T))
    # y2T = zeros(length(y2T))

    xgrid, ygrid = obsgrid(L+offset, B+offset, R-offset, maximum(y1T)-offset, npts)

    x1, y1, x2, y2 = discretizedline(L, B, R, B, nside) # Bottom
    addelsez!(elsbox, x1, y1, x2, y2, "B")
    x1, y1, x2, y2 = discretizedline(R, B, R, minimum(y2T), nside) # Right hand side
    addelsez!(elsbox, x1, y1, x2, y2, "R")
    addelsez!(elsbox, x1T, y1T, x2T, y2T, "T")
    x1, y1, x2, y2 = discretizedline(L, maximum(y1T), L, B, nside) # Left hand side
    addelsez!(elsbox, x1, y1, x2, y2, "L")
    x1, y1, x2, y2 = discretizedline(-10e3, -10e3, -5e3, -5e3, nfault) # 45 degree dipping fault
    addelsez!(elsbox, x1, y1, x2, y2, "F")
    idxbox = getidxdict(elsbox)

    ### Fault only
    ### R, T, L are traction free bcs
    ### B is zero slip BC
    T_TB_F, H_TB_F = PUTC(slip2dispstress, elsbox,
                          [idxbox["B"] ; idxbox["R"] ; idxbox["T"] ; idxbox["L"]],
                          idxbox["F"], mu, nu)
    Fslip = [100; 100]; # y-direction slip only
    Uslip = T_TB_F * Fslip
    Tslip = H_TB_F * Fslip

    # Kernels and solve
    T_B_BRTL, H_B_BRTL = PUTC(slip2dispstress, elsbox, idxbox["B"],
                       [idxbox["B"] ; idxbox["R"] ; idxbox["T"] ; idxbox["L"]],
                       mu, nu)
    T_R_BRTL, H_R_BRTL = PUTC(slip2dispstress, elsbox, idxbox["R"],
                       [idxbox["B"] ; idxbox["R"] ; idxbox["T"] ; idxbox["L"]],
                       mu, nu)
    T_L_BRTL, H_L_BRTL = PUTC(slip2dispstress, elsbox, idxbox["L"],
                       [idxbox["B"] ; idxbox["R"] ; idxbox["T"] ; idxbox["L"]],
                       mu, nu)
    _, H_T_BRTL = PUTC(slip2dispstress, elsbox, idxbox["T"],
                       [idxbox["B"] ; idxbox["R"] ; idxbox["T"] ; idxbox["L"]],
                       mu, nu)
    bcsbox = zeros(8 * nside)
    bcsbox[1:2*nside] = -Uslip[1:2*nside] # Bottom
    bcsbox[2*nside+1:4*nside] = -Tslip[2*nside+1:4*nside] # Right
    bcsbox[4*nside+1:6*nside] = -Tslip[4*nside+1:6*nside] # Top
    bcsbox[6*nside+1:8*nside] = -Tslip[6*nside+1:8*nside] # Left
    THbox = [T_B_BRTL ; H_R_BRTL; H_T_BRTL ; H_L_BRTL]
    Ueffbox = THbox \ bcsbox

    # Volume evaluation
    UTB, STB = constdispstress(slip2dispstress, xgrid, ygrid, elsbox,
                               [idxbox["B"] ; idxbox["R"] ; idxbox["T"] ; idxbox["L"]],
                               Ueffbox[1:2:end], Ueffbox[2:2:end], mu, nu)
    UF, SF = constdispstress(slip2dispstress, xgrid, ygrid, elsbox, idxbox["F"],
                             Fslip[1:2:end], Fslip[2:2:end], mu, nu)
    Ufaultonly = UTB .+ UF
    Sfaultonly = STB .+ SF
    twopanel(xgrid, ygrid, npts, Ufaultonly, Sfaultonly, idxbox, elsbox)

    ### Box BEM problem (no dislocation, gravity only)
    # Displacement BCs for bottom
    Ug, Sg = gravityparticularfunctions(elsbox.xcenter[idxbox["B"]],
                                        elsbox.ycenter[idxbox["B"]],
                                        g, rho, lambda, mu)
    bcsboxgravity = zeros(2 * elsbox.endidx - 2)
    bcsboxgravity[1:2:2*nside] = Ug[:, 1]
    bcsboxgravity[2:2:2*nside] = Ug[:, 2]

    # Traction BCs for top and sides
    Ug, Sg = gravityparticularfunctions(elsbox.xcenter[idxbox["T"]],
                                        elsbox.ycenter[idxbox["T"]],
                                        g, rho, lambda, mu)
    Ttx = zeros(nside)
    Tty = zeros(nside)
    for i in 1:length(Sg[:, 1])
        nvec = [elsbox.xnormal[idxbox["T"][i]] ; elsbox.ynormal[idxbox["T"][i]]]
        temp = [Sg[i, 1] Sg[i, 3] ; Sg[i, 3] Sg[i, 2]] * nvec
        Ttx[i] = temp[1]
        Tty[i] = temp[2]
    end
    bcsboxgravity[4*nside+1:2:6*nside] = Ttx
    bcsboxgravity[4*nside+2:2:6*nside] = Tty
    bcsboxgravity *= -1
    Ueffboxparticular = THbox \ bcsboxgravity

    Ucomp, Scomp = constdispstress(slip2dispstress, xgrid, ygrid, elsbox,
                                   [idxbox["B"] ; idxbox["R"] ; idxbox["T"] ; idxbox["L"]],
                                   Ueffboxparticular[1:2:end], Ueffboxparticular[2:2:end], mu, nu)
    Uint, Sint = gravityparticularfunctions(xgrid, ygrid, g, rho, lambda, mu)
    Ugravityonly = @. Ucomp + Uint
    Sgravityonly = @. Scomp + Sint
    twopanel(xgrid, ygrid, npts, Ugravityonly, Sgravityonly, idxbox, elsbox)

    ### Box BEM problem (dislocation and gravity)
    bcscombined = bcsboxgravity .+ bcsbox
    Ueffcombined = THbox \ bcsboxgravity # FIXME: Equivalent to addind the solutions?
    Ucomp, Scomp = constdispstress(slip2dispstress, xgrid, ygrid, elsbox,
                                   [idxbox["B"] ; idxbox["R"] ; idxbox["T"] ; idxbox["L"]],
                                   Ueffboxparticular[1:2:end], Ueffboxparticular[2:2:end], mu, nu)
    Ugravityfault = Ucomp .+ Uint .+ UF
    Sgravityfault = Scomp .+ Sint .+ SF
    twopanel(xgrid, ygrid, npts, Ugravityfault, Sgravityfault, idxbox, elsbox)
end
faultboxgravity()


text:
# # how to print
# # assigning variables
# # syntax for basic math

# println("Print to Standard output")
# 123

# # the "ans" variable holds the last expression in memory

# # basic math operations
# sum = 3 + 8
# difference = 10 - 3
# product = 20 * 3
# power = 10^2
# println(product)

s1 = "this is a string"
s2 = """ this is another string"""

# typeof(string)

# typeof('a')
# # typeof('aa')

# # String Interpolation
# # dollar sign to throw variables into a string
# a = 5
# print("The value of a is $a")
# println()
# b = 3
# print("The sum of a and b is $(a + b)")

# String concatenation
# Method 1, use the string function
string("con", "cat", "e", "nate")
string("con", 3, "cat", 3, "e", 3, "nate")

a = 1
b = 2
# Method 2 of string concatenation
"$a$b"

max_stars_repo_name: ryanorsinger/JuliaPlayground

max_issues_repo_name: ryanorsinger/JuliaPlayground

max_forks_repo_name: ryanorsinger/JuliaPlayground