text:
@testset "MACAddress" begin

@testset "IO" begin
    x = MACAddress((0x01, 0x10, 0x0a, 0xa0, 0x0, 0xff))
    @test string(x) == "01:10:0a:a0:00:ff"
end

@testset "flags" begin
    x = MACAddress((0x0, 0x0, 0x0, 0x0, 0x0, 0x0))
    @test isunicast(x)
    @test !ismulticast(x)
    @test isuniversal(x)
    @test !islocal(x)
    x = MACAddress((0x01, 0x0, 0x0, 0x0, 0x0, 0x0))
    @test !isunicast(x)
    @test ismulticast(x)
    @test isuniversal(x)
    @test !islocal(x)
    x = MACAddress((0x02, 0x0, 0x0, 0x0, 0x0, 0x0))
    @test isunicast(x)
    @test !ismulticast(x)
    @test !isuniversal(x)
    @test islocal(x)
end

end

max_stars_repo_name: ancapdev/NetworkProtocols

max_issues_repo_name: ancapdev/NetworkProtocols


text:
#= Monetary arithmetic functions =#

# numeric operations
Base.zero(::Type{Monetary{T,U,V}}) where {T,U,V} = Monetary{T,U,V}(0)
Base.zero(::Type{T}) where {T<:Monetary} = zero(filltype(T))

# NB: one returns multiplicative identity, which does not have units
Base.one(::Type{Monetary{T,U,V}}) where {T,U,V} = one(U)

# mathematical number-like operations
Base.abs(m::T) where {T<:Monetary} = T(abs(m.val))

# a note on this one: a sign does NOT include the unit
# quantity = sign * magnitude * unit
Base.sign(m::Monetary) = sign(m.val)

# on types
Base.zero(::T) where {T<:AbstractMonetary} = zero(T)
Base.one(::T) where {T<:AbstractMonetary} = one(T)

# comparisons
==(m::T, n::T) where {T<:Monetary} = m.val == n.val
==(m::Monetary{T}, n::Monetary{T}) where {T} = (m - n).val == 0
m::Monetary == n::Monetary = m.val == n.val == 0
Base.isless(m::Monetary{T,U,V}, n::Monetary{T,U,V}) where {T,U,V} = isless(m.val, n.val)

# unary plus/minus
+ m::AbstractMonetary = m
-(m::T) where {T<:Monetary} = T(-m.val)

# arithmetic operations on two monetary values
+(m::Monetary{T,U,V}, n::Monetary{T,U,V}) where {T,U,V} = Monetary{T,U,V}(m.val + n.val)
-(m::Monetary{T,U,V}, n::Monetary{T,U,V}) where {T,U,V} = Monetary{T,U,V}(m.val - n.val)
/(m::Monetary{T,U,V}, n::Monetary{T,U,V}) where {T,U,V} = float(m.val) / float(n.val)

# arithmetic operations on monetary and dimensionless values
*(m::T, i::Real) where {T<:Monetary} = T(m.val * i)
*(i::Real, m::T) where {T<:Monetary} = T(i * m.val)
m::Monetary / f::Real = m * inv(f)

# Note that quotient is an integer, but remainder is a monetary value.

const DIVS = ((:div, :rem, :divrem),
              (:fld, :mod, :fldmod),
              (:fld1, :mod1, :fldmod1))

for (dv, rm, dvrm) in DIVS
    @eval function Base.$(dvrm)(m::Monetary{T,U,V}, n::Monetary{T,U,V}) where {T,U,V}
        quotient, remainder = $(dvrm)(m.val, n.val)
        quotient, Monetary{T,U,V}(remainder)
    end
    @eval Base.$(dv)(m::Monetary{T,U,V}, n::Monetary{T,U,V}) where {T,U,V} =
        $(dv)(m.val, n.val)
    @eval Base.$(rm)(m::Monetary{T,U,V}, n::Monetary{T,U,V}) where {T,U,V} =
        Monetary{T,U,V}($(rm)(m.val, n.val))
end

ext: jl


text:
abstract type LuxDeviceAdaptor end

struct LuxCPUAdaptor <: LuxDeviceAdaptor end
struct LuxCUDAAdaptor <: LuxDeviceAdaptor end

adapt_storage(::LuxCUDAAdaptor, x) = CUDA.cu(x)
adapt_storage(::LuxCUDAAdaptor, x::FillArrays.AbstractFill) = CUDA.cu(colelct(x))
adapt_storage(::LuxCUDAAdaptor, x::Zygote.OneElement) = CUDA.cu(collect(x))
function adapt_storage(to::LuxCUDAAdaptor, x::ComponentArray)
    ComponentArray(adapt_storage(to, getdata(x)), getaxes(x))
end
adapt_storage(::LuxCUDAAdaptor, rng::AbstractRNG) = rng

function adapt_storage(::LuxCPUAdaptor,
                       x::Union{AbstractRange, FillArrays.AbstractFill, Zygote.OneElement,
                                SparseArrays.AbstractSparseArray})
    return x
end
adapt_storage(::LuxCPUAdaptor, x::AbstractArray) = adapt(Array, x)
function adapt_storage(to::LuxCPUAdaptor, x::ComponentArray)
    ComponentArray(adapt_storage(to, getdata(x)), getaxes(x))
end
adapt_storage(::LuxCPUAdaptor, rng::AbstractRNG) = rng
# TODO: SparseArrays
function adapt_storage(::LuxCPUAdaptor,
                       x::CUDA.CUSPARSE.CUDA.CUSPARSE.AbstractCuSparseMatrix)
    adapt(Array, x)
end

_isbitsarray(::AbstractArray{<:Number}) = true
_isbitsarray(::AbstractArray{T}) where {T} = isbitstype(T)
_isbitsarray(x) = false

_isleaf(::AbstractRNG) = true
_isleaf(x) = _isbitsarray(x) || Functors.isleaf(x)

"""
    cpu(x)

Transfer `x` to CPU
"""
cpu(x) = fmap(x -> adapt(LuxCPUAdaptor(), x), x)

"""
    gpu(x)

Transfer `x` to GPU
"""
function gpu(x)
    check_use_cuda()
    return use_cuda[] ? fmap(x -> adapt(LuxCUDAAdaptor(), x), x; exclude=_isleaf) : x
end

function check_use_cuda()
    if use_cuda[] === nothing
        use_cuda[] = CUDA.functional()
        if use_cuda[] && !CUDA.has_cudnn()
            @warn "CUDA.jl found cuda, but did not find libcudnn. Some functionality will not be available."
        end
        if !(use_cuda[])
            @info """The GPU function is being called but the GPU is not accessible.
                     Defaulting back to the CPU. (No action is required if you want to run on the CPU).""" maxlog=1
        end
    end
end


text:
module WinUser
include("c_types.jl")
include("c_interface.jl")
end


text:
function makeid(df::DataFrame, i::Int, id_indices)
  if isempty(id_indices)
    id = "id_$i"
  else
    id = join([df[i, j] for j in id_indices], "_")
  end
end

function process_dataset(
    path::String;
    target_index::Int=-1,
    feature_indices=1:0,
    id_indices=1:0,
    categoric_indices=1:0,
    kwargs...
  )
  df = CSV.File(
      path,
      header=false,
      typemap=Dict(Date=>String, DateTime=>String),
      missingstrings=["", "NA", "?", "*", "#DIV/0!"],
      truestrings=["T", "t", "TRUE", "true", "y", "yes"],
      falsestrings=["F", "f", "FALSE", "false", "n", "no"];
      kwargs...
  ) |> DataFrame

  output_names = Symbol[]
  output_df = DataFrame()

  output_df.id = [makeid(df, i, id_indices) for i in 1:size(df, 1)]
  push!(output_names, :id)

  # Construct output values
  categoric_indices_set = Set(categoric_indices)
  for i in feature_indices
    if i in categoric_indices_set
      push!(output_names, :C)
    else
      push!(output_names, :N)
    end
    output_df = hcat(output_df, df[!, i:i], makeunique=true)
  end
  rename!(output_df, output_names, makeunique=true)

  output_df.target = df[!, target_index]

  output_path = joinpath(dirname(path), "data.csv")

  CSV.write(output_path, output_df, delim=',', header=true)
end


text:
#=
On Julia 1.0, it was worth using threaded loop for exp & log above about 100.
But on 1.2 & 1.3, it looks like it only pays above about 5000.
=#

using ArrayAllez, BenchmarkTools
Threads.nthreads()
ArrayAllez.TH_EXP

function exp_t(A)
    B = similar(A)
    Threads.@threads for I in eachindex(A)
        @inbounds B[I] = exp(A[I])
    end
    B
end

times_exp = []
@time for p in 6:2:14
    r = rand(2^p)
    t0 = 1e6 * @belapsed exp0($r)
    t1 = 1e6 * @belapsed exp_t($r)
    t2 = 1e6 * @belapsed exp_($r)
    push!(times_exp, (length = 2^p, bcast = t0, thread = t1, lib = t2))
end
times_exp

function log_t(A)
    B = similar(A)
    Threads.@threads for I in eachindex(A)
        @inbounds B[I] = log(A[I])
    end
    B
end

times_log = []
@time for p in 6:2:14
    r = rand(2^p)
    t0 = 1e6 * @belapsed log0($r)
    t1 = 1e6 * @belapsed log_t($r)
    t2 = 1e6 * @belapsed log_($r)
    push!(times_log, (length = 2^p, bcast = t0, thread = t1, lib = t2))
end
times_log


text:
type Handle
  ptr::Ptr{Void}

  function Handle()
    p = Ptr{Void}[0]
    cudnnCreate(p)
    h = new(p[1])
    finalizer(h, cudnnDestroy)
    h
  end
end

Base.unsafe_convert(::Type{Ptr{Void}}, h::Handle) = h.ptr

const handles = Dict{Int,Handle}()

function gethandle(dev::Int)
  if !haskey(handles, dev)
    h = Handle()
    handles[dev] = h
    h
  else
    handles[dev]
  end
end


text:
#=
Agent dynamics in the lake model
=#

using QuantEcon
using Plots
pyplot()
include("lake_model.jl")

srand(42)
lm = LakeModel(d=0, b=0)
T = 5000     # Simulation length

alpha, lambda = lm.alpha, lm.lambda
P = [(1 - lambda) lambda; alpha (1 - alpha)]

mc = MarkovChain(P, [0; 1])     # 0=unemployed, 1=employed
xbar = rate_steady_state(lm)

s_path = simulate(mc, T; init=2)
s_bar_e = cumsum(s_path) ./ (1:T)
s_bar_u = 1 - s_bar_e
s_bars = [s_bar_u s_bar_e]

titles = ["Proportion of time unemployed" "Proportion of time employed"]
dates = collect(1:T)

