text:
# Test Stan.jl examples.

using DataFrames, Test

TestDir = @__DIR__
ExampleDir = joinpath(TestDir, "..")

examples = [

  "Examples/Bernoulli/bernoulli.jl",
  "Examples/Binomial/binomial.jl",
  "Examples/Binormal/binormal.jl",
  "Examples/Dyes/dyes.jl",
  "Examples/EightSchools/schools8.jl",
  "Examples/ARM/Ch03/Kid/kidscore.jl",

  "Examples_Stan_Methods/Diagnose/diagnose.jl",
  "Examples_Stan_Methods/Optimize/optimize.jl",
  #"Examples_Stan_Methods/Variational/variational.jl",
  "Examples_Stan_Methods/StanQuap/howell1.jl",

  "Examples_Test_Cases/Diagnostics/diagnostics.jl",
  "Examples_Test_Cases/InitThetaDict/init_dict.jl",
  "Examples_Test_Cases/InitThetaDictArray/init_dict_array.jl",
  "Examples_Test_Cases/InitThetaFile/init_file.jl",
  "Examples_Test_Cases/ScalarObs/scalar.jl",
  "Examples_Test_Cases/ZeroLengthArray/zerolengtharray.jl",

  "Examples_Stan_Methods/Generate_Quantities/generate_quantities.jl",
  "Examples_Stan_Methods/Parse_and_Interpolate/parse.jl"
]

if haskey(ENV, "JULIA_CMDSTAN_HOME")
  println("\nRunning Stan.jl v7.x test examples")

  for example in examples
      println("\n* $(joinpath(TestDir, example)) *\n")

      cd(TestDir) do
        include(joinpath(TestDir, example))
      end

  end
else
  println("\nJULIA_CMDSTAN_HOME not set. Skipping tests")
end


text:
module SimpleSDMLayers

using ArchGDAL
using HTTP
using RecipesBase
using ZipFile
using Requires
using Statistics

include(joinpath("lib", "types.jl"))
export SimpleSDMLayer, SimpleSDMResponse, SimpleSDMPredictor

include(joinpath("lib", "overloads.jl"))

include(joinpath("lib", "generated.jl"))

include(joinpath("lib", "basics.jl"))
export latitudes, longitudes

include(joinpath("lib", "iteration.jl"))

include(joinpath("datasets", "sources.jl"))
include(joinpath("datasets", "download_layer.jl"))
export EarthEnv, WorldClim, BioClim

include(joinpath("datasets", "geotiff.jl"))
include(joinpath("datasets", "raster.jl"))
include(joinpath("datasets", "worldclim.jl"))
include(joinpath("datasets", "chelsa.jl"))
include(joinpath("datasets", "landcover.jl"))
include(joinpath("datasets", "ascii.jl"))
export worldclim, bioclim, landcover

include(joinpath("operations", "coarsen.jl"))
include(joinpath("operations", "sliding.jl"))
include(joinpath("operations", "mask.jl"))
include(joinpath("operations", "rescale.jl"))
include(joinpath("operations", "mosaic.jl"))
export coarsen, slidingwindow, mask, rescale!, rescale, mosaic

include(joinpath("recipes", "recipes.jl"))

# This next bit is about being able to change the path for raster assets
# globally, which avoids duplication this argument across multiple functions.
_layers_assets_path = "assets"
function assets_path()
    isdir(SimpleSDMLayers._layers_assets_path) || mkdir(SimpleSDMLayers._layers_assets_path)
    return SimpleSDMLayers._layers_assets_path
end

# Fixes the export of clip when GBIF or others are loaded
clip(::T) where {T <: SimpleSDMLayer} = nothing
export clip

function __init__()
    @require GBIF="ee291a33-5a6c-5552-a3c8-0f29a1181037" begin
        @info "GBIF integration loaded"
        include(joinpath(dirname(pathof(SimpleSDMLayers)), "integrations", "GBIF.jl"))
    end
    @require DataFrames = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0" begin
        @info "DataFrames integration loaded"
        include(joinpath(dirname(pathof(SimpleSDMLayers)), "integrations", "DataFrames.jl"))
    end

end

end # module

ext: jl


text:
struct SeaCucumberHerd
    east::Dict{Int, Vector{Int}}
    south::Dict{Int, Vector{Int}}
    xmax::Int
    ymax::Int
end

function moveeast!(herd::SeaCucumberHerd)
    n = 0
    for (x, ys) in deepcopy(herd.east)
        for (i, y) in enumerate(ys)
            ynew = mod1(y + 1, herd.ymax)
            ynew in ys && continue
            ynew in keys(herd.south) && x in herd.south[ynew] && continue
            herd.east[x][i] = ynew
            n += 1
        end
    end
    n
end

function movesouth!(herd::SeaCucumberHerd)
    n = 0
    for (y, xs) in deepcopy(herd.south)
        for (i, x) in enumerate(xs)
            xnew = mod1(x + 1, herd.xmax)
            xnew in xs && continue
            xnew in keys(herd.east) && y in herd.east[xnew] && continue
            herd.south[y][i] = xnew
            n += 1
        end
    end
    n
end

function step!(herd::SeaCucumberHerd)
    moveeast!(herd) + movesouth!(herd)
end

function Base.parse(::Type{SeaCucumberHerd}, lines::Vector{String})
    east = Dict{Int, Vector{Int}}()
    south = Dict{Int, Vector{Int}}()
    for (x, line) in enumerate(lines)
        for (y, char) in enumerate(collect(line))
            char == '>' && push!(get!(valtype(east), east, x), y)
            char == 'v' && push!(get!(valtype(south), south, y), x)
        end
    end
    SeaCucumberHerd(east, south, length(lines), length(lines[1]))
end

herd = parse(SeaCucumberHerd, readlines("day25/cucumbers.txt"))

@time p1 = maximum(Iterators.takewhile(_ -> step!(herd) > 0, Iterators.countfrom(1))) + 1

@show p1


text:
"""
    shifted_backward_sub!(x, R, λ, k) → x

Solve the problem (R[1:k,1:k] - λI) \\ x[1:k] in-place.
"""
function shifted_backward_sub!(x, R::AbstractMatrix{Tm}, λ, k) where {Tm<:Real}
    # Real arithmetic with quasi-upper triangular R
    @inbounds while k > 0
        if k > 1 && R[k,k-1] != zero(Tm)
            # Solve 2x2 problem
            R11, R12 = R[k-1,k-1] - λ, R[k-1,k]
            R21, R22 = R[k  ,k-1]    , R[k  ,k] - λ
            det = R11 * R22 - R21 * R12
            a1 = ( R22 * x[k-1] - R12 * x[k-0]) / det
            a2 = (-R21 * x[k-1] + R11 * x[k-0]) / det
            x[k-1] = a1
            x[k-0] = a2

            # Backward substitute
            for i = 1 : k-2
                x[i] -= R[i,k-1] * x[k-1] + R[i,k-0] * x[k-0]
            end
            k -= 2
        else
            # Solve 1x1 "problem"
            x[k] /= R[k,k] - λ

            # Backward substitute
            for i = 1 : k - 1
                x[i] -= R[i,k] * x[k]
            end

            k -= 1
        end
    end

    x
end

function shifted_backward_sub!(x, R::AbstractMatrix, λ, k)
    # Generic implementation, upper triangular R
    @inbounds while k > 0
        # Solve 1x1 "problem"
        x[k] /= R[k,k] - λ

        # Backward substitute
        for i = 1 : k - 1
            x[i] -= R[i,k] * x[k]
        end

        k -= 1
    end

    x
end

"""
    collect_eigen!(x, R, j) → k

Store the `j`th eigenvector of an upper triangular matrix `R` in `x`.
In the end `norm(x[1:k]) = 1` This function leaves x[k+1:end] untouched!
"""
function collect_eigen!(x::AbstractVector{Tv}, R::AbstractMatrix{Tm}, j::Integer) where {Tm<:Real,Tv<:Number}
    n = size(R, 2)

    @inbounds begin
        # If it's a conjugate pair with the next index, then just increment j.
        if j < n && R[j+1,j] != zero(Tv)
            j += 1
        end

        # Initialize the rhs and do the first backward substitution
        # Then do the rest of the shifted backward substitution in another function,
        # cause λ is either real or complex.
        if j > 1 && R[j,j-1] != 0
            # Complex arithmetic
            R11, R21 = R[j-1,j-1], R[j-0,j-1]
            R12, R22 = R[j-1,j-0], R[j-0,j-0]
            det = R11 * R22 - R21 * R12
            tr = R11 + R22
            λ = (tr + sqrt(complex(tr * tr - 4det))) / 2
            x[j-1] = -R12 / (R11 - λ)
            x[j-0] = one(Tv)
            for i = 1 : j-2
                x[i] = -R[i,j-1] * x[j-1] - R[i,j]
            end

            shifted_backward_sub!(x, R, λ, j-2)
        else
            # Real arithmetic
            λ = R[j,j]
            x[j] = one(Tv)
            for i = 1 : j-1
                x[i] = -R[i,j]
            end
            shifted_backward_sub!(x, R, λ, j-1)
        end

        # Normalize
        nrm = zero(real(Tv))
        for k = 1:j
            nrm += abs2(x[k])
        end
        scale = inv(√nrm)
        for k = 1:j
            x[k] *= scale
        end
    end

    return j
end

function collect_eigen!(x::AbstractVector{Tv}, R::AbstractMatrix, j::Integer) where {Tv}
    n = size(R, 2)

    @inbounds begin
        λ = R[j,j]
        x[j] = one(Tv)
        for i = 1 : j-1
            x[i] = -R[i,j]
        end

        shifted_backward_sub!(x, R, λ, j-1)

        # Normalize
        nrm = zero(real(Tv))
        for k = 1:j
            nrm += abs2(x[k])
        end
        scale = inv(√nrm)
        for k = 1:j
            x[k] *= scale
        end
    end

    return j
end


text:
module CellStatesTests

using Test
using FillArrays
using Gridap.Helpers
using Gridap.Fields
using Gridap.CellData
using Gridap.TensorValues
using Gridap.ReferenceFEs
using Gridap.Integration
using Gridap.Geometry

domain = (0,1,0,1)
cells = (3,3)
model = CartesianDiscreteModel(domain,cells)

Ω = Triangulation(model)
dΩ = Measure(Ω,2)