plot(dates, s_bars, layout=(2, 1), title=titles, legend=:none)
hline!(reverse(xbar)', layout=(2, 1), color=:red, linestyle=:dash)

max_stars_repo_name: mwhchen/quantecon

max_issues_repo_name: mwhchen/quantecon

max_forks_repo_name: mwhchen/quantecon


text:
using OpenType
using OpenType: HorizontalMetric, VerticalMetric
using GeometryExperiments
using Test

const arial = joinpath(@__DIR__, "resources", "arial.ttf")
const juliamono = joinpath(@__DIR__, "resources", "juliamono-regular.ttf")

font = OpenTypeFont(juliamono)
# OpenTypeFont(arial)

@testset "OpenType.jl" begin
    font = OpenTypeFont(juliamono)
    glyph = font.glyphs[64]
    @test glyph.header == GlyphHeader(1, 55, -15, 526, 732)
    @test glyph.data.contour_indices == [26]
    glyph_points = [
        GlyphPoint((186,-15), false),
        GlyphPoint((55,171), false),
        GlyphPoint((55,352), true),
        GlyphPoint((55,535), false),
        GlyphPoint((195,732), false),
        GlyphPoint((325,732), true),
        GlyphPoint((390,732), false),
        GlyphPoint((497,687), false),
        GlyphPoint((526,636), true),
        GlyphPoint((471,595), true),
        GlyphPoint((435,634), false),
        GlyphPoint((366,660), false),
        GlyphPoint((322,660), true),
        GlyphPoint((230,660), false),
        GlyphPoint((149,503), false),
        GlyphPoint((149,357), true),
        GlyphPoint((149,211), false),
        GlyphPoint((225,60), false),
        GlyphPoint((319,60), true),
        GlyphPoint((370,60), false),
        GlyphPoint((445,95), false),
        GlyphPoint((472,135), true),
        GlyphPoint((526,87), true),
        GlyphPoint((494,35), false),
        GlyphPoint((386,-15), false),
        GlyphPoint((318,-15), true),
    ]
    @test glyph.data.points == glyph_points

    @testset "Data extraction" begin
        curves = uncompress(glyph)
        curve = first(curves)
        for point in glyph_points
            @test point.coords in curve
        end
        @test first(curve) == Point(55,352)
        for c in curves
            @test last(c) == first(c)
            @test isodd(length(c))
            for (x, y) in c
                @test glyph.header.xmin ≤ minimum(x)
                @test glyph.header.ymin ≤ minimum(y)
                @test glyph.header.xmax ≥ maximum(x)
                @test glyph.header.ymax ≥ maximum(y)
            end
        end

        ncurves = normalize(curves, glyph)
        for ncurve in ncurves
            for point in ncurve
                @test all(0 .≤ point .≤ 1)
            end
        end

        curves = OpenType.curves(glyph)
        @test all(==(3), length.(curves))
    end

    @testset "Character to Glyph mapping" begin
        @test font['c'] == font.glyphs[626]
        @test font['\uffff'] == font.glyphs[1]
    end

    @testset "Metrics" begin
        @test font.hhea.nhmetrics == 8910
        @test font.vhea.nvmetrics == 4575

        @test first(font.hmtx.metrics) == HorizontalMetric(595, 162)
        @test last(font.hmtx.metrics) == HorizontalMetric(600, 0)

        @test first(font.vmtx.metrics) == VerticalMetric(1140, 328)
        @test last(font.vmtx.metrics) == VerticalMetric(1140, 581)
    end
end


text:
####
#### Defines list of getting started documents
####

getting_started_docs = Any[
    "Installation" => "GettingStarted/Installation.md",
    "Terminology" => "GettingStarted/Terminology.md",
    "Running" => "GettingStarted/RunningClimateMachine.md",
    "Defaults" => Any["Atmosphere model configurations" => "GettingStarted/Atmos.md",],
]


text:
# ---------------------
# Ahmed El Fatmaoui
# Homework # 2
#----------------------

        using JLD2, Random, LinearAlgebra, Statistics, CSV, DataFrames, FreqTables, Distributions,
              FreqTables, Optim, HTTP, GLM

    function how2()
        #:::::::::::::::::::::::::::::::::::::::::::::::::::
        # question 1
        #:::::::::::::::::::::::::::::::::::::::::::::::::::

        f(x) = -x[1]^4-10x[1]^3-2x[1]^2-3x[1]-2
        minusf(x) = x[1]^4+10x[1]^3+2x[1]^2+3x[1]+2
        startval = rand(1)   # random starting value
        result = optimize(minusf, startval, BFGS())

        #:::::::::::::::::::::::::::::::::::::::::::::::::::
        # question 2

        url = "https://raw.githubusercontent.com/OU-PhD-Econometrics/fall-2020/master/ProblemSets/PS1-julia-intro/nlsw88.csv"
        df = CSV.read(HTTP.get(url).body,DataFrame)

        X = [ones(size(df,1),1) df.age df.race.==1 df.collgrad.==1]
        y = df.married.==1

        function ols(beta, X, y)
            ssr = (y.-X*beta)'*(y.-X*beta)
            return ssr
        end

        beta_hat_ols = optimize(b -> ols(b, X, y), rand(size(X,2)), LBFGS(), Optim.Options(g_tol=1e-6, iterations=100_000, show_trace=true))
        println(beta_hat_ols.minimizer)

        bols = inv(X'*X)*X'*y
        df.white = df.race.==1
        bols_lm = lm(@formula(married ~ age + white + collgrad), df)

        #:::::::::::::::::::::::::::::::::::::::::::::::::::
        # question 3
        #:::::::::::::::::::::::::::::::::::::::::::::::::::

        # di[Xi * alpha] − log(1+exp(Xi * alpha))
        function logit(alpha, X, d)
            loglike =    - sum([
            d[i] * (X * alpha)[i] - log(1 + exp((X * alpha)[i]))
            for i = 1:size(X,1)
            ])

            return loglike
        end

        beta_hat_loglikhd = optimize(b -> logit(b, X, y), rand(size(X,2)), LBFGS(), Optim.Options(g_tol=1e-6, iterations=100_000, show_trace=true))
        println(beta_hat_loglikhd.minimizer)

        #:::::::::::::::::::::::::::::::::::::::::::::::::::
        # question 4
        #:::::::::::::::::::::::::::::::::::::::::::::::::::
        # see Lecture 3 slides for example
        α̂ = glm(@formula(married ~ age + white + collgrad), df, Binomial(), LogitLink())
        println(α̂)

        #:::::::::::::::::::::::::::::::::::::::::::::::::::
        # question 5
        #:::::::::::::::::::::::::::::::::::::::::::::::::::

        freqtable(df, :occupation) # note small number of obs in some occupations
        df = dropmissing(df, :occupation)
        df[df.occupation.==10,:occupation] .= 9
        df[df.occupation.==11,:occupation] .= 9
        df[df.occupation.==12,:occupation] .= 9
        df[df.occupation.==13,:occupation] .= 9
        freqtable(df, :occupation) # problem solved

        X = [ones(size(df,1),1) df.age df.race.==1 df.collgrad.==1]
        y = df.occupation

        JJ =  size(freqtable(df, :occupation),1) # number of unique occupatins
        NN = size(X,1)  # number of observations (individuals i)

        function mlogit(alpha, X, d)
            C = [i==j ? 1 : 0 for i in d , j in 1:(JJ-1)]

            log_mat = [log(exp.(X[i,:]' * alpha[:,j]) / (1+sum(exp.(X[i,:]'*alpha)))) for i in 1:NN ,j in 1:(JJ-1)]

            return -sum(C.*log_mat)

        end

        beta_mnlog = optimize(b -> mnlogit(b, X, y), rand(size(X,2),JJ-1), LBFGS(), Optim.Options(g_tol=1e-7, iterations=100_000, show_trace=true))
            println(beta_mnlog.minimizer)

    end

how2()


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

Cancels execution of a task.  When you cancel a task execution, the transfer of some files is abruptly interrupted. The contents of files that are transferred to the destination might be incomplete or inconsistent with the source files. However, if you start a new task execution on the same task and you allow the task execution to complete, file content on the destination is complete and consistent. This applies to other unexpected failures that interrupt a task execution. In all of these cases, AWS DataSync successfully complete the transfer when you start the next task execution.

# Required Parameters
- `TaskExecutionArn`: The Amazon Resource Name (ARN) of the task execution to cancel.

"""

cancel_task_execution(TaskExecutionArn; aws_config::AWSConfig=global_aws_config()) = datasync("CancelTaskExecution", Dict{String, Any}("TaskExecutionArn"=>TaskExecutionArn); aws_config=aws_config)
cancel_task_execution(TaskExecutionArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = datasync("CancelTaskExecution", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("TaskExecutionArn"=>TaskExecutionArn), args)); aws_config=aws_config)

"""
    CreateAgent()

Activates an AWS DataSync agent that you have deployed on your host. The activation process associates your agent with your account. In the activation process, you specify information such as the AWS Region that you want to activate the agent in. You activate the agent in the AWS Region where your target locations (in Amazon S3 or Amazon EFS) reside. Your tasks are created in this AWS Region. You can activate the agent in a VPC (virtual private cloud) or provide the agent access to a VPC endpoint so you can run tasks without going over the public internet. You can use an agent for more than one location. If a task uses multiple agents, all of them need to have status AVAILABLE for the task to run. If you use multiple agents for a source location, the status of all the agents must be AVAILABLE for the task to run.  Agents are automatically updated by AWS on a regular basis, using a mechanism that ensures minimal interruption to your tasks.

# Required Parameters
- `ActivationKey`: Your agent activation key. You can get the activation key either by sending an HTTP GET request with redirects that enable you to get the agent IP address (port 80). Alternatively, you can get it from the AWS DataSync console. The redirect URL returned in the response provides you the activation key for your agent in the query string parameter activationKey. It might also include other activation-related parameters; however, these are merely defaults. The arguments you pass to this API call determine the actual configuration of your agent. For more information, see Activating an Agent in the AWS DataSync User Guide.

# Optional Parameters
- `AgentName`: The name you configured for your agent. This value is a text reference that is used to identify the agent in the console.
- `SecurityGroupArns`: The ARNs of the security groups used to protect your data transfer task subnets. See CreateAgentRequestSubnetArns.
- `SubnetArns`: The Amazon Resource Names (ARNs) of the subnets in which DataSync will create elastic network interfaces for each data transfer task. The agent that runs a task must be private. When you start a task that is associated with an agent created in a VPC, or one that has access to an IP address in a VPC, then the task is also private. In this case, DataSync creates four network interfaces for each task in your subnet. For a data transfer to work, the agent must be able to route to all these four network interfaces.
- `Tags`: The key-value pair that represents the tag that you want to associate with the agent. The value can be an empty string. This value helps you manage, filter, and search for your agents.  Valid characters for key and value are letters, spaces, and numbers representable in UTF-8 format, and the following special characters: + - = . _ : / @.
- `VpcEndpointId`: The ID of the VPC (virtual private cloud) endpoint that the agent has access to. This is the client-side VPC endpoint, also called a PrivateLink. If you don't have a PrivateLink VPC endpoint, see Creating a VPC Endpoint Service Configuration in the Amazon VPC User Guide. VPC endpoint ID looks like this: vpce-01234d5aff67890e1.
"""

create_agent(ActivationKey; aws_config::AWSConfig=global_aws_config()) = datasync("CreateAgent", Dict{String, Any}("ActivationKey"=>ActivationKey); aws_config=aws_config)
create_agent(ActivationKey, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = datasync("CreateAgent", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ActivationKey"=>ActivationKey), args)); aws_config=aws_config)

"""
    CreateLocationEfs()

Creates an endpoint for an Amazon EFS file system.

# Required Parameters
- `Ec2Config`: The subnet and security group that the Amazon EFS file system uses. The security group that you provide needs to be able to communicate with the security group on the mount target in the subnet specified. The exact relationship between security group M (of the mount target) and security group S (which you provide for DataSync to use at this stage) is as follows:     Security group M (which you associate with the mount target) must allow inbound access for the Transmission Control Protocol (TCP) on the NFS port (2049) from security group S. You can enable inbound connections either by IP address (CIDR range) or security group.    Security group S (provided to DataSync to access EFS) should have a rule that enables outbound connections to the NFS port on one of the file system’s mount targets. You can enable outbound connections either by IP address (CIDR range) or security group. For information about security groups and mount targets, see Security Groups for Amazon EC2 Instances and Mount Targets in the Amazon EFS User Guide.
- `EfsFilesystemArn`: The Amazon Resource Name (ARN) for the Amazon EFS file system.

# Optional Parameters
- `Subdirectory`: A subdirectory in the location’s path. This subdirectory in the EFS file system is used to read data from the EFS source location or write data to the EFS destination. By default, AWS DataSync uses the root directory.   Subdirectory must be specified with forward slashes. For example, /path/to/folder.
- `Tags`: The key-value pair that represents a tag that you want to add to the resource. The value can be an empty string. This value helps you manage, filter, and search for your resources. We recommend that you create a name tag for your location.
"""

create_location_efs(Ec2Config, EfsFilesystemArn; aws_config::AWSConfig=global_aws_config()) = datasync("CreateLocationEfs", Dict{String, Any}("Ec2Config"=>Ec2Config, "EfsFilesystemArn"=>EfsFilesystemArn); aws_config=aws_config)
create_location_efs(Ec2Config, EfsFilesystemArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = datasync("CreateLocationEfs", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Ec2Config"=>Ec2Config, "EfsFilesystemArn"=>EfsFilesystemArn), args)); aws_config=aws_config)

"""
    CreateLocationFsxWindows()

Creates an endpoint for an Amazon FSx for Windows file system.

# Required Parameters
- `FsxFilesystemArn`: The Amazon Resource Name (ARN) for the FSx for Windows file system.
- `Password`: The password of the user who has the permissions to access files and folders in the FSx for Windows file system.
- `SecurityGroupArns`: The Amazon Resource Names (ARNs) of the security groups that are to use to configure the FSx for Windows file system.
- `User`: The user who has the permissions to access files and folders in the FSx for Windows file system.

# Optional Parameters
- `Domain`: The name of the Windows domain that the FSx for Windows server belongs to.
- `Subdirectory`: A subdirectory in the location’s path. This subdirectory in the Amazon FSx for Windows file system is used to read data from the Amazon FSx for Windows source location or write data to the FSx for Windows destination.
- `Tags`: The key-value pair that represents a tag that you want to add to the resource. The value can be an empty string. This value helps you manage, filter, and search for your resources. We recommend that you create a name tag for your location.
"""

create_location_fsx_windows(FsxFilesystemArn, Password, SecurityGroupArns, User; aws_config::AWSConfig=global_aws_config()) = datasync("CreateLocationFsxWindows", Dict{String, Any}("FsxFilesystemArn"=>FsxFilesystemArn, "Password"=>Password, "SecurityGroupArns"=>SecurityGroupArns, "User"=>User); aws_config=aws_config)
create_location_fsx_windows(FsxFilesystemArn, Password, SecurityGroupArns, User, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = datasync("CreateLocationFsxWindows", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("FsxFilesystemArn"=>FsxFilesystemArn, "Password"=>Password, "SecurityGroupArns"=>SecurityGroupArns, "User"=>User), args)); aws_config=aws_config)

"""
    CreateLocationNfs()

Defines a file system on a Network File System (NFS) server that can be read from or written to.

# Required Parameters
- `OnPremConfig`: Contains a list of Amazon Resource Names (ARNs) of agents that are used to connect to an NFS server.  If you are copying data to or from your AWS Snowcone device, see NFS Server on AWS Snowcone for more information.
- `ServerHostname`: The name of the NFS server. This value is the IP address or Domain Name Service (DNS) name of the NFS server. An agent that is installed on-premises uses this host name to mount the NFS server in a network.  If you are copying data to or from your AWS Snowcone device, see NFS Server on AWS Snowcone for more information.  This name must either be DNS-compliant or must be an IP version 4 (IPv4) address.
- `Subdirectory`: The subdirectory in the NFS file system that is used to read data from the NFS source location or write data to the NFS destination. The NFS path should be a path that's exported by the NFS server, or a subdirectory of that path. The path should be such that it can be mounted by other NFS clients in your network.  To see all the paths exported by your NFS server. run \"showmount -e nfs-server-name\" from an NFS client that has access to your server. You can specify any directory that appears in the results, and any subdirectory of that directory. Ensure that the NFS export is accessible without Kerberos authentication.  To transfer all the data in the folder you specified, DataSync needs to have permissions to read all the data. To ensure this, either configure the NFS export with no_root_squash, or ensure that the permissions for all of the files that you want DataSync allow read access for all users. Doing either enables the agent to read the files. For the agent to access directories, you must additionally enable all execute access. If you are copying data to or from your AWS Snowcone device, see NFS Server on AWS Snowcone for more information. For information about NFS export configuration, see 18.7. The /etc/exports Configuration File in the Red Hat Enterprise Linux documentation.

# Optional Parameters
- `MountOptions`: The NFS mount options that DataSync can use to mount your NFS share.
- `Tags`: The key-value pair that represents the tag that you want to add to the location. The value can be an empty string. We recommend using tags to name your resources.
"""

create_location_nfs(OnPremConfig, ServerHostname, Subdirectory; aws_config::AWSConfig=global_aws_config()) = datasync("CreateLocationNfs", Dict{String, Any}("OnPremConfig"=>OnPremConfig, "ServerHostname"=>ServerHostname, "Subdirectory"=>Subdirectory); aws_config=aws_config)
create_location_nfs(OnPremConfig, ServerHostname, Subdirectory, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = datasync("CreateLocationNfs", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("OnPremConfig"=>OnPremConfig, "ServerHostname"=>ServerHostname, "Subdirectory"=>Subdirectory), args)); aws_config=aws_config)

"""
    CreateLocationObjectStorage()

Creates an endpoint for a self-managed object storage bucket. For more information about self-managed object storage locations, see create-object-location.

# Required Parameters
- `AgentArns`: The Amazon Resource Name (ARN) of the agents associated with the self-managed object storage server location.
- `BucketName`: The bucket on the self-managed object storage server that is used to read data from.
- `ServerHostname`: The name of the self-managed object storage server. This value is the IP address or Domain Name Service (DNS) name of the object storage server. An agent uses this host name to mount the object storage server in a network.

# Optional Parameters
- `AccessKey`: Optional. The access key is used if credentials are required to access the self-managed object storage server. If your object storage requires a user name and password to authenticate, use AccessKey and SecretKey to provide the user name and password, respectively.
- `SecretKey`: Optional. The secret key is used if credentials are required to access the self-managed object storage server. If your object storage requires a user name and password to authenticate, use AccessKey and SecretKey to provide the user name and password, respectively.
- `ServerPort`: The port that your self-managed object storage server accepts inbound network traffic on. The server port is set by default to TCP 80 (HTTP) or TCP 443 (HTTPS). You can specify a custom port if your self-managed object storage server requires one.
- `ServerProtocol`: The protocol that the object storage server uses to communicate. Valid values are HTTP or HTTPS.
- `Subdirectory`: The subdirectory in the self-managed object storage server that is used to read data from.
- `Tags`: The key-value pair that represents the tag that you want to add to the location. The value can be an empty string. We recommend using tags to name your resources.
"""

create_location_object_storage(AgentArns, BucketName, ServerHostname; aws_config::AWSConfig=global_aws_config()) = datasync("CreateLocationObjectStorage", Dict{String, Any}("AgentArns"=>AgentArns, "BucketName"=>BucketName, "ServerHostname"=>ServerHostname); aws_config=aws_config)
create_location_object_storage(AgentArns, BucketName, ServerHostname, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = datasync("CreateLocationObjectStorage", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("AgentArns"=>AgentArns, "BucketName"=>BucketName, "ServerHostname"=>ServerHostname), args)); aws_config=aws_config)

"""
    CreateLocationS3()

Creates an endpoint for an Amazon S3 bucket. For more information, see https://docs.aws.amazon.com/datasync/latest/userguide/create-locations-cli.html#create-location-s3-cli in the AWS DataSync User Guide.

# Required Parameters
- `S3BucketArn`: The Amazon Resource Name (ARN) of the Amazon S3 bucket. If the bucket is on an AWS Outpost, this must be an access point ARN.
- `S3Config`:

# Optional Parameters
- `AgentArns`: If you are using DataSync on an AWS Outpost, specify the Amazon Resource Names (ARNs) of the DataSync agents deployed on your AWS Outpost. For more information about launching a DataSync agent on an Amazon Outpost, see outposts-agent.
- `S3StorageClass`: The Amazon S3 storage class that you want to store your files in when this location is used as a task destination. For buckets in AWS Regions, the storage class defaults to Standard. For buckets on AWS Outposts, the storage class defaults to AWS S3 Outposts. For more information about S3 storage classes, see Amazon S3 Storage Classes in the Amazon Simple Storage Service Developer Guide. Some storage classes have behaviors that can affect your S3 storage cost. For detailed information, see using-storage-classes.
- `Subdirectory`: A subdirectory in the Amazon S3 bucket. This subdirectory in Amazon S3 is used to read data from the S3 source location or write data to the S3 destination.
- `Tags`: The key-value pair that represents the tag that you want to add to the location. The value can be an empty string. We recommend using tags to name your resources.
"""

create_location_s3(S3BucketArn, S3Config; aws_config::AWSConfig=global_aws_config()) = datasync("CreateLocationS3", Dict{String, Any}("S3BucketArn"=>S3BucketArn, "S3Config"=>S3Config); aws_config=aws_config)
create_location_s3(S3BucketArn, S3Config, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = datasync("CreateLocationS3", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("S3BucketArn"=>S3BucketArn, "S3Config"=>S3Config), args)); aws_config=aws_config)

"""
    CreateLocationSmb()

Defines a file system on a Server Message Block (SMB) server that can be read from or written to.

# Required Parameters
- `AgentArns`: The Amazon Resource Names (ARNs) of agents to use for a Simple Message Block (SMB) location.
- `Password`: The password of the user who can mount the share, has the permissions to access files and folders in the SMB share.
- `ServerHostname`: The name of the SMB server. This value is the IP address or Domain Name Service (DNS) name of the SMB server. An agent that is installed on-premises uses this hostname to mount the SMB server in a network.  This name must either be DNS-compliant or must be an IP version 4 (IPv4) address.
- `Subdirectory`: The subdirectory in the SMB file system that is used to read data from the SMB source location or write data to the SMB destination. The SMB path should be a path that's exported by the SMB server, or a subdirectory of that path. The path should be such that it can be mounted by other SMB clients in your network.   Subdirectory must be specified with forward slashes. For example, /path/to/folder.  To transfer all the data in the folder you specified, DataSync needs to have permissions to mount the SMB share, as well as to access all the data in that share. To ensure this, either ensure that the user/password specified belongs to the user who can mount the share, and who has the appropriate permissions for all of the files and directories that you want DataSync to access, or use credentials of a member of the Backup Operators group to mount the share. Doing either enables the agent to access the data. For the agent to access directories, you must additionally enable all execute access.
- `User`: The user who can mount the share, has the permissions to access files and folders in the SMB share.