f = CellState{Float64}(undef,dΩ)
@test f.values[1] !== f.values[2]
updater(f) = true, 1.0
update_state!(updater,f)
@test sum(∫(f)*dΩ) ≈ 1

f = CellState(1,dΩ)
@test f.values[1] !== f.values[2]
@test sum(∫(f)*dΩ) ≈ 1

f = CellState(2.0,dΩ)
g = CellState(VectorValue(4.0,4.0),dΩ)
h = CellState(2.0,dΩ)
updater(f,g,h) = true, 0.5*f, 0.25*g
update_state!(updater,f,g,h)
@test sum(∫(f)*dΩ) ≈ 1
@test sum(∫(g)*dΩ) ≈ VectorValue(1,1)
@test sum(∫(h)*dΩ) ≈ 2

f = CellState(2.0,dΩ)
g = CellState(VectorValue(4.0,4.0),dΩ)
h = CellField(2.0,Ω)
updater(f,g,h) = true, 0.5*f, 0.25*g
update_state!(updater,f,g,h)
@test sum(∫(f)*dΩ) ≈ 1
@test sum(∫(g)*dΩ) ≈ VectorValue(1,1)
@test sum(∫(h)*dΩ) ≈ 2

r1 = f*h
@test sum(∫(r1)*dΩ) ≈ 2

σ(f,g,h) = f*g*h
r2 = σ∘(f,g,h)
@test sum(∫(r2)*dΩ) ≈ VectorValue(2,2)

r = r1*r2*h
@test sum(∫(r)*dΩ) ≈ VectorValue(8,8)

#x = get_cell_points(dΩ)
#using Gridap.Visualization
#writevtk(x,"x",cellfields=["f"=>f,"g"=>g])

end # module


text:
"""
Internal DuckDB database handle.
"""
mutable struct DuckDBHandle
    file::String
    handle::duckdb_database
    functions::Vector{Any}
    registered_objects::Dict{Any, Any}

    function DuckDBHandle(f::AbstractString, config::Config)
        f = String(isempty(f) ? f : expanduser(f))
        handle = Ref{duckdb_database}()
        error = Ref{Ptr{UInt8}}()
        if duckdb_open_ext(f, handle, config.handle, error) != DuckDBSuccess
            error_message = unsafe_string(error[])
            duckdb_free(error[])
            throw(ConnectionException(error_message))
        end

        db = new(f, handle[], Vector(), Dict())
        finalizer(_close_database, db)
        return db
    end
end

function _close_database(db::DuckDBHandle)
    # disconnect from DB
    if db.handle != C_NULL
        duckdb_close(db.handle)
    end
    return db.handle = C_NULL
end

"""
A connection object to a DuckDB database.

Transaction contexts are local to a single connection.

A connection can only run a single query concurrently.
It is possible to open multiple connections to a single DuckDB database instance.
Multiple connections can run multiple queries concurrently.
"""
mutable struct Connection
    db::DuckDBHandle
    handle::duckdb_connection

    function Connection(db::DuckDBHandle)
        handle = Ref{duckdb_connection}()
        if duckdb_connect(db.handle, handle) != DuckDBSuccess
            throw(ConnectionException("Failed to open connection"))
        end
        con = new(db, handle[])
        finalizer(_close_connection, con)
        return con
    end
end

function _close_connection(con::Connection)
    # disconnect
    if con.handle != C_NULL
        duckdb_disconnect(con.handle)
    end
    con.handle = C_NULL
    return
end

"""
A DuckDB database object.

By default a DuckDB database object has an open connection object (db.main_connection).
When the database object is used directly in queries, it is actually the underlying main_connection that is used.

It is possible to open new connections to a single database instance using DBInterface.connect(db).
"""
mutable struct DB <: DBInterface.Connection
    handle::DuckDBHandle
    main_connection::Connection

    function DB(f::AbstractString, config::Config)
        set_config(config, "threads", "1")
        handle = DuckDBHandle(f, config)
        main_connection = Connection(handle)

        db = new(handle, main_connection)
        _add_data_frame_scan(db)
        return db
    end
    function DB(f::AbstractString)
        return DB(f, Config())
    end
end

function close_database(db::DB)
    _close_connection(db.main_connection)
    _close_database(db.handle)
    return
end

const VECTOR_SIZE = duckdb_vector_size()

DB() = DB(":memory:")
DBInterface.connect(::Type{DB}) = DB()
DBInterface.connect(::Type{DB}, f::AbstractString) = DB(f)
DBInterface.connect(::Type{DB}, f::AbstractString, config::Config) = DB(f, config)
DBInterface.connect(db::DB) = Connection(db.handle)
DBInterface.close!(db::DB) = close_database(db)
DBInterface.close!(con::Connection) = _close_connection(con)
Base.close(db::DB) = close_database(db)
Base.isopen(db::DB) = db.handle != C_NULL

Base.show(io::IO, db::DuckDB.DB) = print(io, string("DuckDB.DB(", "\"$(db.handle.file)\"", ")"))
Base.show(io::IO, con::DuckDB.Connection) = print(io, string("DuckDB.Connection(", "\"$(con.db.file)\"", ")"))

max_stars_repo_name: Dtenwolde/duckdb

max_issues_repo_name: Dtenwolde/duckdb

max_forks_repo_name: Dtenwolde/duckdb


text:
function VelocityScale(z,h,L,ustar,θv=nothing,wθv=nothing)
  xi=z/L
  psis=holtslag_psis(xi)
  psim=holtslag_psim(xi)
  if xi>0
      wt=ustar/psis
      wm=wt
  else
      if z/h<0.1
          wt=ustar/psis
          wm=ustar/psim
      else
          a=7.2
          xi1=0.1*h/L
          psis1=holtslag_psis(xi1)
          psim1=holtslag_psim(xi1)
          #wθv<0 ? println("wθv",wθv) : nothing
          #println("θv",θv)
          wstar=((gravity_mks/θv)*wθv*h)^(1/3)
          # this part is different than Holtslag et. al to ensure continueos
          # velositiy scale at the surface and the mixed layer above.
          ct=(ustar/wstar)^3*(1/psis1^3-1)
          cm=(ustar/wstar)^3*(1/psim1^3-1)
          wm=(ustar^3+cm*wstar^3)^(1/3)
          wt=(ustar^3+ct*wstar^3)^(1/3)
          #Pr=max(min(psis1/psim1*abs(xi1)+a*karman*(0.1*(wstar/wm)),4),1)
          #wt=wm/Pr
      end
  end
  return wt,wm
end


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

using Markdown
using InteractiveUtils

# ╔═╡ 2ad11ff8-b8c8-11eb-1c46-f3babe900e58
using Luxor

# ╔═╡ de5764b5-7203-41d5-94e1-438bcd8c75fb
md"Based on [inconvergent/differential](https://github.com/inconvergent/differential-line/tree/d951ed459a99fd87713b8b5a2aee06685119c007)"

# ╔═╡ 328c272f-4d85-4bb5-928a-8d95883498ba
function draw_points(points)
	for i in 1:length(points)
		next_i = i < length(points) ? i + 1 : 1
		line(points[i], points[next_i], :stroke)
		# circle(points[i], 1, :fill)
	end
end

# ╔═╡ 4b35feec-702d-402f-8015-5d77ea9a3b67
function attraction_step(points, farl, nearl, step)
	n_points = length(points)
	d_points = [Point(0, 0) for _ in 1:n_points]
	# for every point, attract and reject
	for i in 1:n_points
		next_i = i < n_points ? i + 1 : 1
		prev_i = i > 1 ? i - 1 : n_points

		v = points[i]

		# for every other point, attract or reject
		for j in 1:n_points
			w = points[j]
			diff = v - w
			norm = sqrt(v.x^2 + v.y^2)

			if j == next_i || j == prev_i
				# it is one of the neighbors
				# don't want to be too close
				if norm >= nearl
					# attract
					d_points[i] -= diff/norm*step
				end
			else
				# reject if not too far
				# closer points reject stronger
				if norm < farl
					d_points[i] += diff*(farl/norm-1)*step
				end
			end
		end
	end

	for i in 1:n_points
		points[i] += d_points[i]
	end
end

# ╔═╡ 4e291e01-6601-4102-8038-6f082e0ffedd
@draw begin
	n_init_points = 40
	radius = 100
	n_steps = 400
	draw_every = 10
	step = 10
	farl = 40
	nearl = 2
	setline(1)

	angles = sort(rand(n_init_points)*2pi)

	points = [Point(radius*cos(a), radius*sin(a)) for a in angles]

	draw_points(points)

	for i in 1:n_steps
		attraction_step(points, farl, nearl, step)
		if i % draw_every == 0
			draw_points(points)
		end
	end
end

# ╔═╡ Cell order:
# ╠═de5764b5-7203-41d5-94e1-438bcd8c75fb
# ╠═2ad11ff8-b8c8-11eb-1c46-f3babe900e58
# ╠═328c272f-4d85-4bb5-928a-8d95883498ba
# ╠═4b35feec-702d-402f-8015-5d77ea9a3b67
# ╠═4e291e01-6601-4102-8038-6f082e0ffedd


text:
for (f,_f) in zip((:ustrip, :uconvert), (:_ustrip, :_uconvert))
    @eval begin
        function Unitful.$f(unit::Units, grid::AxisGrid)
            grid_axes = collect(grid)
            u_grid = map.(g->$f(unit, g), grid_axes)

            return AxisGrid(u_grid..., names=propertynames(grid))
        end

        function Unitful.$f(unit::Units, grid::SparseAxisGrid)
            grid_axes = collect(grid)
            u_grid = map(grid_axes) do g
                $_f(unit, g)
            end

            return SparseAxisGrid(u_grid..., names=propertynames(grid))
        end

        function Unitful.$f(unit::Units, grid::ParticlePositions)
            grid_axes = collect(grid)
            u_grid = map.(g->$f(unit, g), grid_axes)

            names = propertynames(grid)
            mins = ($f).(minimum(grid))
            maxs = ($f).(maximum(grid))

            return ParticlePositions(u_grid...; names, mins, maxs)
        end
    end
end

for (f,u) in zip((:_ustrip, :_uconvert), (:ustrip, :uconvert))
    @eval begin
        function $f(u::Units, x::Base.TwicePrecision)
            lo = $u(u, x.lo)
            hi = $u(u, x.hi)

            Base.TwicePrecision(hi, lo)
        end

        function $f(u::Units, x::StepRange)
            start = $u(u, first(x))
            st = $u(u, step(x))
            stop = $u(u, last(x))

            StepRange(start, st, stop)
        end

        function $f(u::Units, x::StepRangeLen)
            ref = $f(u, x.ref)
            step = $f(u, x.step)
            len = x.len
            offset = x.offset

            StepRangeLen(ref, step, len, offset)
        end
    end