# Optional Parameters
- `Domain`: The name of the Windows domain that the SMB server belongs to.
- `MountOptions`: The mount options used by DataSync to access the SMB server.
- `Tags`: The key-value pair that represents the tag that you want to add to the location. The value can be an empty string. We recommend using tags to name your resources.
"""

create_location_smb(AgentArns, Password, ServerHostname, Subdirectory, User; aws_config::AWSConfig=global_aws_config()) = datasync("CreateLocationSmb", Dict{String, Any}("AgentArns"=>AgentArns, "Password"=>Password, "ServerHostname"=>ServerHostname, "Subdirectory"=>Subdirectory, "User"=>User); aws_config=aws_config)
create_location_smb(AgentArns, Password, ServerHostname, Subdirectory, User, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = datasync("CreateLocationSmb", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("AgentArns"=>AgentArns, "Password"=>Password, "ServerHostname"=>ServerHostname, "Subdirectory"=>Subdirectory, "User"=>User), args)); aws_config=aws_config)

"""
    CreateTask()

Creates a task. A task is a set of two locations (source and destination) and a set of Options that you use to control the behavior of a task. If you don't specify Options when you create a task, AWS DataSync populates them with service defaults. When you create a task, it first enters the CREATING state. During CREATING AWS DataSync attempts to mount the on-premises Network File System (NFS) location. The task transitions to the AVAILABLE state without waiting for the AWS location to become mounted. If required, AWS DataSync mounts the AWS location before each task execution. If an agent that is associated with a source (NFS) location goes offline, the task transitions to the UNAVAILABLE status. If the status of the task remains in the CREATING status for more than a few minutes, it means that your agent might be having trouble mounting the source NFS file system. Check the task's ErrorCode and ErrorDetail. Mount issues are often caused by either a misconfigured firewall or a mistyped NFS server hostname.

# Required Parameters
- `DestinationLocationArn`: The Amazon Resource Name (ARN) of an AWS storage resource's location.
- `SourceLocationArn`: The Amazon Resource Name (ARN) of the source location for the task.

# Optional Parameters
- `CloudWatchLogGroupArn`: The Amazon Resource Name (ARN) of the Amazon CloudWatch log group that is used to monitor and log events in the task.
- `Excludes`: A list of filter rules that determines which files to exclude from a task. The list should contain a single filter string that consists of the patterns to exclude. The patterns are delimited by \"|\" (that is, a pipe), for example, \"/folder1|/folder2\"
- `Name`: The name of a task. This value is a text reference that is used to identify the task in the console.
- `Options`: The set of configuration options that control the behavior of a single execution of the task that occurs when you call StartTaskExecution. You can configure these options to preserve metadata such as user ID (UID) and group ID (GID), file permissions, data integrity verification, and so on. For each individual task execution, you can override these options by specifying the OverrideOptions before starting the task execution. For more information, see the operation.
- `Schedule`: Specifies a schedule used to periodically transfer files from a source to a destination location. The schedule should be specified in UTC time. For more information, see task-scheduling.
- `Tags`: The key-value pair that represents the tag that you want to add to the resource. The value can be an empty string.
"""

create_task(DestinationLocationArn, SourceLocationArn; aws_config::AWSConfig=global_aws_config()) = datasync("CreateTask", Dict{String, Any}("DestinationLocationArn"=>DestinationLocationArn, "SourceLocationArn"=>SourceLocationArn); aws_config=aws_config)
create_task(DestinationLocationArn, SourceLocationArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = datasync("CreateTask", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("DestinationLocationArn"=>DestinationLocationArn, "SourceLocationArn"=>SourceLocationArn), args)); aws_config=aws_config)

"""
    DeleteAgent()

Deletes an agent. To specify which agent to delete, use the Amazon Resource Name (ARN) of the agent in your request. The operation disassociates the agent from your AWS account. However, it doesn't delete the agent virtual machine (VM) from your on-premises environment.

# Required Parameters
- `AgentArn`: The Amazon Resource Name (ARN) of the agent to delete. Use the ListAgents operation to return a list of agents for your account and AWS Region.

"""

delete_agent(AgentArn; aws_config::AWSConfig=global_aws_config()) = datasync("DeleteAgent", Dict{String, Any}("AgentArn"=>AgentArn); aws_config=aws_config)
delete_agent(AgentArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = datasync("DeleteAgent", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("AgentArn"=>AgentArn), args)); aws_config=aws_config)

"""
    DeleteLocation()

Deletes the configuration of a location used by AWS DataSync.

# Required Parameters
- `LocationArn`: The Amazon Resource Name (ARN) of the location to delete.

"""

delete_location(LocationArn; aws_config::AWSConfig=global_aws_config()) = datasync("DeleteLocation", Dict{String, Any}("LocationArn"=>LocationArn); aws_config=aws_config)
delete_location(LocationArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = datasync("DeleteLocation", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("LocationArn"=>LocationArn), args)); aws_config=aws_config)

"""
    DeleteTask()

Deletes a task.

# Required Parameters
- `TaskArn`: The Amazon Resource Name (ARN) of the task to delete.

"""

delete_task(TaskArn; aws_config::AWSConfig=global_aws_config()) = datasync("DeleteTask", Dict{String, Any}("TaskArn"=>TaskArn); aws_config=aws_config)
delete_task(TaskArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = datasync("DeleteTask", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("TaskArn"=>TaskArn), args)); aws_config=aws_config)

"""
    DescribeAgent()

Returns metadata such as the name, the network interfaces, and the status (that is, whether the agent is running or not) for an agent. To specify which agent to describe, use the Amazon Resource Name (ARN) of the agent in your request.

# Required Parameters
- `AgentArn`: The Amazon Resource Name (ARN) of the agent to describe.

"""

describe_agent(AgentArn; aws_config::AWSConfig=global_aws_config()) = datasync("DescribeAgent", Dict{String, Any}("AgentArn"=>AgentArn); aws_config=aws_config)
describe_agent(AgentArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = datasync("DescribeAgent", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("AgentArn"=>AgentArn), args)); aws_config=aws_config)

"""
    DescribeLocationEfs()

Returns metadata, such as the path information about an Amazon EFS location.

# Required Parameters
- `LocationArn`: The Amazon Resource Name (ARN) of the EFS location to describe.

"""

describe_location_efs(LocationArn; aws_config::AWSConfig=global_aws_config()) = datasync("DescribeLocationEfs", Dict{String, Any}("LocationArn"=>LocationArn); aws_config=aws_config)
describe_location_efs(LocationArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = datasync("DescribeLocationEfs", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("LocationArn"=>LocationArn), args)); aws_config=aws_config)

"""
    DescribeLocationFsxWindows()

Returns metadata, such as the path information about an Amazon FSx for Windows location.

# Required Parameters
- `LocationArn`: The Amazon Resource Name (ARN) of the FSx for Windows location to describe.

"""

describe_location_fsx_windows(LocationArn; aws_config::AWSConfig=global_aws_config()) = datasync("DescribeLocationFsxWindows", Dict{String, Any}("LocationArn"=>LocationArn); aws_config=aws_config)
describe_location_fsx_windows(LocationArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = datasync("DescribeLocationFsxWindows", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("LocationArn"=>LocationArn), args)); aws_config=aws_config)

"""
    DescribeLocationNfs()

Returns metadata, such as the path information, about an NFS location.

# Required Parameters
- `LocationArn`: The Amazon Resource Name (ARN) of the NFS location to describe.

"""

describe_location_nfs(LocationArn; aws_config::AWSConfig=global_aws_config()) = datasync("DescribeLocationNfs", Dict{String, Any}("LocationArn"=>LocationArn); aws_config=aws_config)
describe_location_nfs(LocationArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = datasync("DescribeLocationNfs", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("LocationArn"=>LocationArn), args)); aws_config=aws_config)

"""
    DescribeLocationObjectStorage()

Returns metadata about a self-managed object storage server location. For more information about self-managed object storage locations, see create-object-location.

# Required Parameters
- `LocationArn`: The Amazon Resource Name (ARN) of the self-managed object storage server location that was described.

"""

describe_location_object_storage(LocationArn; aws_config::AWSConfig=global_aws_config()) = datasync("DescribeLocationObjectStorage", Dict{String, Any}("LocationArn"=>LocationArn); aws_config=aws_config)
describe_location_object_storage(LocationArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = datasync("DescribeLocationObjectStorage", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("LocationArn"=>LocationArn), args)); aws_config=aws_config)

"""
    DescribeLocationS3()

Returns metadata, such as bucket name, about an Amazon S3 bucket location.

# Required Parameters
- `LocationArn`: The Amazon Resource Name (ARN) of the Amazon S3 bucket location to describe.

"""

describe_location_s3(LocationArn; aws_config::AWSConfig=global_aws_config()) = datasync("DescribeLocationS3", Dict{String, Any}("LocationArn"=>LocationArn); aws_config=aws_config)
describe_location_s3(LocationArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = datasync("DescribeLocationS3", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("LocationArn"=>LocationArn), args)); aws_config=aws_config)

"""
    DescribeLocationSmb()

Returns metadata, such as the path and user information about an SMB location.

# Required Parameters
- `LocationArn`: The Amazon Resource Name (ARN) of the SMB location to describe.

"""

describe_location_smb(LocationArn; aws_config::AWSConfig=global_aws_config()) = datasync("DescribeLocationSmb", Dict{String, Any}("LocationArn"=>LocationArn); aws_config=aws_config)
describe_location_smb(LocationArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = datasync("DescribeLocationSmb", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("LocationArn"=>LocationArn), args)); aws_config=aws_config)

"""
    DescribeTask()

Returns metadata about a task.

# Required Parameters
- `TaskArn`: The Amazon Resource Name (ARN) of the task to describe.

"""

describe_task(TaskArn; aws_config::AWSConfig=global_aws_config()) = datasync("DescribeTask", Dict{String, Any}("TaskArn"=>TaskArn); aws_config=aws_config)
describe_task(TaskArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = datasync("DescribeTask", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("TaskArn"=>TaskArn), args)); aws_config=aws_config)

"""
    DescribeTaskExecution()

Returns detailed metadata about a task that is being executed.

# Required Parameters
- `TaskExecutionArn`: The Amazon Resource Name (ARN) of the task that is being executed.

"""

describe_task_execution(TaskExecutionArn; aws_config::AWSConfig=global_aws_config()) = datasync("DescribeTaskExecution", Dict{String, Any}("TaskExecutionArn"=>TaskExecutionArn); aws_config=aws_config)
describe_task_execution(TaskExecutionArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = datasync("DescribeTaskExecution", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("TaskExecutionArn"=>TaskExecutionArn), args)); aws_config=aws_config)

"""
    ListAgents()

Returns a list of agents owned by an AWS account in the AWS Region specified in the request. The returned list is ordered by agent Amazon Resource Name (ARN). By default, this operation returns a maximum of 100 agents. This operation supports pagination that enables you to optionally reduce the number of agents returned in a response. If you have more agents than are returned in a response (that is, the response returns only a truncated list of your agents), the response contains a marker that you can specify in your next request to fetch the next page of agents.

# Optional Parameters
- `MaxResults`: The maximum number of agents to list.
- `NextToken`: An opaque string that indicates the position at which to begin the next list of agents.
"""

list_agents(; aws_config::AWSConfig=global_aws_config()) = datasync("ListAgents"; aws_config=aws_config)
list_agents(args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = datasync("ListAgents", args; aws_config=aws_config)

"""
    ListLocations()

Returns a list of source and destination locations. If you have more locations than are returned in a response (that is, the response returns only a truncated list of your agents), the response contains a token that you can specify in your next request to fetch the next page of locations.

# Optional Parameters
- `Filters`: You can use API filters to narrow down the list of resources returned by ListLocations. For example, to retrieve all tasks on a specific source location, you can use ListLocations with filter name LocationType S3 and Operator Equals.
- `MaxResults`: The maximum number of locations to return.
- `NextToken`: An opaque string that indicates the position at which to begin the next list of locations.
"""

list_locations(; aws_config::AWSConfig=global_aws_config()) = datasync("ListLocations"; aws_config=aws_config)
list_locations(args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = datasync("ListLocations", args; aws_config=aws_config)

"""
    ListTagsForResource()

Returns all the tags associated with a specified resource.

# Required Parameters
- `ResourceArn`: The Amazon Resource Name (ARN) of the resource whose tags to list.

# Optional Parameters
- `MaxResults`: The maximum number of locations to return.
- `NextToken`: An opaque string that indicates the position at which to begin the next list of locations.
"""

list_tags_for_resource(ResourceArn; aws_config::AWSConfig=global_aws_config()) = datasync("ListTagsForResource", Dict{String, Any}("ResourceArn"=>ResourceArn); aws_config=aws_config)
list_tags_for_resource(ResourceArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = datasync("ListTagsForResource", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ResourceArn"=>ResourceArn), args)); aws_config=aws_config)

"""
    ListTaskExecutions()

Returns a list of executed tasks.

# Optional Parameters
- `MaxResults`: The maximum number of executed tasks to list.
- `NextToken`: An opaque string that indicates the position at which to begin the next list of the executed tasks.
- `TaskArn`: The Amazon Resource Name (ARN) of the task whose tasks you want to list.
"""

list_task_executions(; aws_config::AWSConfig=global_aws_config()) = datasync("ListTaskExecutions"; aws_config=aws_config)
list_task_executions(args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = datasync("ListTaskExecutions", args; aws_config=aws_config)

"""
    ListTasks()

Returns a list of all the tasks.

# Optional Parameters
- `Filters`: You can use API filters to narrow down the list of resources returned by ListTasks. For example, to retrieve all tasks on a specific source location, you can use ListTasks with filter name LocationId and Operator Equals with the ARN for the location.
- `MaxResults`: The maximum number of tasks to return.
- `NextToken`: An opaque string that indicates the position at which to begin the next list of tasks.
"""

list_tasks(; aws_config::AWSConfig=global_aws_config()) = datasync("ListTasks"; aws_config=aws_config)
list_tasks(args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = datasync("ListTasks", args; aws_config=aws_config)

"""
    StartTaskExecution()

Starts a specific invocation of a task. A TaskExecution value represents an individual run of a task. Each task can have at most one TaskExecution at a time.  TaskExecution has the following transition phases: INITIALIZING | PREPARING | TRANSFERRING | VERIFYING | SUCCESS/FAILURE.  For detailed information, see the Task Execution section in the Components and Terminology topic in the AWS DataSync User Guide.

# Required Parameters
- `TaskArn`: The Amazon Resource Name (ARN) of the task to start.

# Optional Parameters
- `Includes`: A list of filter rules that determines which files to include when running a task. The pattern should contain a single filter string that consists of the patterns to include. The patterns are delimited by \"|\" (that is, a pipe). For example: \"/folder1|/folder2\"
- `OverrideOptions`:
"""

start_task_execution(TaskArn; aws_config::AWSConfig=global_aws_config()) = datasync("StartTaskExecution", Dict{String, Any}("TaskArn"=>TaskArn); aws_config=aws_config)
start_task_execution(TaskArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = datasync("StartTaskExecution", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("TaskArn"=>TaskArn), args)); aws_config=aws_config)

"""
    TagResource()

Applies a key-value pair to an AWS resource.

# Required Parameters
- `ResourceArn`: The Amazon Resource Name (ARN) of the resource to apply the tag to.
- `Tags`: The tags to apply.

"""

tag_resource(ResourceArn, Tags; aws_config::AWSConfig=global_aws_config()) = datasync("TagResource", Dict{String, Any}("ResourceArn"=>ResourceArn, "Tags"=>Tags); aws_config=aws_config)
tag_resource(ResourceArn, Tags, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = datasync("TagResource", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ResourceArn"=>ResourceArn, "Tags"=>Tags), args)); aws_config=aws_config)

"""
    UntagResource()

Removes a tag from an AWS resource.

# Required Parameters
- `Keys`: The keys in the key-value pair in the tag to remove.
- `ResourceArn`: The Amazon Resource Name (ARN) of the resource to remove the tag from.

"""

untag_resource(Keys, ResourceArn; aws_config::AWSConfig=global_aws_config()) = datasync("UntagResource", Dict{String, Any}("Keys"=>Keys, "ResourceArn"=>ResourceArn); aws_config=aws_config)
untag_resource(Keys, ResourceArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = datasync("UntagResource", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Keys"=>Keys, "ResourceArn"=>ResourceArn), args)); aws_config=aws_config)

"""
    UpdateAgent()

Updates the name of an agent.

# Required Parameters
- `AgentArn`: The Amazon Resource Name (ARN) of the agent to update.

# Optional Parameters
- `Name`: The name that you want to use to configure the agent.
"""

update_agent(AgentArn; aws_config::AWSConfig=global_aws_config()) = datasync("UpdateAgent", Dict{String, Any}("AgentArn"=>AgentArn); aws_config=aws_config)
update_agent(AgentArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = datasync("UpdateAgent", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("AgentArn"=>AgentArn), args)); aws_config=aws_config)

"""
    UpdateTask()

Updates the metadata associated with a task.

# Required Parameters
- `TaskArn`: The Amazon Resource Name (ARN) of the resource name of the task to update.

# Optional Parameters
- `CloudWatchLogGroupArn`: The Amazon Resource Name (ARN) of the resource name of the CloudWatch LogGroup.
- `Excludes`: A list of filter rules that determines which files to exclude from a task. The list should contain a single filter string that consists of the patterns to exclude. The patterns are delimited by \"|\" (that is, a pipe), for example: \"/folder1|/folder2\"
- `Name`: The name of the task to update.
- `Options`:
- `Schedule`: Specifies a schedule used to periodically transfer files from a source to a destination location. You can configure your task to execute hourly, daily, weekly or on specific days of the week. You control when in the day or hour you want the task to execute. The time you specify is UTC time. For more information, see task-scheduling.
"""

update_task(TaskArn; aws_config::AWSConfig=global_aws_config()) = datasync("UpdateTask", Dict{String, Any}("TaskArn"=>TaskArn); aws_config=aws_config)
update_task(TaskArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = datasync("UpdateTask", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("TaskArn"=>TaskArn), args)); aws_config=aws_config)


text:
# INTERVAL TYPES

"""
Abstract interval type
"""
abstract type AbstractInterval{T<:AbstractFloat} end

const PersistenceDiagram{T} = AbstractVector{<:AbstractInterval{T}}

"""
    birth(i::AbstractInterval)

Return a birth value of the interval `i`.
"""
birth(i::AbstractInterval) = error("`birth` is not implemented ")

"""
    death(i::AbstractInterval)

Return a death value of the interval `i`.
"""
death(i::AbstractInterval) = error("`death` is not implemented ")

# auxilary methods
show(io::IO, i::AbstractInterval) = print(io, "[$(birth(i)),$(death(i)))")
birthx(i::AbstractInterval) = birth(i) - death(i)
deathx(i::AbstractInterval) = birth(i) + death(i)
pair(i::AbstractInterval) = birth(i) => death(i)
isempty(i::AbstractInterval) = birth(i) == death(i)
eltype(i::AbstractInterval{T}) where {T<:AbstractFloat} = T
in(e::T, i::AbstractInterval{T}) where {T<:AbstractFloat} = birth(i) <= e < death(i)
(==)(i1::AbstractInterval, i2::AbstractInterval) =
    birth(i1) == birth(i2) && death(i1) == death(i2)
isless(i1::AbstractInterval, i2::AbstractInterval) =
    birth(i1) < birth(i2) ? true : ( birth(i1) == birth(i2) ? death(i1) < death(i2) : false )

"""
    Interval{T<:AbstractFloat} <: AbstractInterval{T}

Simple implementation of the `AbstractInterval` type.
"""
struct Interval{T<:AbstractFloat} <: AbstractInterval{T}
    b::T
    d::T
end
Interval(p::Pair{T,T}) where {T<:AbstractFloat} = Interval(p.first, p.second)
Interval() = Interval(0.0=>Inf)

birth(i::Interval) = i.b
death(i::Interval) = i.d
diag(i::Interval) = let c = deathx(i)/2.0; Interval(c, c) end

"""
    AnnotatedInterval{T<:AbstractFloat, C<:AbstractChain} <: AbstractInterval{T}

Interval type annotated with a generator chain.
"""
mutable struct AnnotatedInterval{T<:AbstractFloat, C<:AbstractChain} <: AbstractInterval{T}
    b::T
    d::T
    g::C
end
AnnotatedInterval(b::T, d::T) where {T<:AbstractFloat} = AnnotatedInterval(b, d, EmptyChain())

birth(i::AnnotatedInterval) = i.b
death(i::AnnotatedInterval) = i.d
generator(i::AnnotatedInterval) = i.g
show(io::IO, i::AnnotatedInterval) = print(io, "[$(i.b),$(i.d)) => $(i.g)")

"""
    diagram(d, pts)