end

function _ustrip(x::StepRange)
    start = ustrip(first(x))
    st = ustrip(step(x))
    stop = ustrip(last(x))

    StepRange(start, st, stop)
end

function _ustrip(x::StepRangeLen)
    ref = ustrip(x.ref)
    step = ustrip(x.step)
    len = x.len
    offset = x.offset

    StepRangeLen(ref, step, len, offset)
end

function Unitful.ustrip(grid::AxisGrid)
    !hasunit(grid) && return grid
    grid_axes = collect(grid)
    u_grid = map.(ustrip, grid_axes)
    names = propertynames(grid)

    return AxisGrid(u_grid...; names)
end

function Unitful.ustrip(grid::SparseAxisGrid)
    !hasunit(grid) && return grid
    grid_axes = collect(grid)
    u_grid = map(_ustrip, grid_axes)
    names = propertynames(grid)

    return SparseAxisGrid(u_grid...; names)
end

function Unitful.ustrip(grid::ParticlePositions)
    !hasunit(grid) && return grid
    grid_axes = collect(grid)
    u_grid = map.(ustrip, grid_axes)

    mins = ustrip.(minimum(grid))
    maxs = ustrip.(maximum(grid))
    names = propertynames(grid)

    return ParticlePositions(u_grid...; names, mins, maxs)
end


text:
using Dates

# Array:
todo1 = [1, "Getting groceries", false, Date("2022-04-01", "yyyy-mm-dd"), 5]
# 5-element Vector{Any}:
#      1
#       "Getting groceries"
#  false
#       2022-04-01
#      5

# Struct:
mutable struct ToDo
  id::Int32
  description::String
  completed::Bool
  created::Date
  priority::Int8
end

todo1 = ToDo(1, "Getting groceries", false, Date("2022-04-01", "yyyy-mm-dd"), 5)
# ToDo(1, "Getting groceries", false, Date("2022-04-01"), 5)

todo1.description
# "Getting groceries"
todo1.completed = true
# true
show(todo1)
display(todo1)

# Symbols:
sym = :info
# :info
typeof(sym)
# Symbol

# Functions:
increase_priority!(todo) = todo.priority += 1
todo1.priority          # 5
increase_priority!(todo1) # 6
todo1.priority            # 6

# increase_priority!("does this work?")
# ERROR: type String has no field priority

# Stacktrace:
# [1] getproperty
# @ .\Base.jl:42 [inlined]
# [2] increase_priority!(todo::String)
# @ Main .\REPL[55]:2
# [3] top-level scope
# @ REPL[56]:1


text:
using Images, MXNet

### LOADING THE MODEL
const MODEL_NAME = "weights/inception-v3/Inception-7"

nnet = mx.load_checkpoint(MODEL_NAME, 1, mx.FeedForward);

layers = mx.get_internals(nnet.arch);
layers_flatten = nothing
layers_to_remove = Symbol[]

for i = 1:2000

    layer = layers[i];
    layer_name = mx.get_name(layer)

    if layers_flatten == nothing && layer_name == :flatten
        layers_flatten = layer
    elseif layers_flatten != nothing
        push!(layers_to_remove, layer_name)
        if layer_name in [:softmax, :label] break end
    end
end

nnet.arch = layers_flatten
map(x -> delete!(nnet.arg_params, x), layers_to_remove);
map(x -> delete!(nnet.aux_params, x), layers_to_remove);

mx.save_checkpoint(nnet, "weights/inception-v3/InceptionV3-FE", mx.OptimizationState(1, 0, 0, 0))


text:
# Original Java version Copyright 2005 Google Inc.
# Julia translation Copyright 2022 Ted Dunning
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# This class represents a point on the unit sphere as a pair of latitude-longitude coordinates.

struct S2LatLng
    lat::Float64
    lng::Float64
end

S2LatLng(lat::S1Angle, lon::S1Angle) = S2LatLng(radians(lat), radians(lon))
S2LatLng(p::Vector) = verifyPoint(p) && S2LatLng(latitude(p), longitude(p))

radians2LL(lat::Number, lon::Number) = S2LatLng(lat, lon)
deg2LL(lat::Number, lon::Number) = S2LatLng(deg2rad(lat), deg2rad(lon))

latitude(p::Vector) = verifyPoint(p) && S1Angle(atan(p[3], hypot(p[1], p[2])))
latitude(p::S2LatLng) = S1Angle(p.lat)
longitude(p::Vector) = verifyPoint(p) && S1Angle(atan(p[2], p[1]))
longitude(p::S2LatLng) = S1Angle(p.lngRadians)

md"""
Returns a new S2LatLng based on this instance for which {@link #isValid()} will be {@code
true}.

* Latitude is clipped to the range {@code [-90, 90]}
* Longitude is normalized to be in the range {@code [-180, 180]}

f the current point is valid then the returned point will have the same coordinates.
"""
function LinearAlgebra.normalize(p::S2LatLng)::S2LatLng
    S2LatLng(max(-π, min(π, p.lat)),
             normalizeRange(p.lng))
end

function S2Point(ll::S2LatLng)
    ϕ = ll.lat
    θ = ll.lng
    cosphi = cos(ϕ)
    return S2Point(cos(θ) * cosphi, sin(θ) * cosphi, sin(ϕ))
end

md"""
Returns the distance (measured along the surface of the sphere) to the given point.

This code uses the Haversine formula which is very good for short distances but is
not as good for nearly antipodal points (but that only means errors of 10cm). An
alternative is to convert to S2Points and then to S1Angle to get 15 digits of accuracy
for all distances.
"""
function distance(a::S2LatLng, b::S2LatLng)
    dlat = Math.sin(0.5 * (a.lat - b.latRadians))
    dlng = Math.sin(0.5 * (a.lngRadians - b.lngRadians))
    x = dlat * dlat + dlng * dlng * cos(a.latRadians) * cos(b.latRadians)
    return S1Angle.radians(2 * asin(sqrt(min(1.0, x))))
end

md"Returns the surface distance to the given point assuming a constant radius."
distance(a::S2LatLng, b::S2LatLng, radius) = distance(distance(a, b), radius)

md"""
Adds the given point to this point. Note that there is no guarantee that the new point will be
valid.
"""
(+)(a::S2LatLng, b::S2LatLng) = S2LatLng(a.latRadians + b.latRadians, a.lngRadians + o.lngRadians)

md"""
Subtracts the given point from this point. Note that there is no guarantee that the new point
will be valid.
"""
(-)(a::S2LatLng, b::S2LatLng) = S2LatLng(a.latRadians - b.latRadians, a.lngRadians - b.lngRadians)

(*)(a::S2LatLng, m) = S2LatLng(a.latRadians * m, a.lngRadians * m)

equals(a::S2LatLng, b::S2LatLng) = (a.latRadians == b.latRadians) && (a.lngRadians == b.lngRadians)


text:
module Multithread

using Base.Threads
import Random
import Future

# thread-local seeds for rand()
function seed_per_thread() :: Vector{Random.MersenneTwister}
    m = Random.MersenneTwister(1)
    return [m; accumulate(Future.randjump,
                          fill(big(10)^20,
                          nthreads()-1),
                          init=m)]
end

# returns the number of simulations
# for the current thread
function thread_num_sims(total_num_sims::Integer)
    n = nthreads()
    dv = div(total_num_sims, n)
    md = mod(total_num_sims, n)

    if dv == 0
        # degenerates to single-threaded
        if threadid() == 1
            return total_num_sims
        else
            return 0
        end
    else
        if threadid() != n
            return dv
        else
            return dv + md
        end
    end
end

# checks if we're running Julia in multithread mode
function check_julia_num_threads()
    if nthreads() == 1
        error("Run `export JULIA_NUM_THREADS=n`, n > 1, before launching Julia.")
    end
end

# with threading
function run_multithread(num_sims::T) :: Float64 where {T<:Integer}
    check_julia_num_threads()
    @assert num_sims > 0

    local acum = Threads.Atomic{Int}(0)
    local check_num_sims = Threads.Atomic{T}(0)

    seeds = seed_per_thread()

    @threads for tid in 1:nthreads()
        @assert tid == threadid()

        thread_seed = seeds[threadid()]
        thread_acum = 0
        local_num_sims = thread_num_sims(num_sims)

        for sim in 1:local_num_sims

            x = rand(thread_seed)
            y = rand(thread_seed)

            r = sqrt(x^2 + y^2)

            if r <= 1.0
                thread_acum += 1
            end
        end

        Threads.atomic_add!(acum, thread_acum)
        Threads.atomic_add!(check_num_sims, local_num_sims)
    end

    @assert check_num_sims[] == num_sims

    area = acum[] / num_sims
    return 4*area
end

end # module Threaded


text:
using ARCSolver
using ImageView


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

"""
    abort_document_version_upload(document_id, version_id)
    abort_document_version_upload(document_id, version_id, params::Dict{String,<:Any})

Aborts the upload of the specified document version that was previously initiated by
InitiateDocumentVersionUpload. The client should make this call only when it no longer
intends to upload the document version, or fails to do so.

# Arguments
- `document_id`: The ID of the document.
- `version_id`: The ID of the version.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
"""
abort_document_version_upload(DocumentId, VersionId; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("DELETE", "/api/v1/documents/$(DocumentId)/versions/$(VersionId)"; aws_config=aws_config)
abort_document_version_upload(DocumentId, VersionId, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("DELETE", "/api/v1/documents/$(DocumentId)/versions/$(VersionId)", params; aws_config=aws_config)

"""
    activate_user(user_id)
    activate_user(user_id, params::Dict{String,<:Any})

Activates the specified user. Only active users can access Amazon WorkDocs.

# Arguments
- `user_id`: The ID of the user.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
"""
activate_user(UserId; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("POST", "/api/v1/users/$(UserId)/activation"; aws_config=aws_config)
activate_user(UserId, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("POST", "/api/v1/users/$(UserId)/activation", params; aws_config=aws_config)

"""
    add_resource_permissions(principals, resource_id)
    add_resource_permissions(principals, resource_id, params::Dict{String,<:Any})

Creates a set of permissions for the specified folder or document. The resource permissions
are overwritten if the principals already have different permissions.

# Arguments
- `principals`: The users, groups, or organization being granted permission.
- `resource_id`: The ID of the resource.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
- `"NotificationOptions"`: The notification options.
"""
add_resource_permissions(Principals, ResourceId; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("POST", "/api/v1/resources/$(ResourceId)/permissions", Dict{String, Any}("Principals"=>Principals); aws_config=aws_config)
add_resource_permissions(Principals, ResourceId, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("POST", "/api/v1/resources/$(ResourceId)/permissions", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Principals"=>Principals), params)); aws_config=aws_config)

"""
    create_comment(document_id, text, version_id)
    create_comment(document_id, text, version_id, params::Dict{String,<:Any})

Adds a new comment to the specified document version.

# Arguments
- `document_id`: The ID of the document.
- `text`: The text of the comment.
- `version_id`: The ID of the document version.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
- `"NotifyCollaborators"`: Set this parameter to TRUE to send an email out to the document
  collaborators after the comment is created.
- `"ParentId"`: The ID of the parent comment.
- `"ThreadId"`: The ID of the root comment in the thread.
- `"Visibility"`: The visibility of the comment. Options are either PRIVATE, where the
  comment is visible only to the comment author and document owner and co-owners, or PUBLIC,
  where the comment is visible to document owners, co-owners, and contributors.
"""
create_comment(DocumentId, Text, VersionId; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("POST", "/api/v1/documents/$(DocumentId)/versions/$(VersionId)/comment", Dict{String, Any}("Text"=>Text); aws_config=aws_config)
create_comment(DocumentId, Text, VersionId, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("POST", "/api/v1/documents/$(DocumentId)/versions/$(VersionId)/comment", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Text"=>Text), params)); aws_config=aws_config)

"""
    create_custom_metadata(custom_metadata, resource_id)
    create_custom_metadata(custom_metadata, resource_id, params::Dict{String,<:Any})

Adds one or more custom properties to the specified resource (a folder, document, or
version).

# Arguments
- `custom_metadata`: Custom metadata in the form of name-value pairs.
- `resource_id`: The ID of the resource.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
- `"versionid"`: The ID of the version, if the custom metadata is being added to a document
  version.
"""
create_custom_metadata(CustomMetadata, ResourceId; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("PUT", "/api/v1/resources/$(ResourceId)/customMetadata", Dict{String, Any}("CustomMetadata"=>CustomMetadata); aws_config=aws_config)
create_custom_metadata(CustomMetadata, ResourceId, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("PUT", "/api/v1/resources/$(ResourceId)/customMetadata", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("CustomMetadata"=>CustomMetadata), params)); aws_config=aws_config)

"""
    create_folder(parent_folder_id)
    create_folder(parent_folder_id, params::Dict{String,<:Any})

Creates a folder with the specified name and parent folder.

# Arguments
- `parent_folder_id`: The ID of the parent folder.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
- `"Name"`: The name of the new folder.
"""
create_folder(ParentFolderId; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("POST", "/api/v1/folders", Dict{String, Any}("ParentFolderId"=>ParentFolderId); aws_config=aws_config)
create_folder(ParentFolderId, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("POST", "/api/v1/folders", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ParentFolderId"=>ParentFolderId), params)); aws_config=aws_config)

"""
    create_labels(labels, resource_id)
    create_labels(labels, resource_id, params::Dict{String,<:Any})

Adds the specified list of labels to the given resource (a document or folder)

# Arguments
- `labels`: List of labels to add to the resource.
- `resource_id`: The ID of the resource.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
"""
create_labels(Labels, ResourceId; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("PUT", "/api/v1/resources/$(ResourceId)/labels", Dict{String, Any}("Labels"=>Labels); aws_config=aws_config)
create_labels(Labels, ResourceId, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("PUT", "/api/v1/resources/$(ResourceId)/labels", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Labels"=>Labels), params)); aws_config=aws_config)

"""
    create_notification_subscription(endpoint, organization_id, protocol, subscription_type)
    create_notification_subscription(endpoint, organization_id, protocol, subscription_type, params::Dict{String,<:Any})

Configure Amazon WorkDocs to use Amazon SNS notifications. The endpoint receives a
confirmation message, and must confirm the subscription. For more information, see
Subscribe to Notifications in the Amazon WorkDocs Developer Guide.

# Arguments
- `endpoint`: The endpoint to receive the notifications. If the protocol is HTTPS, the
  endpoint is a URL that begins with https.
- `organization_id`: The ID of the organization.
- `protocol`: The protocol to use. The supported value is https, which delivers
  JSON-encoded messages using HTTPS POST.
- `subscription_type`: The notification type.

"""
create_notification_subscription(Endpoint, OrganizationId, Protocol, SubscriptionType; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("POST", "/api/v1/organizations/$(OrganizationId)/subscriptions", Dict{String, Any}("Endpoint"=>Endpoint, "Protocol"=>Protocol, "SubscriptionType"=>SubscriptionType); aws_config=aws_config)
create_notification_subscription(Endpoint, OrganizationId, Protocol, SubscriptionType, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("POST", "/api/v1/organizations/$(OrganizationId)/subscriptions", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Endpoint"=>Endpoint, "Protocol"=>Protocol, "SubscriptionType"=>SubscriptionType), params)); aws_config=aws_config)

"""
    create_user(given_name, password, surname, username)
    create_user(given_name, password, surname, username, params::Dict{String,<:Any})

Creates a user in a Simple AD or Microsoft AD directory. The status of a newly created user
is \"ACTIVE\". New users can access Amazon WorkDocs.

# Arguments
- `given_name`: The given name of the user.
- `password`: The password of the user.
- `surname`: The surname of the user.
- `username`: The login name of the user.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
- `"EmailAddress"`: The email address of the user.
- `"OrganizationId"`: The ID of the organization.
- `"StorageRule"`: The amount of storage for the user.
- `"TimeZoneId"`: The time zone ID of the user.
"""
create_user(GivenName, Password, Surname, Username; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("POST", "/api/v1/users", Dict{String, Any}("GivenName"=>GivenName, "Password"=>Password, "Surname"=>Surname, "Username"=>Username); aws_config=aws_config)
create_user(GivenName, Password, Surname, Username, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("POST", "/api/v1/users", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("GivenName"=>GivenName, "Password"=>Password, "Surname"=>Surname, "Username"=>Username), params)); aws_config=aws_config)

"""
    deactivate_user(user_id)
    deactivate_user(user_id, params::Dict{String,<:Any})

Deactivates the specified user, which revokes the user's access to Amazon WorkDocs.

# Arguments
- `user_id`: The ID of the user.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
"""
deactivate_user(UserId; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("DELETE", "/api/v1/users/$(UserId)/activation"; aws_config=aws_config)
deactivate_user(UserId, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("DELETE", "/api/v1/users/$(UserId)/activation", params; aws_config=aws_config)

"""
    delete_comment(comment_id, document_id, version_id)
    delete_comment(comment_id, document_id, version_id, params::Dict{String,<:Any})

Deletes the specified comment from the document version.

# Arguments
- `comment_id`: The ID of the comment.
- `document_id`: The ID of the document.
- `version_id`: The ID of the document version.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
"""
delete_comment(CommentId, DocumentId, VersionId; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("DELETE", "/api/v1/documents/$(DocumentId)/versions/$(VersionId)/comment/$(CommentId)"; aws_config=aws_config)
delete_comment(CommentId, DocumentId, VersionId, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("DELETE", "/api/v1/documents/$(DocumentId)/versions/$(VersionId)/comment/$(CommentId)", params; aws_config=aws_config)

"""
    delete_custom_metadata(resource_id)
    delete_custom_metadata(resource_id, params::Dict{String,<:Any})

Deletes custom metadata from the specified resource.

# Arguments
- `resource_id`: The ID of the resource, either a document or folder.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
- `"deleteAll"`: Flag to indicate removal of all custom metadata properties from the
  specified resource.
- `"keys"`: List of properties to remove.
- `"versionId"`: The ID of the version, if the custom metadata is being deleted from a
  document version.
"""
delete_custom_metadata(ResourceId; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("DELETE", "/api/v1/resources/$(ResourceId)/customMetadata"; aws_config=aws_config)
delete_custom_metadata(ResourceId, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("DELETE", "/api/v1/resources/$(ResourceId)/customMetadata", params; aws_config=aws_config)

"""
    delete_document(document_id)
    delete_document(document_id, params::Dict{String,<:Any})

Permanently deletes the specified document and its associated metadata.

# Arguments
- `document_id`: The ID of the document.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
"""
delete_document(DocumentId; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("DELETE", "/api/v1/documents/$(DocumentId)"; aws_config=aws_config)
delete_document(DocumentId, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("DELETE", "/api/v1/documents/$(DocumentId)", params; aws_config=aws_config)

"""
    delete_folder(folder_id)
    delete_folder(folder_id, params::Dict{String,<:Any})

Permanently deletes the specified folder and its contents.

# Arguments
- `folder_id`: The ID of the folder.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
"""
delete_folder(FolderId; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("DELETE", "/api/v1/folders/$(FolderId)"; aws_config=aws_config)
delete_folder(FolderId, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("DELETE", "/api/v1/folders/$(FolderId)", params; aws_config=aws_config)

"""
    delete_folder_contents(folder_id)
    delete_folder_contents(folder_id, params::Dict{String,<:Any})

Deletes the contents of the specified folder.

# Arguments
- `folder_id`: The ID of the folder.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
"""
delete_folder_contents(FolderId; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("DELETE", "/api/v1/folders/$(FolderId)/contents"; aws_config=aws_config)
delete_folder_contents(FolderId, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("DELETE", "/api/v1/folders/$(FolderId)/contents", params; aws_config=aws_config)

"""
    delete_labels(resource_id)
    delete_labels(resource_id, params::Dict{String,<:Any})

Deletes the specified list of labels from a resource.

# Arguments
- `resource_id`: The ID of the resource.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
- `"deleteAll"`: Flag to request removal of all labels from the specified resource.
- `"labels"`: List of labels to delete from the resource.
"""
delete_labels(ResourceId; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("DELETE", "/api/v1/resources/$(ResourceId)/labels"; aws_config=aws_config)
delete_labels(ResourceId, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("DELETE", "/api/v1/resources/$(ResourceId)/labels", params; aws_config=aws_config)

"""
    delete_notification_subscription(organization_id, subscription_id)
    delete_notification_subscription(organization_id, subscription_id, params::Dict{String,<:Any})

Deletes the specified subscription from the specified organization.

# Arguments
- `organization_id`: The ID of the organization.
- `subscription_id`: The ID of the subscription.

"""
delete_notification_subscription(OrganizationId, SubscriptionId; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("DELETE", "/api/v1/organizations/$(OrganizationId)/subscriptions/$(SubscriptionId)"; aws_config=aws_config)
delete_notification_subscription(OrganizationId, SubscriptionId, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("DELETE", "/api/v1/organizations/$(OrganizationId)/subscriptions/$(SubscriptionId)", params; aws_config=aws_config)

"""
    delete_user(user_id)
    delete_user(user_id, params::Dict{String,<:Any})

Deletes the specified user from a Simple AD or Microsoft AD directory.

# Arguments
- `user_id`: The ID of the user.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Do not set this field when
  using administrative API actions, as in accessing the API using AWS credentials.
"""
delete_user(UserId; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("DELETE", "/api/v1/users/$(UserId)"; aws_config=aws_config)
delete_user(UserId, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("DELETE", "/api/v1/users/$(UserId)", params; aws_config=aws_config)

"""
    describe_activities()
    describe_activities(params::Dict{String,<:Any})

Describes the user activities in a specified time period.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
- `"activityTypes"`: Specifies which activity types to include in the response. If this
  field is left empty, all activity types are returned.
- `"endTime"`: The timestamp that determines the end time of the activities. The response
  includes the activities performed before the specified timestamp.
- `"includeIndirectActivities"`: Includes indirect activities. An indirect activity results
  from a direct activity performed on a parent resource. For example, sharing a parent folder
  (the direct activity) shares all of the subfolders and documents within the parent folder
  (the indirect activity).
- `"limit"`: The maximum number of items to return.
- `"marker"`: The marker for the next set of results.
- `"organizationId"`: The ID of the organization. This is a mandatory parameter when using
  administrative API (SigV4) requests.
- `"resourceId"`: The document or folder ID for which to describe activity types.
- `"startTime"`: The timestamp that determines the starting time of the activities. The
  response includes the activities performed after the specified timestamp.
- `"userId"`: The ID of the user who performed the action. The response includes activities
  pertaining to this user. This is an optional parameter and is only applicable for
  administrative API (SigV4) requests.
"""
describe_activities(; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("GET", "/api/v1/activities"; aws_config=aws_config)
describe_activities(params::AbstractDict{String, Any}; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("GET", "/api/v1/activities", params; aws_config=aws_config)

"""
    describe_comments(document_id, version_id)
    describe_comments(document_id, version_id, params::Dict{String,<:Any})

List all the comments for the specified document version.

# Arguments
- `document_id`: The ID of the document.
- `version_id`: The ID of the document version.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
- `"limit"`: The maximum number of items to return.
- `"marker"`: The marker for the next set of results. This marker was received from a
  previous call.
"""
describe_comments(DocumentId, VersionId; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("GET", "/api/v1/documents/$(DocumentId)/versions/$(VersionId)/comments"; aws_config=aws_config)
describe_comments(DocumentId, VersionId, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("GET", "/api/v1/documents/$(DocumentId)/versions/$(VersionId)/comments", params; aws_config=aws_config)

"""
    describe_document_versions(document_id)
    describe_document_versions(document_id, params::Dict{String,<:Any})

Retrieves the document versions for the specified document. By default, only active
versions are returned.

# Arguments
- `document_id`: The ID of the document.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
- `"fields"`: Specify \"SOURCE\" to include initialized versions and a URL for the source
  document.
- `"include"`: A comma-separated list of values. Specify \"INITIALIZED\" to include
  incomplete versions.
- `"limit"`: The maximum number of versions to return with this call.
- `"marker"`: The marker for the next set of results. (You received this marker from a
  previous call.)
"""
describe_document_versions(DocumentId; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("GET", "/api/v1/documents/$(DocumentId)/versions"; aws_config=aws_config)
describe_document_versions(DocumentId, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("GET", "/api/v1/documents/$(DocumentId)/versions", params; aws_config=aws_config)

"""
    describe_folder_contents(folder_id)
    describe_folder_contents(folder_id, params::Dict{String,<:Any})

Describes the contents of the specified folder, including its documents and subfolders. By
default, Amazon WorkDocs returns the first 100 active document and folder metadata items.
If there are more results, the response includes a marker that you can use to request the
next set of results. You can also request initialized documents.

# Arguments
- `folder_id`: The ID of the folder.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
- `"include"`: The contents to include. Specify \"INITIALIZED\" to include initialized
  documents.
- `"limit"`: The maximum number of items to return with this call.
- `"marker"`: The marker for the next set of results. This marker was received from a
  previous call.
- `"order"`: The order for the contents of the folder.
- `"sort"`: The sorting criteria.
- `"type"`: The type of items.
"""
describe_folder_contents(FolderId; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("GET", "/api/v1/folders/$(FolderId)/contents"; aws_config=aws_config)
describe_folder_contents(FolderId, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("GET", "/api/v1/folders/$(FolderId)/contents", params; aws_config=aws_config)

"""
    describe_groups(search_query)
    describe_groups(search_query, params::Dict{String,<:Any})

Describes the groups specified by the query. Groups are defined by the underlying Active
Directory.

# Arguments
- `search_query`: A query to describe groups by group name.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
- `"limit"`: The maximum number of items to return with this call.
- `"marker"`: The marker for the next set of results. (You received this marker from a
  previous call.)
- `"organizationId"`: The ID of the organization.
"""
describe_groups(searchQuery; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("GET", "/api/v1/groups", Dict{String, Any}("searchQuery"=>searchQuery); aws_config=aws_config)
describe_groups(searchQuery, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("GET", "/api/v1/groups", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("searchQuery"=>searchQuery), params)); aws_config=aws_config)

"""
    describe_notification_subscriptions(organization_id)
    describe_notification_subscriptions(organization_id, params::Dict{String,<:Any})

Lists the specified notification subscriptions.

# Arguments
- `organization_id`: The ID of the organization.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"limit"`: The maximum number of items to return with this call.
- `"marker"`: The marker for the next set of results. (You received this marker from a
  previous call.)
"""
describe_notification_subscriptions(OrganizationId; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("GET", "/api/v1/organizations/$(OrganizationId)/subscriptions"; aws_config=aws_config)
describe_notification_subscriptions(OrganizationId, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("GET", "/api/v1/organizations/$(OrganizationId)/subscriptions", params; aws_config=aws_config)

"""
    describe_resource_permissions(resource_id)
    describe_resource_permissions(resource_id, params::Dict{String,<:Any})

Describes the permissions of a specified resource.

# Arguments
- `resource_id`: The ID of the resource.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
- `"limit"`: The maximum number of items to return with this call.
- `"marker"`: The marker for the next set of results. (You received this marker from a
  previous call)
- `"principalId"`: The ID of the principal to filter permissions by.
"""
describe_resource_permissions(ResourceId; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("GET", "/api/v1/resources/$(ResourceId)/permissions"; aws_config=aws_config)
describe_resource_permissions(ResourceId, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("GET", "/api/v1/resources/$(ResourceId)/permissions", params; aws_config=aws_config)

"""
    describe_root_folders(authentication)
    describe_root_folders(authentication, params::Dict{String,<:Any})

Describes the current user's special folders; the RootFolder and the RecycleBin. RootFolder
is the root of user's files and folders and RecycleBin is the root of recycled items. This
is not a valid action for SigV4 (administrative API) clients. This action requires an
authentication token. To get an authentication token, register an application with Amazon
WorkDocs. For more information, see Authentication and Access Control for User Applications
in the Amazon WorkDocs Developer Guide.

# Arguments
- `authentication`: Amazon WorkDocs authentication token.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"limit"`: The maximum number of items to return.
- `"marker"`: The marker for the next set of results. (You received this marker from a
  previous call.)
"""
describe_root_folders(Authentication; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("GET", "/api/v1/me/root", Dict{String, Any}("headers"=>Dict{String, Any}("Authentication"=>Authentication)); aws_config=aws_config)
describe_root_folders(Authentication, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("GET", "/api/v1/me/root", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("headers"=>Dict{String, Any}("Authentication"=>Authentication)), params)); aws_config=aws_config)

"""
    describe_users()
    describe_users(params::Dict{String,<:Any})

Describes the specified users. You can describe all users or filter the results (for
example, by status or organization). By default, Amazon WorkDocs returns the first 24
active or pending users. If there are more results, the response includes a marker that you
can use to request the next set of results.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
- `"fields"`: A comma-separated list of values. Specify \"STORAGE_METADATA\" to include the
  user storage quota and utilization information.
- `"include"`: The state of the users. Specify \"ALL\" to include inactive users.
- `"limit"`: The maximum number of items to return.
- `"marker"`: The marker for the next set of results. (You received this marker from a
  previous call.)
- `"order"`: The order for the results.
- `"organizationId"`: The ID of the organization.
- `"query"`: A query to filter users by user name.
- `"sort"`: The sorting criteria.
- `"userIds"`: The IDs of the users.
"""
describe_users(; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("GET", "/api/v1/users"; aws_config=aws_config)
describe_users(params::AbstractDict{String, Any}; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("GET", "/api/v1/users", params; aws_config=aws_config)

"""
    get_current_user(authentication)
    get_current_user(authentication, params::Dict{String,<:Any})

Retrieves details of the current user for whom the authentication token was generated. This
is not a valid action for SigV4 (administrative API) clients. This action requires an
authentication token. To get an authentication token, register an application with Amazon
WorkDocs. For more information, see Authentication and Access Control for User Applications
in the Amazon WorkDocs Developer Guide.

# Arguments
- `authentication`: Amazon WorkDocs authentication token.

"""
get_current_user(Authentication; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("GET", "/api/v1/me", Dict{String, Any}("headers"=>Dict{String, Any}("Authentication"=>Authentication)); aws_config=aws_config)
get_current_user(Authentication, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("GET", "/api/v1/me", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("headers"=>Dict{String, Any}("Authentication"=>Authentication)), params)); aws_config=aws_config)

"""
    get_document(document_id)
    get_document(document_id, params::Dict{String,<:Any})

Retrieves details of a document.

# Arguments
- `document_id`: The ID of the document.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
- `"includeCustomMetadata"`: Set this to TRUE to include custom metadata in the response.
"""
get_document(DocumentId; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("GET", "/api/v1/documents/$(DocumentId)"; aws_config=aws_config)
get_document(DocumentId, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("GET", "/api/v1/documents/$(DocumentId)", params; aws_config=aws_config)

"""
    get_document_path(document_id)
    get_document_path(document_id, params::Dict{String,<:Any})

Retrieves the path information (the hierarchy from the root folder) for the requested
document. By default, Amazon WorkDocs returns a maximum of 100 levels upwards from the
requested document and only includes the IDs of the parent folders in the path. You can
limit the maximum number of levels. You can also request the names of the parent folders.

# Arguments
- `document_id`: The ID of the document.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
- `"fields"`: A comma-separated list of values. Specify NAME to include the names of the
  parent folders.
- `"limit"`: The maximum number of levels in the hierarchy to return.
- `"marker"`: This value is not supported.
"""
get_document_path(DocumentId; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("GET", "/api/v1/documents/$(DocumentId)/path"; aws_config=aws_config)
get_document_path(DocumentId, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("GET", "/api/v1/documents/$(DocumentId)/path", params; aws_config=aws_config)

"""
    get_document_version(document_id, version_id)
    get_document_version(document_id, version_id, params::Dict{String,<:Any})

Retrieves version metadata for the specified document.

# Arguments
- `document_id`: The ID of the document.
- `version_id`: The version ID of the document.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
- `"fields"`: A comma-separated list of values. Specify \"SOURCE\" to include a URL for the
  source document.
- `"includeCustomMetadata"`: Set this to TRUE to include custom metadata in the response.
"""
get_document_version(DocumentId, VersionId; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("GET", "/api/v1/documents/$(DocumentId)/versions/$(VersionId)"; aws_config=aws_config)
get_document_version(DocumentId, VersionId, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("GET", "/api/v1/documents/$(DocumentId)/versions/$(VersionId)", params; aws_config=aws_config)

"""
    get_folder(folder_id)
    get_folder(folder_id, params::Dict{String,<:Any})

Retrieves the metadata of the specified folder.

# Arguments
- `folder_id`: The ID of the folder.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
- `"includeCustomMetadata"`: Set to TRUE to include custom metadata in the response.
"""
get_folder(FolderId; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("GET", "/api/v1/folders/$(FolderId)"; aws_config=aws_config)
get_folder(FolderId, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("GET", "/api/v1/folders/$(FolderId)", params; aws_config=aws_config)

"""
    get_folder_path(folder_id)
    get_folder_path(folder_id, params::Dict{String,<:Any})

Retrieves the path information (the hierarchy from the root folder) for the specified
folder. By default, Amazon WorkDocs returns a maximum of 100 levels upwards from the
requested folder and only includes the IDs of the parent folders in the path. You can limit
the maximum number of levels. You can also request the parent folder names.

# Arguments
- `folder_id`: The ID of the folder.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
- `"fields"`: A comma-separated list of values. Specify \"NAME\" to include the names of
  the parent folders.
- `"limit"`: The maximum number of levels in the hierarchy to return.
- `"marker"`: This value is not supported.
"""
get_folder_path(FolderId; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("GET", "/api/v1/folders/$(FolderId)/path"; aws_config=aws_config)
get_folder_path(FolderId, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("GET", "/api/v1/folders/$(FolderId)/path", params; aws_config=aws_config)

"""
    get_resources()
    get_resources(params::Dict{String,<:Any})

Retrieves a collection of resources, including folders and documents. The only
CollectionType supported is SHARED_WITH_ME.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: The Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
- `"collectionType"`: The collection type.
- `"limit"`: The maximum number of resources to return.
- `"marker"`: The marker for the next set of results. This marker was received from a
  previous call.
- `"userId"`: The user ID for the resource collection. This is a required field for
  accessing the API operation using IAM credentials.
"""
get_resources(; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("GET", "/api/v1/resources"; aws_config=aws_config)
get_resources(params::AbstractDict{String, Any}; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("GET", "/api/v1/resources", params; aws_config=aws_config)

"""
    initiate_document_version_upload(parent_folder_id)
    initiate_document_version_upload(parent_folder_id, params::Dict{String,<:Any})

Creates a new document object and version object. The client specifies the parent folder ID
and name of the document to upload. The ID is optionally specified when creating a new
version of an existing document. This is the first step to upload a document. Next, upload
the document to the URL returned from the call, and then call UpdateDocumentVersion. To
cancel the document upload, call AbortDocumentVersionUpload.

# Arguments
- `parent_folder_id`: The ID of the parent folder.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
- `"ContentCreatedTimestamp"`: The timestamp when the content of the document was
  originally created.
- `"ContentModifiedTimestamp"`: The timestamp when the content of the document was modified.
- `"ContentType"`: The content type of the document.
- `"DocumentSizeInBytes"`: The size of the document, in bytes.
- `"Id"`: The ID of the document.
- `"Name"`: The name of the document.
"""
initiate_document_version_upload(ParentFolderId; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("POST", "/api/v1/documents", Dict{String, Any}("ParentFolderId"=>ParentFolderId); aws_config=aws_config)
initiate_document_version_upload(ParentFolderId, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("POST", "/api/v1/documents", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ParentFolderId"=>ParentFolderId), params)); aws_config=aws_config)

"""
    remove_all_resource_permissions(resource_id)
    remove_all_resource_permissions(resource_id, params::Dict{String,<:Any})

Removes all the permissions from the specified resource.

# Arguments
- `resource_id`: The ID of the resource.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
"""
remove_all_resource_permissions(ResourceId; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("DELETE", "/api/v1/resources/$(ResourceId)/permissions"; aws_config=aws_config)
remove_all_resource_permissions(ResourceId, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("DELETE", "/api/v1/resources/$(ResourceId)/permissions", params; aws_config=aws_config)

"""
    remove_resource_permission(principal_id, resource_id)
    remove_resource_permission(principal_id, resource_id, params::Dict{String,<:Any})

Removes the permission for the specified principal from the specified resource.

# Arguments
- `principal_id`: The principal ID of the resource.
- `resource_id`: The ID of the resource.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
- `"type"`: The principal type of the resource.
"""
remove_resource_permission(PrincipalId, ResourceId; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("DELETE", "/api/v1/resources/$(ResourceId)/permissions/$(PrincipalId)"; aws_config=aws_config)
remove_resource_permission(PrincipalId, ResourceId, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("DELETE", "/api/v1/resources/$(ResourceId)/permissions/$(PrincipalId)", params; aws_config=aws_config)

"""
    update_document(document_id)
    update_document(document_id, params::Dict{String,<:Any})

Updates the specified attributes of a document. The user must have access to both the
document and its parent folder, if applicable.

# Arguments
- `document_id`: The ID of the document.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
- `"Name"`: The name of the document.
- `"ParentFolderId"`: The ID of the parent folder.
- `"ResourceState"`: The resource state of the document. Only ACTIVE and RECYCLED are
  supported.
"""
update_document(DocumentId; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("PATCH", "/api/v1/documents/$(DocumentId)"; aws_config=aws_config)
update_document(DocumentId, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("PATCH", "/api/v1/documents/$(DocumentId)", params; aws_config=aws_config)

"""
    update_document_version(document_id, version_id)
    update_document_version(document_id, version_id, params::Dict{String,<:Any})

Changes the status of the document version to ACTIVE.  Amazon WorkDocs also sets its
document container to ACTIVE. This is the last step in a document upload, after the client
uploads the document to an S3-presigned URL returned by InitiateDocumentVersionUpload.

# Arguments
- `document_id`: The ID of the document.
- `version_id`: The version ID of the document.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
- `"VersionStatus"`: The status of the version.
"""
update_document_version(DocumentId, VersionId; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("PATCH", "/api/v1/documents/$(DocumentId)/versions/$(VersionId)"; aws_config=aws_config)
update_document_version(DocumentId, VersionId, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("PATCH", "/api/v1/documents/$(DocumentId)/versions/$(VersionId)", params; aws_config=aws_config)

"""
    update_folder(folder_id)
    update_folder(folder_id, params::Dict{String,<:Any})

Updates the specified attributes of the specified folder. The user must have access to both
the folder and its parent folder, if applicable.

# Arguments
- `folder_id`: The ID of the folder.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
- `"Name"`: The name of the folder.
- `"ParentFolderId"`: The ID of the parent folder.
- `"ResourceState"`: The resource state of the folder. Only ACTIVE and RECYCLED are
  accepted values from the API.
"""
update_folder(FolderId; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("PATCH", "/api/v1/folders/$(FolderId)"; aws_config=aws_config)
update_folder(FolderId, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("PATCH", "/api/v1/folders/$(FolderId)", params; aws_config=aws_config)

"""
    update_user(user_id)
    update_user(user_id, params::Dict{String,<:Any})

Updates the specified attributes of the specified user, and grants or revokes
administrative privileges to the Amazon WorkDocs site.

# Arguments
- `user_id`: The ID of the user.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
- `"GivenName"`: The given name of the user.
- `"GrantPoweruserPrivileges"`: Boolean value to determine whether the user is granted
  Poweruser privileges.
- `"Locale"`: The locale of the user.
- `"StorageRule"`: The amount of storage for the user.
- `"Surname"`: The surname of the user.
- `"TimeZoneId"`: The time zone ID of the user.
- `"Type"`: The type of the user.
"""
update_user(UserId; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("PATCH", "/api/v1/users/$(UserId)"; aws_config=aws_config)
update_user(UserId, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = workdocs("PATCH", "/api/v1/users/$(UserId)", params; aws_config=aws_config)


text:
"""
    plotplanmaster(plan::DataFrame;schedulcolumn::Int=6)

# 処理概要
スケジュール調整した結果をグラフに出力
* 注意：グラフ描画エンジンの指定が必要。詳細はパッケージ：Plotsの利用方法を参照

# 引数
* `plan`:adjustedresultcheckの実行結果を指定
* `schedulcolumn`:スケジュールON,OFF開始列を指定（デフォルト：６）

# 結果（戻り値）
グラフ出力
"""
function plotplanmaster(plan::DataFrame;schedulcolumn::Int=6)
  xs = map(String,names(plan)[schedulcolumn:end] )
  ys = map(String,plan[:,:jobname])

  plot=Plots.heatmap(xs, ys, convert(Matrix,plan[:,schedulcolumn:end]), legend=false,c=cgrad([:white,:blue]))

  return plot

end

"""
    plotplangr(plan::DataFrame;schedulcolumn::Int=6)

# 処理概要
スケジュール調整した結果をGRを使ってグラフに出力

# 引数
* `plan`:adjustedresultcheckの実行結果を指定
* `schedulcolumn`:スケジュールON,OFF開始列を指定（デフォルト：６）

# 結果（戻り値）
* グラフ出力
"""
function plotplangr(plan::DataFrame;schedulcolumn::Int=6)
  ENV["GKS_ENCODING"]="utf-8"
  gr()

  plot=plotplanmaster(plan,schedulcolumn=schedulcolumn)
  gui(plot)
  return plot
end

"""
    plotplanplotlyjs(plan::DataFrame;schedulcolumn::Int=6)

# 処理概要
スケジュール調整した結果をPlotlyJSを使ってグラフに出力

# 引数
* `plan`:adjustedresultcheckの実行結果を指定
* `schedulcolumn`:スケジュールON,OFF開始列を指定（デフォルト：６）

# 結果（戻り値）
* グラフ出力
"""
function plotplanplotlyjs(plan::DataFrame;schedulcolumn::Int=6)
  plotlyjs()

  plot=plotplanmaster(plan,schedulcolumn=schedulcolumn)
  gui(plot)
  return plot
end

"""
    exportplan(plan::DataFrame;ExcelFilePath::String="")

# 処理概要
スケジュール調整した結果をExcelファイルに出力

# 引数
* `plan`:adjustedresultcheckの実行結果を指定
* `ExcelFilePath`:出力ファイル名をフルパスで記載。指定しない場合は、カレントディレクトリ（フォルダ）に"UiPathOrchestratorJobSchedulingPlan.xlsx"名で出力
"""
function exportplan(plan::DataFrame;ExcelFilePath::String="")
  if(ExcelFilePath=="")
    ExcelFilePath="UiPathOrchestratorJobSchedulingPlan.xlsx"
  end

 XLSX.writetable(ExcelFilePath, REPORT_jobplan=( collect(DataFrames.eachcol(plan)), DataFrames.names(plan) )  )
end

"""
    exportplan(plan::DataFrame,robotn::Int,run_unit_time::Int;ExcelFilePath::String="")

# 処理概要
スケジュール調整した結果をExcelファイルに出力

# 引数
* `plan`:adjustedresultcheckの実行結果を指定
* `robotn`:
* `run_unit_time`:
* `ExcelFilePath`:出力ファイル名をフルパスで記載。指定しない場合は、カレントディレクトリ（フォルダ）に"UiPathOrchestratorJobSchedulingPlan.xlsx"名で出力
"""
function exportplan(plan::DataFrame,robotn::Int,run_unit_time::Int;ExcelFilePath::String="")
  if(ExcelFilePath=="")
    ExcelFilePath="UiPathOrchestratorJobSchedulingPlan.xlsx"
  end

  parameters=DataFrame(parameter=["run_unit_time","all_run_robot"],Int=[run_unit_time,robotn],unit=["min",""],説明=["スケジュール実行単位","割り当て可能ロボット総数"])

  XLSX.writetable(ExcelFilePath, REPORT_parameters=( collect(DataFrames.eachcol(parameters)), DataFrames.names(parameters) ) ,REPORT_jobplan=( collect(DataFrames.eachcol(plan)), DataFrames.names(plan) )  )
end


text:
module BrainFlow

include("errors.jl")
include("brainflow_url.jl")
include("c_interfaces.jl")
include("brainflow_logs.jl")
include("board_shim.jl")
include("data_filter.jl")
include("ml_model.jl")

end # module


text:
@defcomp AbatementCostParameters begin

    region = Index()
    y_year = Parameter(index=[time], unit="year")
    y_year_0 = Parameter(unit="year", default = 2008.)

    #gas inputs
    emit_UncertaintyinBAUEmissFactorinFocusRegioninFinalYear = Parameter(unit="%")
    q0propinit_CutbacksinNegativeCostinFocusRegioninBaseYear = Parameter(unit="% of BAU emissions")
    c0init_MostNegativeCostCutbackinBaseYear = Parameter(unit="\$/ton")
    qmaxminusq0propinit_MaxCutbackCostatPositiveCostinBaseYear = Parameter(unit="% of BAU emissions")
    cmaxinit_MaximumCutbackCostinFocusRegioninBaseYear = Parameter(unit="\$/ton")
    ies_InitialExperienceStockofCutbacks = Parameter(unit= "Million ton")
    e0_baselineemissions = Parameter(index=[region], unit= "Mtonne/year")

    #regional inputs
    emitf_uncertaintyinBAUemissfactor = Parameter(index=[region], unit= "none")
    q0f_negativecostpercentagefactor = Parameter(index=[region], unit="none")
    cmaxf_maxcostfactor = Parameter(index=[region], unit="none")

    bau_businessasusualemissions = Parameter(index=[time, region], unit = "%")
    yagg = Parameter(index=[time], unit="year") # from equity weighting

    #inputs with single, uncertain values
    q0propmult_cutbacksatnegativecostinfinalyear = Parameter(unit="none", default=.733333333333333334)
    qmax_minus_q0propmult_maxcutbacksatpositivecostinfinalyear = Parameter(unit="none", default=1.2666666666666666)
    c0mult_mostnegativecostinfinalyear = Parameter(unit="none", default=.8333333333333334)
    curve_below_curvatureofMACcurvebelowzerocost = Parameter(unit="none", default=.5)
    curve_above_curvatureofMACcurveabovezerocost = Parameter(unit="none", default=.4)
    cross_experiencecrossoverratio = Parameter(unit="none", default=.2)
    learn_learningrate = Parameter(unit="none", default=.2)
    automult_autonomoustechchange = Parameter(unit="none", default=.65)
    equity_prop_equityweightsproportion = Parameter(unit="none", default=1.)

    # Inputs from other components
    cbe_absoluteemissionreductions = Parameter(index=[time, region], unit="Mtonne") #TODO: default here?

    #Variables
    emit_UncertaintyinBAUEmissFactor = Variable(index=[region], unit = "%")
    q0propinit_CutbacksinNegativeCostinBaseYear = Variable(index=[region], unit= "% of BAU emissions")
    cmaxinit_MaxCutbackCostinBaseYear = Variable(index=[region], unit = "\$/ton")
    zc_zerocostemissions = Variable(index=[time, region], unit= "%")
    cumcbe_cumulativereductionssincebaseyear = Variable(index=[time, region], unit="Mtonne")
    cumcbe_g_totalreductions = Variable(index=[time], unit="Mtonne")
    learnfac_learning= Variable(index=[time, region], unit= "none")
    auto = Variable(unit="% per year")
    autofac = Variable(index=[time], unit= "% per year")
    c0g = Variable(unit= "% per year")
    c0 = Variable(index=[time], unit= "\$/ton")
    qmaxminusq0propg = Variable(unit= "% per year")
    qmaxminusq0prop = Variable(unit = "% of BAU emissions")
    q0propg = Variable(unit = "% per year")
    q0prop = Variable(index=[time, region], unit="% of BAU emissions")
    q0_absolutecutbacksatnegativecost = Variable(index=[time, region], unit= "Mtonne")
    qmax_maxreferencereductions = Variable(index=[time, region], unit="Mtonne")
    cmax = Variable(index=[time,region], unit = "\$/tonne")
    blo = Variable(index=[time, region], unit = "per Mtonne")
    alo = Variable(index=[time, region], unit = "\$/tonne")
    bhi = Variable(index=[time, region], unit = "per Mtonne")
    ahi = Variable(index=[time, region], unit = "\$/tonne")
    mc_marginalcost = Variable(index=[time, region], unit = "\$/tonne")
    tcq0 = Variable(index=[time, region], unit = "\$million")
    tc_totalcost = Variable(index=[time, region], unit= "\$million")

    function run_timestep(p, v, d, t)

        for r in d.region
            v.emit_UncertaintyinBAUEmissFactor[r] = p.emit_UncertaintyinBAUEmissFactorinFocusRegioninFinalYear *
                p.emitf_uncertaintyinBAUemissfactor[r]
            v.q0propinit_CutbacksinNegativeCostinBaseYear[r] = p.q0propinit_CutbacksinNegativeCostinFocusRegioninBaseYear *
                p.q0f_negativecostpercentagefactor[r]
            v.cmaxinit_MaxCutbackCostinBaseYear[r] = p.cmaxinit_MaximumCutbackCostinFocusRegioninBaseYear *
                p.cmaxf_maxcostfactor[r]

            v.zc_zerocostemissions[t,r] = (1+v.emit_UncertaintyinBAUEmissFactor[r]/100 * (p.y_year[t]-p.y_year_0)/(p.y_year[end]-p.y_year_0)) * p.bau_businessasusualemissions[t,r]

            if is_first(t)
                v.cumcbe_cumulativereductionssincebaseyear[t,r] = 0.
            else
                v.cumcbe_cumulativereductionssincebaseyear[t,r] = v.cumcbe_cumulativereductionssincebaseyear[t-1, r] + p.cbe_absoluteemissionreductions[t-1, r] * p.yagg[t-1]
            end
        end

        v.cumcbe_g_totalreductions[t] = sum(v.cumcbe_cumulativereductionssincebaseyear[t,:])

        v.auto = (1-p.automult_autonomoustechchange^(1/(p.y_year[end]-p.y_year_0)))*100
        v.autofac[t] = (1-v.auto/100)^(p.y_year[t] - p.y_year_0)

        v.c0g = (p.c0mult_mostnegativecostinfinalyear^(1/(p.y_year[end]-p.y_year_0))-1)*100
        v.c0[t] = p.c0init_MostNegativeCostCutbackinBaseYear* (1+v.c0g/100)^(p.y_year[t]-p.y_year_0)

        v.qmaxminusq0propg = (p.qmax_minus_q0propmult_maxcutbacksatpositivecostinfinalyear ^(1/(p.y_year[end]-p.y_year_0))- 1)* 100
        v.qmaxminusq0prop = p.qmaxminusq0propinit_MaxCutbackCostatPositiveCostinBaseYear * (1+ v.qmaxminusq0propg/100)^(p.y_year[t]-p.y_year_0)

        v.q0propg = (p.q0propmult_cutbacksatnegativecostinfinalyear^(1/(p.y_year[end]-p.y_year_0))-1)*100

        for r in d.region
            v.learnfac_learning[t,r] = ((p.cross_experiencecrossoverratio *v.cumcbe_g_totalreductions[t]+ (1-p.cross_experiencecrossoverratio)*v.cumcbe_cumulativereductionssincebaseyear[t,r] + p.ies_InitialExperienceStockofCutbacks)/ p.ies_InitialExperienceStockofCutbacks)^ -(log(1/(1-p.learn_learningrate))/log(2))

            v.q0prop[t,r] = v.q0propinit_CutbacksinNegativeCostinBaseYear[r]* (1+v.q0propg/100)^(p.y_year[t]-p.y_year_0)

            v.q0_absolutecutbacksatnegativecost[t,r]= (v.q0prop[t,r]/100)* (v.zc_zerocostemissions[t,r]/100) * p.e0_baselineemissions[r]

            v.qmax_maxreferencereductions[t,r] = (v.qmaxminusq0prop/100) * (v.zc_zerocostemissions[t,r]/100)* p.e0_baselineemissions[r] + v.q0_absolutecutbacksatnegativecost[t,r]

            v.cmax[t,r] = v.cmaxinit_MaxCutbackCostinBaseYear[r] * v.learnfac_learning[t,r]* v.autofac[t]

            v.blo[t,r] = -2*log((1+p.curve_below_curvatureofMACcurvebelowzerocost)/(1-p.curve_below_curvatureofMACcurvebelowzerocost))/ v.q0_absolutecutbacksatnegativecost[t,r]
            v.alo[t,r] = v.c0[t]/(exp(-v.blo[t,r]*v.q0_absolutecutbacksatnegativecost[t,r])-1)
            v.bhi[t,r] = 2*log((1+p.curve_above_curvatureofMACcurveabovezerocost)/(1-p.curve_above_curvatureofMACcurveabovezerocost))/ (v.qmax_maxreferencereductions[t,r] - v.q0_absolutecutbacksatnegativecost[t,r])
            v.ahi[t,r] = v.cmax[t,r]/ (exp(v.bhi[t,r]*(v.qmax_maxreferencereductions[t,r]-v.q0_absolutecutbacksatnegativecost[t,r]))-1)
        end
    end
end

function addabatementcostparameters(model::Model, class::Symbol, policy::String="policy-a")
    componentname = Symbol("AbatementCostParameters$class")
    abatementcostscomp = add_comp!(model, AbatementCostParameters, componentname)

    abatementcostscomp[:q0propmult_cutbacksatnegativecostinfinalyear] = .733333333333333334
    abatementcostscomp[:qmax_minus_q0propmult_maxcutbacksatpositivecostinfinalyear] = 1.2666666666666666
    abatementcostscomp[:c0mult_mostnegativecostinfinalyear] = .8333333333333334
    abatementcostscomp[:curve_below_curvatureofMACcurvebelowzerocost] = .5
    abatementcostscomp[:curve_above_curvatureofMACcurveabovezerocost] = .4
    abatementcostscomp[:cross_experiencecrossoverratio] = .2
    abatementcostscomp[:learn_learningrate] = .2
    abatementcostscomp[:automult_autonomoustechchange] = .65
    abatementcostscomp[:equity_prop_equityweightsproportion] = 1.
    abatementcostscomp[:y_year_0] = 2008.

    if class == :CO2
        setdistinctparameter(model, componentname, :emit_UncertaintyinBAUEmissFactorinFocusRegioninFinalYear, 8.333333333333334)
        setdistinctparameter(model, componentname, :q0propinit_CutbacksinNegativeCostinFocusRegioninBaseYear, 20.)
        setdistinctparameter(model, componentname, :c0init_MostNegativeCostCutbackinBaseYear, -233.333333333333)
        setdistinctparameter(model, componentname, :qmaxminusq0propinit_MaxCutbackCostatPositiveCostinBaseYear, 70.)
        setdistinctparameter(model, componentname, :cmaxinit_MaximumCutbackCostinFocusRegioninBaseYear, 400.)
        setdistinctparameter(model, componentname, :ies_InitialExperienceStockofCutbacks, 150000.)
        setdistinctparameter(model, componentname, :e0_baselineemissions, readpagedata(model, "data/e0_baselineCO2emissions.csv"))
        setdistinctparameter(model, componentname, :bau_businessasusualemissions, readpagedata(model, "data/bau_co2emissions.csv"))
    elseif class == :CH4
        setdistinctparameter(model, componentname, :emit_UncertaintyinBAUEmissFactorinFocusRegioninFinalYear, 25.)
        setdistinctparameter(model, componentname, :q0propinit_CutbacksinNegativeCostinFocusRegioninBaseYear, 10.)
        setdistinctparameter(model, componentname, :c0init_MostNegativeCostCutbackinBaseYear, -4333.3333333333333)
        setdistinctparameter(model, componentname, :qmaxminusq0propinit_MaxCutbackCostatPositiveCostinBaseYear, 51.66666666666666664)
        setdistinctparameter(model, componentname, :cmaxinit_MaximumCutbackCostinFocusRegioninBaseYear, 6333.33333333333)
        setdistinctparameter(model, componentname, :ies_InitialExperienceStockofCutbacks, 2000.)
        setdistinctparameter(model, componentname, :e0_baselineemissions, readpagedata(model, "data/e0_baselineCH4emissions.csv"))
        setdistinctparameter(model, componentname, :bau_businessasusualemissions, readpagedata(model, "data/bau_ch4emissions.csv"))
    elseif class == :N2O
        setdistinctparameter(model, componentname, :emit_UncertaintyinBAUEmissFactorinFocusRegioninFinalYear, 0.)
        setdistinctparameter(model, componentname, :q0propinit_CutbacksinNegativeCostinFocusRegioninBaseYear, 10.)
        setdistinctparameter(model, componentname, :c0init_MostNegativeCostCutbackinBaseYear, -7333.333333333333)
        setdistinctparameter(model, componentname, :qmaxminusq0propinit_MaxCutbackCostatPositiveCostinBaseYear, 51.66666666666666664)
        setdistinctparameter(model, componentname, :cmaxinit_MaximumCutbackCostinFocusRegioninBaseYear, 27333.3333333333)
        setdistinctparameter(model, componentname, :ies_InitialExperienceStockofCutbacks, 53.3333333333333)
        setdistinctparameter(model, componentname, :e0_baselineemissions, readpagedata(model, "data/e0_baselineN2Oemissions.csv"))
        setdistinctparameter(model, componentname, :bau_businessasusualemissions, readpagedata(model, "data/bau_n2oemissions.csv"))
    elseif class == :Lin
        setdistinctparameter(model, componentname, :emit_UncertaintyinBAUEmissFactorinFocusRegioninFinalYear, 0.)
        setdistinctparameter(model, componentname, :q0propinit_CutbacksinNegativeCostinFocusRegioninBaseYear, 10.)
        setdistinctparameter(model, componentname, :c0init_MostNegativeCostCutbackinBaseYear, -233.333333333333)
        setdistinctparameter(model, componentname, :qmaxminusq0propinit_MaxCutbackCostatPositiveCostinBaseYear, 70.)
        setdistinctparameter(model, componentname, :cmaxinit_MaximumCutbackCostinFocusRegioninBaseYear, 333.333333333333)
        setdistinctparameter(model, componentname, :ies_InitialExperienceStockofCutbacks, 2000.)
        setdistinctparameter(model, componentname, :e0_baselineemissions, readpagedata(model,"data/e0_baselineLGemissions.csv"))
        setdistinctparameter(model, componentname, :bau_businessasusualemissions, readpagedata(model,"data/bau_linemissions.csv"))
    else
        error("Unknown class of abatement costs.")
    end

    return abatementcostscomp
end


text:
using JLD2
using Test
using Random

tdir = tempdir()

@testset "BufferedReader" begin
    cd(tdir) do
        a = randn(100)
        open("testfile.1", "w") do ff
            write(ff, a)
        end
        b = open("testfile.1", "r") do ff
            br = JLD2.BufferedReader(ff)
            b = read(br, Float64, 100)
        end
        @test a ≈ b
        rm("testfile.1")
    end
end


text:
using Base.Test

module DeprecationTests # to test @deprecate
    f() = true

    # test the Symbol path of @deprecate
    @deprecate f1 f
    @deprecate f2 f false # test that f2 is not exported

    # test the Expr path of @deprecate
    @deprecate f3() f()
    @deprecate f4() f() false # test that f4 is not exported
    @deprecate f5(x::T) where T f()

    # test deprecation of a constructor
    struct A{T} end
    @deprecate A{T}(x::S) where {T, S} f()

    # test that @deprecate_moved can be overridden by an import
    Base.@deprecate_moved foo1234 "Foo"
    Base.@deprecate_moved bar "Bar" false
end # module
module Foo1234
    export foo1234
    foo1234(x) = x+1
end

# issue #21972
struct T21972
    @noinline function T21972()
        Base.depwarn("something", :T21972)
        new()
    end
end

@testset "@deprecate" begin
    using .DeprecationTests
    using .Foo1234
    @test foo1234(3) == 4
    @test_throws ErrorException DeprecationTests.bar(3)

    # 22845
    ex = :(module M22845; import ..DeprecationTests: bar;
                          bar(x::Number) = x + 3; end)
    @test_warn "importing deprecated binding" eval(ex)
    @test @test_nowarn(DeprecationTests.bar(4)) == 7

    # enable when issue #22043 is fixed
    # @test @test_warn "f1 is deprecated, use f instead." f1()
    # @test @test_nowarn f1()

    # @test_throws UndefVarError f2() # not exported
    # @test @test_warn "f2 is deprecated, use f instead." DeprecationTests.f2()
    # @test @test_nowarn DeprecationTests.f2()

    # @test @test_warn "f3() is deprecated, use f() instead." f3()
    # @test @test_nowarn f3()

    # @test_throws UndefVarError f4() # not exported
    # @test @test_warn "f4() is deprecated, use f() instead." DeprecationTests.f4()
    # @test @test_nowarn DeprecationTests.f4()

    # @test @test_warn "f5(x::T) where T is deprecated, use f() instead." f5(1)
    # @test @test_nowarn f5(1)

    # @test @test_warn "A{T}(x::S) where {T, S} is deprecated, use f() instead." A{Int}(1.)
    # @test @test_nowarn A{Int}(1.)

    # issue #21972
    @noinline function f21972()
        T21972()
    end
    @test_warn "deprecated" f21972()
    @test_nowarn f21972()
end

max_stars_repo_name: Mikewl/julia

max_issues_repo_name: Mikewl/julia

max_forks_repo_name: Mikewl/julia