Construct persistence diagram of dimension `d` from point pairs `pts`.
"""
diagram(pts::Pair...) = [Interval(p) for p in pts]

#
# I/O
#

function write(io::IO, pdd::Dict{Int, PD}) where {T<:Real, PD<:PersistenceDiagram{T}}
    for (d, pd) in pdd
        write(io, "$d\n")
        for i in pd
            write(io, "$(birth(i)) $(death(i))\n")
        end
    end
end

function read(io::IO, ::Type{I}) where {T<:Real, I<:AbstractInterval{T}}
    pd = Dict{Int, Vector{I}}()
    d = -1
    while !eof(io)
        l = readline(io)
        vals = split(l, ' ')
        if length(vals) == 1
            d = parse(Int, vals[1])
            pd[d] = I[]
        else
            vs = parse.(T, vals)
            push!(pd[d], Interval(vs[1],vs[2]))
        end
    end
    return pd
end


text:
export show_plan

### DAG-based graphing

function write_node(io, t::Thunk, c)
    f = isa(t.f, Function) ? "$(t.f)" : "fn"
    println(io, "n_$(t.id) [label=\"$f - $(t.id)\"];")
    c
end

dec(x) = Base.dec(x, 0, false)
function write_node(io, t, c, id=dec(hash(t)))
    l = replace(node_label(t), "\""=>"")
    println(io, "n_$id", " [label=\"$l\"];")
    c
end
function node_label(t)
    iob = IOBuffer()
    Base.show(iob, t)
    String(take!(iob))
end
function node_label(x::T) where T<:AbstractArray
    "$T\nShape: $(size(x))\nSize: $(pretty_size(sizeof(x)))"
end

global _part_labels = Dict()

function write_node(io, t::Chunk, c)
    _part_labels[t]="part_$c"
    c+1
end

function node_id(t::Thunk)
    t.id
end

function node_id(t)
    dec(hash(t))
end

function node_id(t::Chunk)
    _part_labels[t]
end

function write_dag(io, t::Thunk)
    !istask(t) && return
    deps = dependents(t)
    c=1
    for k in keys(deps)
        c = write_node(io, k, c)
    end
    for (k, v) in deps
        for dep in v
            if isa(k, Union{Chunk, Thunk})
                println(io, "$(node_id(k)) -> $(node_id(dep))")
            end
        end
    end
end

### Timespan-based graphing

pretty_time(ts::Timespan) = pretty_time(ts.finish-ts.start)
function pretty_time(t)
    r(t) = round(t; digits=3)
    if t > 1000^3
        "$(r(t/(1000^3))) s"
    elseif t > 1000^2
        "$(r(t/(1000^2))) ms"
    elseif t > 1000
        "$(r(t/1000)) us"
    else
        "$(r(t)) ns"
    end
end
function pretty_size(sz)
    if sz > 1024^4
        "$(sz/(1024^4)) TB (terabytes)"
    elseif sz > 1024^3
        "$(sz/(1024^3)) GB (gigabytes)"
    elseif sz > 1024^2
        "$(sz/(1024^2)) MB (megabytes)"
    elseif sz > 1024
        "$(sz/1024) KB (kilobytes)"
    else
        "$sz B (bytes)"
    end
end

function write_node(io, ts::Timespan, c)
    f, res_type, res_sz = ts.timeline
    f = isa(f, Function) ? "$f" : "fn"
    t_comp = pretty_time(ts)
    sz_comp = pretty_size(res_sz)
    println(io, "n_$(ts.id) [label=\"$f - $(ts.id)\nCompute: $t_comp\nResult Type: $res_type\nResult Size: $sz_comp\"]")
    c
end

function write_edge(io, ts_comm::Timespan, logs)
    f, id = ts_comm.timeline
    # FIXME: We should print these edges too
    id === nothing && return
    t_comm = pretty_time(ts_comm)
    print(io, "n_$id -> n_$(ts_comm.id[1]) [label=\"Comm: $t_comm")
    ts_idx = findfirst(x->x.category==:move &&
                                ts_comm.id==x.id &&
                                id==x.timeline[2], logs)
    if ts_idx !== nothing
        ts_move = logs[ts_idx]
        t_move = pretty_time(ts_move)
        print(io, "\nMove: $t_move")
    end
    println(io, "\"];")
end

write_edge(io, from::String, to::String) = println(io, "n_$from -> n_$to")

getargs!(d, t) = nothing
function getargs!(d, t::Thunk)
    d[t.id] = [filter(!istask, [t.inputs...,])...,]
    foreach(i->getargs!(d, i), t.inputs)
end
function write_dag(io, logs::Vector, t=nothing)
    argmap = Dict{Int,Vector}()
    getargs!(argmap, t)
    c = 1
    for ts in filter(x->x.category==:compute, logs)
        c = write_node(io, ts, c)
    end
    argnodemap = Dict{Int,Vector{String}}()
    argids = IdDict{Any,String}()
    for id in keys(argmap)
        nodes = String[]
        arg_c = 1
        for arg in argmap[id]
            name = "$(id)_arg_$(arg_c)"
            if !isimmutable(arg)
                if arg in keys(argids)
                    name = argids[arg]
                else
                    argids[arg] = name
                    c = write_node(io, arg, c, name)
                end
                push!(nodes, name)
            else
                c = write_node(io, arg, c, name)
                push!(nodes, name)
            end
        end
        argnodemap[id] = nodes
    end
    for ts in filter(x->x.category==:comm, logs)
        write_edge(io, ts, logs)
    end
    for id in keys(argnodemap)
        for arg in argnodemap[id]
            write_edge(io, arg, string(id))
        end
    end
end

function show_plan(io::IO, t)
    print(io, """digraph {
    graph [layout=dot, rankdir=TB];""")
    write_dag(io, t)
    println(io, "}")
end
function show_plan(io::IO, logs::Vector{Timespan}, t::Thunk)
    print(io, """digraph {
    graph [layout=dot, rankdir=TB];""")
    write_dag(io, logs, t)
    println(io, "}")
end

function show_plan(t::Union{Thunk,Vector{Timespan}})
    io = IOBuffer()
    show_plan(io, t)
    return String(take!(io))
end
function show_plan(logs::Vector{Timespan}, t::Thunk)
    io = IOBuffer()
    show_plan(io, logs, t)
    return String(take!(io))
end

function show_plan(c)
    t = thunkize(Context(), stage(Context(), c))
    show_plan(t)
end

function show_plan(t::Tuple)
    show_plan(TupleCompute(t))
end

# function printing

argname(x::Symbol) = x

function argname(x)
    @assert x.head == :(::)
    x.args[1]
end

function show_statement(io, x)
    if x.head == :return
        x = x.args[1]
    end
    print(io, x)
end

function fnbody(io, x)
    body = x.args[3]
    statements = filter(x -> !isa(x, LineNumberNode), body.args)
    for s in statements
        show_statement(io, s)
    end
end

function show_ast(io, f)
    ast = Base.uncompressed_ast(f.code)
    args = map(x -> string(argname(x)), ast.args[1])
    write(io, "(", join(args, ','), ") -> ")
    fnbody(io, ast)
end

function showfn(io, f::Function)
    if isa(f, Function)
        show(io, f)
    else
        show_ast(io, f)
    end
end
showfn(io, f) = show(io, f)


text:
function lagrangian_multiplier(model::MOI.ModelLike, certificate, index, preprocessed, T::Type)
    basis = Certificate.get(certificate, Certificate.MultiplierBasis(), index, preprocessed)
    MCT = SOS.matrix_cone_type(typeof(certificate))
    return SOS.add_gram_matrix(model, MCT, basis, T)..., basis
end

struct SOSPolynomialInSemialgebraicSetBridge{
    T, F <: MOI.AbstractVectorFunction, DT <: SemialgebraicSets.AbstractSemialgebraicSet,
    CT <: Certificate.AbstractIdealCertificate,
    B <: Union{Vector{<:MultivariateBases.AbstractPolynomialBasis},
               MultivariateBases.AbstractPolynomialBasis},
    UMCT <: Union{Vector{<:MOI.ConstraintIndex{MOI.VectorOfVariables}},
                  MOI.ConstraintIndex{MOI.VectorOfVariables}},
    UMST, MCT,
    MT <: MP.AbstractMonomial, MVT <: AbstractVector{MT}} <: MOIB.Constraint.AbstractBridge
    lagrangian_bases::Vector{B}
    lagrangian_variables::Vector{Union{Vector{MOI.VariableIndex}, Vector{Vector{MOI.VariableIndex}}}}
    lagrangian_constraints::Vector{UMCT}
    constraint::MOI.ConstraintIndex{F, SOS.SOSPolynomialSet{DT, MT, MVT, CT}}
    monomials::MVT
end

function MOI.Bridges.Constraint.bridge_constraint(
    ::Type{SOSPolynomialInSemialgebraicSetBridge{T, F, DT, CT, B, UMCT, UMST, MCT, MT, MVT}},
    model::MOI.ModelLike, f::MOI.AbstractVectorFunction,
    set::SOS.SOSPolynomialSet{<:SemialgebraicSets.BasicSemialgebraicSet}) where {T, F, DT, CT, B, UMCT, UMST, MCT, MT, MVT}

    @assert MOI.output_dimension(f) == length(set.monomials)
    # MOI does not modify the coefficients of the functions so we can modify `p`.
    # without altering `f`.
    # The monomials may be copied by MA however so we need to copy it.
    p = MP.polynomial(MOIU.scalarize(f), copy(set.monomials))
    λ_bases     = B[]
    λ_variables = Union{Vector{MOI.VariableIndex}, Vector{Vector{MOI.VariableIndex}}}[]
    λ_constraints = UMCT[]
    preprocessed = Certificate.get(set.certificate, Certificate.PreprocessedDomain(), set.domain, p)
    for index in Certificate.get(set.certificate, Certificate.PreorderIndices(), preprocessed)
        λ, λ_variable, λ_constraint, λ_basis = lagrangian_multiplier(
            model, set.certificate, index, preprocessed, T)
        push!(λ_variables, λ_variable)
        push!(λ_constraints, λ_constraint)
        push!(λ_bases, λ_basis)
        # As `*(::MOI.ScalarAffineFunction{T}, ::S)` is only defined if `S == T`, we
        # need to call `changecoefficienttype`. This is critical since `T` is
        # `Float64` when used with JuMP and the coefficient type is often `Int` if
        # `set.domain.V` is `FullSpace` or `FixedPolynomialsSet`.
        g = Certificate.get(set.certificate, Certificate.Generator(), index, preprocessed)
        # TODO replace with `MA.sub_mul` when it works.
        p = MA.operate!(MA.add_mul, p, -one(T), λ, MP.changecoefficienttype(g, T))
    end
    new_set = SOS.SOSPolynomialSet(
        set.domain.V, MP.monomials(p),
        Certificate.get(set.certificate, Certificate.IdealCertificate()))
    constraint = MOI.add_constraint(model, MOIU.vectorize(MP.coefficients(p)),
                                    new_set)

    return SOSPolynomialInSemialgebraicSetBridge{
        T, F, DT, CT, B, UMCT, UMST, MCT, MT, MVT}(λ_bases, λ_variables, λ_constraints, constraint, set.monomials)
end

function MOI.supports_constraint(::Type{SOSPolynomialInSemialgebraicSetBridge{T}},
                                 ::Type{<:MOI.AbstractVectorFunction},
                                 ::Type{<:SOS.SOSPolynomialSet{<:SemialgebraicSets.BasicSemialgebraicSet}}) where T
    return true
end
function MOIB.added_constrained_variable_types(::Type{<:SOSPolynomialInSemialgebraicSetBridge{T, F, DT, CT}}) where {T, F, DT, CT}
    return constrained_variable_types(SOS.matrix_cone_type(CT))
end
function MOIB.added_constraint_types(
    ::Type{SOSPolynomialInSemialgebraicSetBridge{T, F, DT, CT, B, UMCT, UMST, MCT, MT, MVT}}) where {T, F, DT, CT, B, UMCT, UMST, MCT, MT, MVT}
    return [(F, SOS.SOSPolynomialSet{DT, MT, MVT, CT})]
end
function MOIB.Constraint.concrete_bridge_type(
    ::Type{<:SOSPolynomialInSemialgebraicSetBridge{T}},
    F::Type{<:MOI.AbstractVectorFunction},
    ::Type{<:SOS.SOSPolynomialSet{SemialgebraicSets.BasicSemialgebraicSet{S, PS, AT}, MT, MVT, CT}}) where {T, S, PS, AT, CT, MT, MVT}

    # promotes VectorOfVariables into VectorAffineFunction, it should be enough
    # for most use cases
    G = MOIU.promote_operation(-, T, F, MOI.VectorOfVariables)
    MCT = SOS.matrix_cone_type(CT)
    B = Certificate.get(CT, Certificate.MultiplierBasisType())
    UMCT = union_constraint_types(MCT)
    UMST = union_set_types(MCT)
    IC = Certificate.get(CT, Certificate.IdealCertificate())
    return SOSPolynomialInSemialgebraicSetBridge{T, G, AT, IC, B, UMCT, UMST, MCT, MT, MVT}
end

# Attributes, Bridge acting as an model
function MOI.get(bridge::SOSPolynomialInSemialgebraicSetBridge,
                 ::MOI.NumberOfVariables)
    return mapreduce(_num_variables, +, bridge.lagrangian_variables, init=0)
end
function MOI.get(bridge::SOSPolynomialInSemialgebraicSetBridge, ::MOI.ListOfVariableIndices)
    return Iterators.flatten([_list_variables(Qi) for Qi in bridge.lagrangian_variables])
end
function MOI.get(bridge::SOSPolynomialInSemialgebraicSetBridge{T, F, DT, CT, B, UMCT, UMST},
                 ::MOI.NumberOfConstraints{MOI.VectorOfVariables, S}) where {T, F, DT, CT, B, UMCT, UMST, S<:UMST}
    return mapreduce(cQ -> _num_constraints(cQ, MOI.ConstraintIndex{MOI.VectorOfVariables, S}), +,
                     bridge.lagrangian_constraints, init=0)
end
function MOI.get(b::SOSPolynomialInSemialgebraicSetBridge{T, F, DT, CT, B, UMCT, UMST},
                 ::MOI.ListOfConstraintIndices{MOI.VectorOfVariables, S}) where {T, F, DT, CT, B, UMCT, UMST, S<:UMST}
    C = MOI.ConstraintIndex{MOI.VectorOfVariables, S}
    return Iterators.flatten([_list_constraints(cQ, C) for cQ in bridge.lagrangian_constraints])
end
function MOI.get(::SOSPolynomialInSemialgebraicSetBridge{T, F, DT, CT, B, UMCT, UMST, MCT, MT, MVT},
                 ::MOI.NumberOfConstraints{F, SOS.SOSPolynomialSet{DT, MT, MVT, CT}}) where {T, F, DT, CT, B, UMCT, UMST, MCT, MT, MVT}
    return 1
end
function MOI.get(b::SOSPolynomialInSemialgebraicSetBridge{T, F, DT, CT, B, UMCT, UMST, MCT, MT, MVT},
                 ::MOI.ListOfConstraintIndices{F, SOS.SOSPolynomialSet{DT, MT, MVT, CT}}) where {T, F, DT, CT, B, UMCT, UMST, MCT, MT, MVT}
    return [b.constraint]
end

# Indices
function MOI.delete(model::MOI.ModelLike,
                    bridge::SOSPolynomialInSemialgebraicSetBridge)
    MOI.delete(model, bridge.constraint)
    for variables in bridge.lagrangian_variables
        _delete_variables(model, variables)
    end
end

# Attributes, Bridge acting as a constraint

# The monomials might be different from the ones of the original polynomial
# because of the ∑ λ_i s_i(x) so we don't define ConstraintPrimal and
# ConstraintDual, as the caller won't know how to reshape it
function MOI.get(::MOI.ModelLike,
                 ::MOI.ConstraintPrimal,
                 ::SOSPolynomialInSemialgebraicSetBridge)
    throw(SOS.ValueNotSupported())
end

function MOI.get(model::MOI.ModelLike, attr::MOI.ConstraintDual,
                 bridge::SOSPolynomialInSemialgebraicSetBridge)
    dual = MOI.get(model, attr, bridge.constraint)
    set = MOI.get(model, MOI.ConstraintSet(), bridge.constraint)
    μ = MultivariateMoments.measure(dual, set.monomials)
    return [dot(mono, μ) for mono in bridge.monomials]
end
function MOI.get(model::MOI.ModelLike, attr::PolyJuMP.MomentsAttribute,
                 bridge::SOSPolynomialInSemialgebraicSetBridge)
    return MOI.get(model, attr, bridge.constraint)
end

function MOI.get(model::MOI.ModelLike,
                 attr::Union{SOS.CertificateBasis, SOS.GramMatrixAttribute,
                             SOS.MomentMatrixAttribute},
                 bridge::SOSPolynomialInSemialgebraicSetBridge)
    return MOI.get(model, attr, bridge.constraint)
end
function MOI.get(model::MOI.ModelLike, attr::SOS.LagrangianMultipliers,
                 bridge::SOSPolynomialInSemialgebraicSetBridge{T, F, CT, B, UMCT, UMST, MCT, M}) where {T, F, CT, B, UMCT, UMST, MCT, M}
    @assert eachindex(bridge.lagrangian_variables) == eachindex(bridge.lagrangian_bases)
    map(i -> _gram(Q -> MOI.get(model, MOI.VariablePrimal(attr.N), Q),
                   bridge.lagrangian_variables[i], bridge.lagrangian_bases[i], T, MCT),
        eachindex(bridge.lagrangian_variables))
end


text:
using GLAbstraction

image_path = GLAbstraction.dir("tutorials", "images")
if !isdir(image_path)
    mkdir(image_path)
end
urlbase = "https://open.gl/content/code/"
for (filename,remotefilename) in (("kitten.png","sample.png"),
                                  ("puppy.png", "sample2.png"))
    fullpath = joinpath(image_path, filename)
    if !isfile(fullpath)
        download(string(urlbase, remotefilename), fullpath)
    end
end


text:
using TermWin

ex = :( f(x::Float64) = x*x+2x + 2.*sin(x / 3.0) +1 )
tshow( ex )


text:
import Base: push!, getindex, setindex!

using OrderedCollections: OrderedDict
using Oceananigans: AbstractOutputWriter, AbstractDiagnostic

#####
##### Utilities shared between diagnostics and output writers
#####

defaultname(::AbstractDiagnostic, nelems) = Symbol(:diag, nelems+1)
defaultname(::AbstractOutputWriter, nelems) = Symbol(:writer, nelems+1)

const DiagOrWriterDict = OrderedDict{S, <:Union{AbstractDiagnostic, AbstractOutputWriter}} where S

function push!(container::DiagOrWriterDict, elem)
    name = defaultname(elem, length(container))
    container[name] = elem
    return nothing
end

getindex(container::DiagOrWriterDict, inds::Integer...) = getindex(container.vals, inds...)
setindex!(container::DiagOrWriterDict, newvals, inds::Integer...) = setindex!(container.vals, newvals, inds...)

function push!(container::DiagOrWriterDict, elems...)
    for elem in elems
        push!(container, elem)
    end
    return nothing
end

"""
    validate_interval(frequency, interval)

Ensure that frequency and interval are not both `nothing`.
"""
function validate_interval(frequency, interval)
    isnothing(frequency) && isnothing(interval) && @error "Must specify a frequency or interval!"
    return nothing
end

has_interval(obj) = :interval in propertynames(obj) && obj.interval != nothing
has_frequency(obj) = :frequency in propertynames(obj) && obj.frequency != nothing

function interval_is_ripe(clock, obj)
    if has_interval(obj) && clock.time >= obj.previous + obj.interval
        obj.previous = clock.time - rem(clock.time, obj.interval)
        return true
    else
        return false
    end
end

frequency_is_ripe(clock, obj) = has_frequency(obj) && clock.iteration % obj.frequency == 0

function time_to_run(clock, output_writer)

    interval_is_ripe(clock, output_writer) && return true
    frequency_is_ripe(clock, output_writer) && return true

    # If the output writer does not specify an interval or frequency,
    # it is unable to write output and we throw an error as a convenience.
    has_interval(output_writer) || has_frequency(output_writer) ||
        error("$(typeof(output_writer)) must have a frequency or interval specified!")

    return false
end


text:
"""
    laplace(decisionMat)

    Apply Laplace method for a given decision matrix (for convenience, in type of DataFrame).

# Arguments:
 - `decisionMat::DataFrame`: Decision matrix with n alternatives and m criteria.

# Output
- `::LaplaceResult`: LaplaceResult object that holds multiple outputs including the best alternative.

# Examples
```julia-repl
julia> mat = [
        3000 2750 2500 2250;
        1500 4750 8000 7750;
        2000 5250 8500 11750
]

julia> dm = makeDecisionMatrix(mat)

julia> result = laplace(dm)
```
"""
function laplace(decisionMatrix::DataFrame)::LaplaceResult

    n, p = size(decisionMatrix)

    probs = [1.0 / p for i in 1:p]

    expecteds = zeros(Float64, n)

    # m = convert(Array{Float64,2}, decisionMatrix)
    m = Matrix{Float64}(decisionMatrix)

    for i in 1:n
        expecteds[i] = (m[i,:] .* probs)  |> sum
    end

    bestIndex = sortperm(expecteds) |> last

    result = LaplaceResult(
        expecteds,
        bestIndex
    )

    return result
end

"""
    maximin(decisionMat)

    Apply Maximin method for a given decision matrix (for convenience, in type of DataFrame).

# Arguments:
 - `decisionMat::DataFrame`: Decision matrix with n alternatives and m criteria.

# Output
- `::MaximinResult`: MaximinResult object that holds multiple outputs including the best alternative.

# Examples
```julia-repl
julia> mat = [
        26 26 18 22;
        22 34 30 18;
        28 24 34 26;
        22 30 28 20
    ]

julia> dm = makeDecisionMatrix(mat)

julia> result = maximin(dm)
```
"""
function maximin(decisionMatrix::DataFrame)::MaximinResult

    n, p = size(decisionMatrix)

    # m = convert(Array{Float64,2}, decisionMatrix)
    m = Matrix{Float64}(decisionMatrix)

    rmins = rowmins(decisionMatrix)

    bestIndex = sortperm(rmins) |> last

    result = MaximinResult(
        rmins,
        bestIndex
    )

    return result
end

"""
    maximax(decisionMat)

    Apply Maximax method for a given decision matrix (for convenience, in type of DataFrame).

# Arguments:
 - `decisionMat::DataFrame`: Decision matrix with n alternatives and m criteria.

# Output
- `::MaximaxResult`: MaximaxResult object that holds multiple outputs including the best alternative.

# Examples
```julia-repl
julia> mat = [
        26 26 18 22;
        22 34 30 18;
        28 24 34 26;
        22 30 28 20
    ]

julia> dm = makeDecisionMatrix(mat)

julia> result = maximax(dm)
```
"""
function maximax(decisionMatrix::DataFrame)::MaximaxResult

    n, p = size(decisionMatrix)

    # m = convert(Array{Float64,2}, decisionMatrix)
    m = Matrix{Float64}(decisionMatrix)

    rmaxs = rowmaxs(decisionMatrix)

    bestIndex = sortperm(rmaxs) |> last

    result = MaximaxResult(
        rmaxs,
        bestIndex
    )

    return result
end

"""
    minimax(decisionMat)

    Apply Minimax method for a given decision matrix (for convenience, in type of DataFrame).

# Arguments:
 - `decisionMat::DataFrame`: Decision matrix with n alternatives and m criteria.

# Output
- `::MinimaxResult`: MinimaxResult object that holds multiple outputs including the best alternative.

# Examples
```julia-repl
julia> mat = [
        26 26 18 22;
        22 34 30 18;
        28 24 34 26;
        22 30 28 20
    ]

julia> dm = makeDecisionMatrix(mat)

julia> result = minimax(dm)
```
"""
function minimax(decisionMatrix::DataFrame)::MinimaxResult

    n, p = size(decisionMatrix)

    # m = convert(Array{Float64,2}, decisionMatrix)
    m = Matrix{Float64}(decisionMatrix)

    rmaxs = rowmaxs(decisionMatrix)

    bestIndex = sortperm(rmaxs) |> first

    result = MinimaxResult(
        rmaxs,
        bestIndex
    )

    return result
end

"""
    minimin(decisionMat)

    Apply Minimin method for a given decision matrix (for convenience, in type of DataFrame).

# Arguments:
 - `decisionMat::DataFrame`: Decision matrix with n alternatives and m criteria.

# Output
- `::MiniminResult`: Minimin object that holds multiple outputs including the best alternative.

# Examples
```julia-repl
julia> mat = [
        26 26 18 22;
        22 34 30 18;
        28 24 34 26;
        22 30 28 20
    ]

julia> dm = makeDecisionMatrix(mat)

julia> result = minimin(dm)
```
"""
function minimin(decisionMatrix::DataFrame)::MiniminResult

    n, p = size(decisionMatrix)

    # m = convert(Array{Float64,2}, decisionMatrix)
    m = Matrix{Float64}(decisionMatrix)

    rmins = rowmins(decisionMatrix)

    bestIndex = sortperm(rmins) |> first

    result = MiniminResult(
        rmins,
        bestIndex
    )

    return result
end

"""
    savage(decisionMat)

    Apply Savage method for a given decision matrix (for convenience, in type of DataFrame).

# Arguments:
 - `decisionMat::DataFrame`: Decision matrix with n alternatives and m criteria.

# Output
- `::SavageResult`: SavageResult object that holds multiple outputs including the best alternative.

# Examples
```julia-repl
julia> mat = [
        26 26 18 22;
        22 34 30 18;
        28 24 34 26;
        22 30 28 20
    ]

julia> dm = makeDecisionMatrix(mat)

julia> result = savage(dm)

julia> result.bestIndex
4
```
"""
function savage(decisionMatrix::DataFrame)::SavageResult

    n, p = size(decisionMatrix)

    cmaxs = colmaxs(decisionMatrix)

    newDecisionMatrix = similar(decisionMatrix)

    @inbounds for i in 1:p
        newDecisionMatrix[:, i] = cmaxs[i] .- decisionMatrix[:, i]
    end

    rmaxs = scores = rowmaxs(newDecisionMatrix)

    bestIndex = rmaxs |> sortperm |> first

    result = SavageResult(
        newDecisionMatrix,
        scores,
        bestIndex
    )

    return result
end

"""
    hurwicz(decisionMat; alpha = 0.5)

    Apply Hurwicz method for a given decision matrix (for convenience, in type of DataFrame).

# Arguments:
 - `decisionMat::DataFrame`: Decision matrix with n alternatives and m criteria.
 - `alpha::Float64`: The optional alpha value for the Hurwicz method. Default is 0.5.

# Output
- `::HurwiczResult`: HurwiczResult object that holds multiple outputs including the best alternative.

# Examples
```julia-repl
julia> mat = [
        26 26 18 22;
        22 34 30 18;
        28 24 34 26;
        22 30 28 20
    ]

julia> dm = makeDecisionMatrix(mat)

julia> result = hurwicz(dm)

julia> result.bestIndex
3
```
"""
function hurwicz(decisionMatrix::DataFrame; alpha::Float64=0.5)::HurwiczResult

    n, p = size(decisionMatrix)

    rmaxs = rowmaxs(decisionMatrix)
    rmins = rowmins(decisionMatrix)

    scores = alpha .* rmaxs .+ (1.0 - alpha) .* rmins

    bestIndex = scores |> sortperm |>  last

    result = HurwiczResult(
        scores,
        bestIndex
    )

    return result

end

"""
    mle(decisionMat, weights)

    Apply MLE (Maximum Likelihood) method for a given decision matrix (for convenience, in type of DataFrame) and weights.

# Arguments:
 - `decisionMat::DataFrame`: Decision matrix with n alternatives and m criteria.
 - `weights::Array{Float64,1}`: Array of weights for each criterion that sums up to 1.0.

# Output
- `::MLEResult`: MLEResult object that holds multiple outputs including the best alternative.

# Examples
```julia-repl
julia> mat = [
        26 26 18 22;
        22 34 30 18;
        28 24 34 26;
        22 30 28 20
    ]

julia> dm = makeDecisionMatrix(mat)
julia> weights = [0.2, 0.5, 0.2, 0.1]
julia> result = mle(dm)

julia> result.bestIndex
2
```
"""
function mle(decisionMatrix::DataFrame, weights::Array{Float64,1})::MLEResult

    w = unitize(weights)

    weightedMatrix = w * decisionMatrix

    scores = rowsums(weightedMatrix)

    bestIndex = scores |> sortperm |> last

    result = MLEResult(
        scores,
        bestIndex
    )

    return result

end

"""
    expectedregret(decisionMat, weights)

    Apply Expected Regret method for a given decision matrix (for convenience, in type of DataFrame) and weights.

# Arguments:
 - `decisionMat::DataFrame`: Decision matrix with n alternatives and m criteria.
 - `weights::Array{Float64,1}`: Array of weights for each criterion that sums up to 1.0.

# Output
- `::ExpectedRegretResult`: ExpectedRegretResult object that holds multiple outputs including the best alternative.

# Examples
```julia-repl
julia> mat = [
        26 26 18 22;
        22 34 30 18;
        28 24 34 26;
        22 30 28 20
    ]

julia> dm = makeDecisionMatrix(mat)
julia> weights = [0.2, 0.5, 0.2, 0.1]
julia> result = expectedregret(dm)

julia> result.bestIndex
2
```
"""
function expectedregret(decisionMatrix::DataFrame, weights::Array{Float64,1})

    _, p = size(decisionMatrix)

    w = unitize(weights)

    cmaxs = colmaxs(decisionMatrix)

    regretmat = similar(decisionMatrix)

    for i in 1:p
        regretmat[:, i] = cmaxs[i] .- decisionMatrix[:, i]
    end

    weightedregret = w * regretmat

    scores = rowsums(weightedregret)

    bestIndex = scores |> sortperm |> first

    result = ExpectedRegretResult(
        scores,
        bestIndex
    )

    return result
end

max_stars_repo_name: drvinceknight/JMcDM

max_issues_repo_name: drvinceknight/JMcDM

max_forks_repo_name: drvinceknight/JMcDM


text:
module Models

export IncompressibleModel, NonDimensionalImcompressibleModel, HydrostaticFreeSurfaceModel, ShallowWaterModel

using Oceananigans: AbstractModel

abstract type AbstractIncompressibleModel{TS} <: AbstractModel{TS} end

include("IncompressibleModels/IncompressibleModels.jl")
include("HydrostaticFreeSurfaceModels/HydrostaticFreeSurfaceModels.jl")
include("ShallowWaterModels/ShallowWaterModels.jl")

using .IncompressibleModels: IncompressibleModel, NonDimensionalImcompressibleModel
using .HydrostaticFreeSurfaceModels: HydrostaticFreeSurfaceModel
using .ShallowWaterModels: ShallowWaterModel

end


text:
# Autogenerated wrapper script for Qt5QuickControls_jll for x86_64-w64-mingw32-cxx11
export quickcontrols

using Qt5Declarative_jll
JLLWrappers.@generate_wrapper_header("Qt5QuickControls")
JLLWrappers.@declare_file_product(quickcontrols)
function __init__()
    JLLWrappers.@generate_init_header(Qt5Declarative_jll)
    JLLWrappers.@init_file_product(
        quickcontrols,
        "qml\\QtQuick\\Controls",
    )

    JLLWrappers.@generate_init_footer()
end  # __init__()


text:
function create_propagators(obj::BatchLSODModel, arg0::RealVector)
    return jcall(obj, "createPropagators", Vector{AbstractIntegratedPropagator}, (RealVector,), arg0)
end

function fetch_evaluated_measurement(obj::BatchLSODModel, arg0::jint, arg1::EstimatedMeasurement)
    return jcall(obj, "fetchEvaluatedMeasurement", void, (jint, EstimatedMeasurement), arg0, arg1)
end

function get_evaluations_count(obj::BatchLSODModel)
    return jcall(obj, "getEvaluationsCount", jint, ())
end

function get_iterations_count(obj::BatchLSODModel)
    return jcall(obj, "getIterationsCount", jint, ())
end

function get_selected_propagation_drivers_for_builder(obj::BatchLSODModel, arg0::jint)
    return jcall(obj, "getSelectedPropagationDriversForBuilder", ParameterDriversList, (jint,), arg0)
end

function is_forward_propagation(obj::BatchLSODModel)
    return jcall(obj, "isForwardPropagation", jboolean, ())
end

function set_evaluations_counter(obj::BatchLSODModel, arg0::Incrementor)
    return jcall(obj, "setEvaluationsCounter", void, (Incrementor,), arg0)
end

function set_iterations_counter(obj::BatchLSODModel, arg0::Incrementor)
    return jcall(obj, "setIterationsCounter", void, (Incrementor,), arg0)
end

function value(obj::MultivariateJacobianFunction, arg0::RealVector)
    return jcall(obj, "value", Pair, (RealVector,), arg0)
end


text:
export LS_Function_Meta

mutable struct LS_Function_Meta

    # Successful and very succesful iteration threshold for ARC/TR variant
    eps1 :: Float64
    eps2 :: Float64

    # Reduction/Augmentation size of the trust region/cubic regularisation paramter
    # for the ARC/TR varitans
    aug :: Float64
    red :: Float64

    # Trust region/Cubic regularisation parameter for the ARC/TR variants
    Δ  :: Float64
    Δn :: Float64  # only for the TR variants
    Δp :: Float64  # only for the TR variants

    # Direction used (Newton's, Secant or Improved Secant)
    dir :: Symbol

    # Additionnal step. If true, this option will make another line search iteration
    # after finding an admissible step size.
    add_step :: Bool ## Pertinent à garder ?? Sam

        function LS_Function_Meta(;eps1     :: Float64 = 0.25,
                                  eps2      :: Float64 = 0.75,
                                  aug       :: Float64 = 0.7,
                                  red       :: Float64 = 0.1,
                                  Δ         :: Float64 = 10.0,
                                  dir       :: Symbol  = :Nwt,
                                  add_step  :: Bool    = false)

            Δp = Δ
            Δn = max(0.0, -Δ)

            return new(eps1, eps2, aug, red, Δ, Δn, Δp, dir, add_step)
        end # function
end # struct


text:
using Documenter, ElectromagneticFields

ENV["GKSwstype"] = "100"

makedocs(
    sitename = "ElectromagneticFields.jl",
    format = Documenter.HTML(
                prettyurls = get(ENV, "CI", nothing) == "true",
                assets = [asset("assets/style.css", class=:css, islocal=true)]),
    pages = ["Home" => "index.md",
             "Analytic Fields" => "analytic.md",
             "Modules" => "modules.md",
            ]
)

deploydocs(
    repo   = "github.com/JuliaPlasma/ElectromagneticFields.jl"
)


text:
const API_URL = "https://api.telegram.org/bot"

function get_me(token)
    return JSON.parse(String(HTTP.get(API_URL * token *"/getMe").body))
end

function get_updates(token, offset=0)
    return JSON.parse(String(HTTP.get(API_URL * token *"/getUpdates?offset=" * string(offset)).body))
end

function send_message(token, chat_id, message="")
    return String(HTTP.post(API_URL * token * "/sendMessage?chat_id=" * chat_id * "&text=" * message))
end


text:
using NestedSamplers.Bounds: randball, volume_prefactor

@testset "Rand Sphere" begin
    for _ in 1:100, k in 1:10
        x = randball(rng, Float64, k)
        @test sum(t->t^2, x) < 1
    end
end

@testset "Volume Prefactor" begin
    @test volume_prefactor(1) ≈ 2
    @test volume_prefactor(2) ≈ π
    @test volume_prefactor(3) ≈ 4 / 3 * π
    @test volume_prefactor(4) ≈ 1 / 2 * π^2
    @test volume_prefactor(5) ≈ 8 / 15 * π^2
    @test volume_prefactor(6) ≈ 1 / 6 * π^3
    @test volume_prefactor(7) ≈ 16 / 105 * π^3
    @test volume_prefactor(9) ≈ 32 / 945 * π^4
end