text:
function mark_pyramid(r::Robot)
    count_horizont = moves!(r, West)
    count_verticale = moves!(r, Sud)

    len = moves!(r, Ost)
    moves!(r, West)

    put_all_markers(r, len)

    moves!(r, Sud)
    Back(r, Ost, count_horizont)
    Back(r, Nord, count_verticale)
  end

function put_markers(r::Robot, len::Int)
  while true
      for i = 1:len
          putmarker!(r)
          move!(r, Ost)
      end
      putmarker!(r)

        moves!(r, West)

      if !isborder(r, Nord)
            move!(r, Nord)
      else
          break
      end

      len -= 1
  end
end

function moves!(r::Robot, side::HorizonSide)
  count = 0
  while !isborder(r, side)
      move!(r, side)
      count += 1
  end
  return count
end

function Back(r::Robot, side::HorizonSide, steps::Int)
  for i = 1:steps
      move!(r, side)
  end
end

max_stars_repo_name: NikitaDestroyer/Basics

max_issues_repo_name: NikitaDestroyer/Basics

max_forks_repo_name: NikitaDestroyer/Basics


text:
    user_agents = [
        "chrome", "firefox", "internet_explorer", "opera", "safari"
    ]

    windows_platform_tokens = [
        "Windows 95", "Windows 98", "Windows 98; Win 9x 4.90", "Windows CE",
        "Windows NT 4.0", "Windows NT 5.0", "Windows NT 5.01",
        "Windows NT 5.1", "Windows NT 5.2", "Windows NT 6.0", "Windows NT 6.1",
        "Windows NT 6.2"
    ]

    linux_processors = ["i686", "x86_64"]

    mac_processors = ["Intel", "PPC", "U; Intel", "U; PPC"]

    langs = ["en-US", "sl-SI", "it-IT"]

    mac_processor()= executor(mac_processors)

    linux_processor()= executor(linux_processors)

    user_agent()= executor(user_agents)

    windows_platform_token()= executor(windows_platform_tokens)

    linux_platform_token()= "X11; Linux $(linux_processor())"

    mac_platform_token()= "Macintosh; $(mac_processor()) Mac OS X 10_$(rand(5:8))_$(rand(0:9))"

    chrome()=
    (
        saf = "$(rand(531:536))" * "$(rand(0:2))";
        platforms = (
            "($(linux_platform_token())) AppleWebKit/$(saf) (KHTML, like Gecko) Chrome/$(rand(13:70)).0.$(rand(800:899)).0 Safari/$(saf)",
            "($(windows_platform_token())) AppleWebKit/$(saf) (KHTML, like Gecko) Chrome/$(rand(13:70)).0.$(rand(800:899)).0 Safari/$(saf)",
            "($(mac_platform_token())) AppleWebKit/$(saf) (KHTML, like Gecko) Chrome/$(rand(13:70)).0.$(rand(800:899)).0 Safari/$(saf)"
        );

        return "Mozilla/5.0 " * platforms[rand(1:length(platforms))]
    )

    firefox()=
    (ver = (
            "Gecko/$(date_time_between()) Firefox/$(rand(4:15)).0",
            "Gecko/$(date_time_between()) Firefox/3.6.$( rand(1:20))",
            "Gecko/$(date_time_between()) Firefox/3.8"
        );

        platforms = (
         "($(windows_platform_token()); $(langs[rand(1:length(langs))]); rv:1.9.$(rand(0:2)).20) $(ver[rand(1:length(ver))])",
        "($(linux_platform_token()); rv:1.9.$(rand(5:7)).20) $(ver[rand(1:length(ver))])",
        "($(mac_platform_token()); rv:1.9.$(rand(2:6)).20) $(ver[rand(1:length(ver))])"
        );

        return "Mozilla/5.0 " * platforms[rand(1:length(platforms))])

   safari()=
    (saf = "$(rand(531:535)).$(rand(1:50)).$(rand(1:7))";
        if rand(0:1) == 0
            ver = "$(rand(4:5)).$(rand(0:1))"
        else
            ver = "$(rand(4:5)).0.$(rand(1:5))"
        end ;

        platforms = (
        "(Windows; U; $(windows_platform_token())) AppleWebKit/$(saf) (KHTML, like Gecko) Version/$(ver) Safari/$(saf)",
        "($(mac_platform_token()) rv:$(rand(2:6)).0; $(langs[rand(1:length(langs))])) AppleWebKit/$(saf) (KHTML, like Gecko) Version/$(ver) Safari/$(saf)",
        "(iPod; U; CPU iPhone OS $(rand(3:4))_$(rand(0:3)) like Mac OS X; $(langs[rand(1:length(langs))])) AppleWebKit/$(saf) (KHTML, like Gecko) Version/$(rand(3:4)).0.5 Mobile/8B$(rand(111:119)) Safari/6$(saf)"
        );

        return "Mozilla/5.0 " * platforms[rand(1:length(platforms))]
    )

    opera()=
    (
        platforms = ( "($(linux_platform_token()); $(langs[rand(1:length(langs))])) Presto/2.9.$(rand(160:190)) Version/$(rand(10:12)).00" ,
         "($(windows_platform_token()); $(langs[rand(1:length(langs))])) Presto/2.9.$(rand(160:190)) Version/$(rand(10:12)).00"
        );
        return "Opera/$(rand(8:9)).$(rand(10:99)).$(platforms[rand(1:length(platforms))]))"
    )

    internet_explorer()= "Mozilla/5.0 (compatible; MSIE $(rand(5:9)).0; $(windows_platform_token()); Trident/$(rand(3:5)).$(rand(0:1)))"

ext: jl


text:
using DataFrames, Dates

"""Serves as an interface to climate data"""
mutable struct Climate <: AgComponent

    data::Any
    time_steps::Array
    description::Any
    annual_rainfall::DataFrame

    function Climate(data::DataFrame)
        c = new()
        c.data = data
        c.time_steps = data[!, :Date]
        data[:, :Year] = Dates.year.(c.time_steps)

        gdf = groupby(data[:, filter(x -> x != :Date, propertynames(data))], :Year)

        not_year_col::Array{Symbol,1} = collect(filter(x -> x != :Year, propertynames(gdf)))
        yearly = combine(gdf, names(gdf) .=> sum)

        rain_cols::Array{Symbol,1} = filter(x -> occursin("rainfall", string(x)), propertynames(yearly))
        push!(rain_cols, :Year)

        c.annual_rainfall = yearly[:, rain_cols]

        stats::Array{Symbol,1} = [:mean, :std, :min, :q25, :median, :q75, :max, :eltype, :nunique, :nmissing]
        not_year_col = filter(x -> x != :Year, propertynames(yearly))

        c.description = describe(yearly[:, not_year_col], stats...)

        return c
    end
end

function Base.getindex(c::Climate, args...)::DataFrame
    return c.data[args...]
end

# function __getitem__(c::Climate, item)
#     return c.data[item]
# end

# function annual_rainfall(c::Climate, timestep::Date)
#     """
#     Calculate the total amount of rainfall that occured in a year, given in the timestep

#     Parameters
#     ----------
#     * timestep : datetime or int, indicating year in terms of time step.
#     """
#     year = timestep if type(timestep) == int else timestep.year
#     data = c.data

#     year_data = data[data.index.year == year]
#     yearly_rainfall = year_data.sum()

#     return yearly_rainfall['rainfall']
# end

# function annual_rainfall(c::Climate, timestep::Int64)
#     """
#     Calculate the total amount of rainfall that occured in a year, by index position.

#     Parameters
#     ----------
#     * timestep : Indicating year in terms of index position.
#     """
#     data = c.data

#     year_data = data[data.index.year == timestep]
#     yearly_rainfall = sum(year_data)

#     return yearly_rainfall['rainfall']
# end

"""Gets climate data for season range.

Parameters
----------
* p_start : datetime, start of range in Y-m-d format, inclusive.
* p_end : datetime, end of range in Y-m-d format, inclusive.
"""
function get_season_range(c::Climate, p_start::Date, p_end::Date)::DataFrame
    dates::Array{Date,1} = c.time_steps::Array{Date,1}
    mask::BitArray{1} = (p_start .<= dates .<= p_end)::BitArray{1}
    return c.data[mask, :]
end

"""Converts strings to datetime."""
function ensure_date(c::Climate, p_start::String, p_end::String)::Tuple
    s::Date = Date(p_start)
    e::Date = Date(p_end)

    @assert e > s "Season end date cannot be earlier than start date ($(p_start) < $(p_end) ?)"

    return s, e
end

"""Retrieve seasonal rainfall by matching column name.
Columns names are expected to have 'rainfall' with some identifier.

Parameters
----------
* season_range : List-like, start and end dates, can be string or datetime object
* partial_name : str, string to (partially) match column name identifier on

Example
----------
Where column names are: 'rainfall_field1', 'rainfall_field2', ...

`get_seasonal_rainfall(c, ['1981-01-01', '1982-06-01'], 'field1')`

Returns
--------
numeric, representing seasonal rainfall
"""
function get_seasonal_rainfall(c::Climate, season_range::Array{Date}, partial_name::String)::Float64
    s::Date, e::Date = season_range
    subset::DataFrame = get_season_range(c, s, e)[!, Regex("rainfall")][!, Regex(partial_name)]
    return sum.(eachcol(subset))[1]
end

"""Retrieve seasonal evapotranspiration.

Parameters
----------
* season_range : List-like, start and end dates, can be string or datetime object
* partial_name : str, string to (partially) match column name identifier on

Returns
--------
numeric of seasonal rainfall
"""
function get_seasonal_et(c::Climate, season_range::Array{Date}, partial_name::String)::DataFrame
    s::Date, e::Date = season_range
    subset::DataFrame = get_season_range(c, s, e)[!, Regex("ET")][!, Regex(partial_name)]
    return sum.(eachcol(subset))[1]
end

function get_data_for_timestep(c::Climate, dt; pattern=nothing)

    data::DataFrame = c.data::DataFrame
    idx::BitArray = (c.time_steps::Array .== dt)::BitArray

    if isnothing(pattern)
        subset::DataFrame = data[idx, :]
    else
        cols = [k for k in names(data) if any(occursin(pattern, string(k)))]
        subset = data[idx, cols]
    end

    return subset
end

max_stars_repo_name: ConnectedSystems/agtor-jl

max_issues_repo_name: ConnectedSystems/agtor-jl

max_forks_repo_name: ConnectedSystems/agtor-jl


text:
@graphs begin
	 ################################################################################
	 @node event_cards_preferred = Start() -> ep_1_strat

	 @node ep_1_strat = CheckStrategy("military") -> [n_true = ep_1_mili, n_false = ep_1_corr]
	 @node ep_1_mili = BinaryCondition("""
					 A card with army or muster type is *playable*.
					 """) -> [n_true = ep_2_yes, n_false = ep_return]
	 @node ep_1_corr = BinaryCondition("""
					 A card with character type is *playable*.
					 """) -> [n_true = ep_2_yes, n_false = ep_return]

	 @node ep_return = ReturnFromGraph() -> []
	 @node ep_2_yes = UseActiveDie() -> ep_2_strat
	 @node ep_2_strat = CheckStrategy("military") -> [n_true = ep_2_mili, n_false = ep_2_corr]
	 @node ep_2_mili = PerformAction("""
				   Play a *playable* card with muster or army type.

				   Priority:
				   1. Ascending Order of Initiative
				   2. Random
				   """) -> ep_2_end
	 @node ep_2_corr = PerformAction("""
				   Play a *playable* card with character type.

				   Priority:
				   1. Ascending Order of Initiative
				   2. Random
				   """) -> ep_2_end
	 @node ep_2_end = End() -> []

	 ################################################################################
	 @node event_cards_general = Start() -> eg_1
	 @node eg_1 = BinaryCondition("""
					 Holding less than 4 cards.
					 """) -> [n_true = eg_1_yes, n_false = eg_2]
	 @node eg_1_yes = UseActiveDie() -> eg_1_strat
	 @node eg_1_strat = CheckStrategy("military") -> [n_true = eg_1_mili, n_false = eg_1_corr]
	 @node eg_1_mili = PerformAction("""
				   Draw a strategy card.
				   """) -> eg_1_end
	 @node eg_1_corr = PerformAction("""
				   Draw a character card.
				   """) -> eg_1_end
	 @node eg_1_end = End() -> []

	 @node eg_2 = BinaryCondition("""
					 A card is *playable*.
					 """) -> [n_true = eg_2_yes, n_false = eg_3]
	 @node eg_2_yes = UseActiveDie() -> eg_2_action
	 @node eg_2_action = PerformAction("""
				   Play a *playable* card.

				   Priority:
				   1. Ascending order of initiative
				   2. Random
				   """) -> eg_2_end
	 @node eg_2_end = End() -> []

	 @node eg_3 = UseActiveDie() -> eg_3_strat
	 @node eg_3_strat = CheckStrategy("military") -> [n_true = eg_3_mili, n_false = eg_3_corr]
	 @node eg_3_mili = PerformAction("""
				   Draw a strategy card.
				   """) -> eg_3_discard
	 @node eg_3_corr = PerformAction("""
				   Draw a character card.
				   """) -> eg_3_discard
	 @node eg_3_discard = BinaryCondition("""
					 Holding more than 6 cards.
					 """) -> [n_true = eg_3_discard_strat, n_false = eg_3_end]
	 @node eg_3_end = End() -> []

	 @node eg_3_discard_strat = CheckStrategy("military") -> [n_true = eg_3_discard_mili, n_false = eg_3_discard_corr]
	 @node eg_3_discard_mili = PerformAction("""
				   Discard down to 6 cards.

				   Priority:
				   1. Not a card with army or muster type
				   2. Doesn't use the term "Fellowship revealed"
				   3. Doesn't place a tile
				   4. Ascending order of initiative
				   5. Random
				   """) -> eg_3_discard_end
	 @node eg_3_discard_corr = PerformAction("""
				   Discard down to 6 cards.

				   Priority:
				   1. Not card with character type
				   2. Doesn't use the term "Fellowship revealed"
				   3. Doesn't place a tile
				   4. Ascending order of initiative
				   5. Random
				   """) -> eg_3_discard_end
	 @node eg_3_discard_end = End() -> []

	 ################################################################################
	 @node event_cards_corruption = Start() -> ec_1
	 @node ec_1 = BinaryCondition("""
					 A "Fellowship revealed" card is *playable*.
					 """) -> [n_true = ec_1_yes, n_false = ec_2]
	 @node ec_1_yes = UseActiveDie() -> ec_1_action
	 @node ec_1_action = PerformAction("""
				   Play a *playable* "Fellowship revealed" card.

				   Priority:
				   1. Ascending order of initiative
				   2. Random
				   """) -> ec_1_end
	 @node ec_1_end = End() -> []

	 @node ec_2 = BinaryCondition("""
					 A card that adds corruption or adds a hunt tile is *playable*.
					 """) -> [n_true = ec_2_yes, n_false = ec_3]
	 @node ec_2_yes = UseActiveDie() -> ec_2_action
	 @node ec_2_action = PerformAction("""
				   Play a *playable* card which adds corruption or adds a hunt tile.

				   Priority:
				   1. Ascending order of initiative
				   2. Random
				   """) -> ec_2_end
	 @node ec_2_end = End() -> []

	 @node ec_3 = BinaryCondition("""
					 Holding less than 4 cards.
					 """) -> [n_true = ec_3_yes, n_false = ec_return]
	 @node ec_3_yes = UseActiveDie() -> ec_3_action
	 @node ec_3_action = PerformAction("""
				   Draw a character card.
				   """) -> ec_3_end
	 @node ec_3_end = End() -> []

	 @node ec_return = ReturnFromGraph() -> []

	 ################################################################################
	 @node event_cards_resolve_effect = Start() -> er_select_card_effect_choice
	 @node er_select_card_effect_choice = MultipleChoice("""
					Select card effect to resolve.

					1. Region selection for muster
					2. Army selection for movement or attack
					3. Move minion or Nazgûl
					4. Hunt allocation
					5. No effect, return to Phase 5 menu
					""") -> [er_muster, er_army, er_char_move, er_hunt, er_resolve_end]
	 @node er_muster = JumpToGraph("muster_card") -> er_resolve_end
	 @node er_army = JumpToGraph("movement_attack_card") -> er_resolve_end
	 @node er_char_move = MultipleChoice("""
					Select what to move.

					1. The Which King
					2. The Mouth of Sauron
					3. The Nazgûl
					4. Nothing
					""") -> [er_move_wk, er_move_mos, er_move_naz, er_select_card_effect_choice]
	 @node er_move_wk = JumpToGraph("character_wk_prio") -> er_resolve_end
	 @node er_move_mos = JumpToGraph("character_mos_prio") -> er_resolve_end
	 @node er_move_naz = JumpToGraph("character_nazgul_prio") -> er_resolve_end

	 @node er_hunt = CheckStrategy("military") -> [n_true = er_hunt_mili, n_false = er_hunt_corr]
	 @node er_hunt_mili = PerformAction("""
										Select a character or event die at random, roll a d6. On a 4+, add it to the hunt pool. Do this for each die it is possible to add to the hunt pool.
										""") -> er_resolve_end
	 @node er_hunt_corr = PerformAction("""
										Select a army, muster, muster/army, or event die at random, roll a d6. On a 4+, add it to the hunt pool. Do this for each die it is possible to add to the hunt pool.
										""") -> er_resolve_end
	 @node er_resolve_end = End() -> []
end

max_stars_repo_name: mvmorin/queller-bot

max_issues_repo_name: mvmorin/queller-bot

max_forks_repo_name: mvmorin/queller-bot


text:
using Distributed

using Test

@everywhere begin
    using MLJBase
    using MLJTuning
    using ..Models
    import ComputationalResources: CPU1, CPUProcesses, CPUThreads
end

using Random
Random.seed!(1234*myid())
using .TestUtilities

N = 30
x1 = rand(N);
x2 = rand(N);
x3 = rand(N);
X = (x1=x1, x2=x2, x3=x3);
y = 2*x1 .+ 5*x2 .- 3*x3 .+ 0.4*rand(N);

m(K) = KNNRegressor(K=K)
r = [m(K) for K in 2:13]

# TODO: replace the above with the line below and post an issue on
# the failure (a bug in Distributed, I reckon):
# r = (m(K) for K in 2:13)

@testset "constructor" begin
    @test_throws ErrorException TunedModel(model=first(r), tuning=Explicit(),
                                           measure=rms)
    @test_throws ErrorException TunedModel(tuning=Explicit(),
                                           range=r, measure=rms)
    @test_throws ErrorException TunedModel(model=42, tuning=Explicit(),
                                           range=r, measure=rms)
    @test_logs((:info, r"No measure"),
               TunedModel(model=first(r), tuning=Explicit(), range=r))
end

# @testset "duplicate models warning" begin
#     s = [m(K) for K in 2:13]
#     push!(s, m(13))
#     tm = TunedModel(model=first(s), tuning=Explicit(),
#                     range=s, resampling=CV(nfolds=2),
#                     measures=[rms, l1])
#     @test_logs((:info, r"Attempting"),
#                (:warn, r"A model already"),
#                fitresult, meta_state, report = fit(tm, 1, X, y))
#     history, _, state = meta_state;
#     @test length(history) == length(2:13) + 1
# end

results = [(evaluate(model, X, y,
                     resampling=CV(nfolds=2),
                     measure=rms,
                     verbosity=0,)).measurement[1] for model in r]

@testset "measure compatibility check" begin
    tm = TunedModel(model=first(r), tuning=Explicit(),
                    range=r, resampling=CV(nfolds=2),
                    measures=cross_entropy)
    @test_throws ArgumentError fit(tm, 0, X, y)
end

@testset_accelerated "basic fit (CPU1)" accel begin
    printstyled("\n Testing progressmeter basic fit with $(accel) and CPU1 resampling \n", color=:bold)
    best_index = argmin(results)
    tm = TunedModel(model=first(r), tuning=Explicit(),
                    range=r, resampling=CV(nfolds=2),
                    measures=[rms, l1], acceleration=accel)
    fitresult, meta_state, report = fit(tm, 1, X, y);
    history, _, state = meta_state;
    results2 = map(event -> event.measurement[1], history)
    @test results2 ≈ results
    @test fitresult.model == collect(r)[best_index]
    @test report.best_model == collect(r)[best_index]
    @test report.history[5] == MLJTuning.delete(history[5], :metadata)
end

@static if VERSION >= v"1.3.0-DEV.573"
@testset_accelerated "Basic fit (CPUThreads)" accel begin
    printstyled("\n Testing progressmeter basic fit with $(accel) and CPUThreads resampling \n", color=:bold)
    tm = TunedModel(model=first(r), tuning=Explicit(),
                    range=r, resampling=CV(nfolds=2),
                    measures=[rms, l1], acceleration= CPUThreads(),
                    acceleration_resampling=accel)
    fitresult, meta_state, report = fit(tm, 1, X, y);
    history, _, state = meta_state;
    results3 = map(event -> event.measurement[1], history)
    @test results3 ≈ results
end
end
@testset_accelerated "Basic fit (CPUProcesses)" accel begin
    printstyled("\n Testing progressmeter basic fit with $(accel) and CPUProcesses resampling \n", color=:bold)
    best_index = argmin(results)
    tm = TunedModel(model=first(r), tuning=Explicit(),
                    range=r, resampling=CV(nfolds=2),
                    measures=[rms, l1], acceleration=CPUProcesses(),
                    acceleration_resampling=accel)
    fitresult, meta_state, report = fit(tm, 1, X, y);
    history, _, state = meta_state;
    results4 = map(event -> event.measurement[1], history)
    @test results4 ≈ results
end

@testset_accelerated("under/over supply of models", accel, begin
                     tm = TunedModel(model=first(r), tuning=Explicit(),
                                     range=r, measures=[rms, l1],
                                     acceleration=accel,
                                     resampling=CV(nfolds=2),
                                     n=4)
    mach = machine(tm, X, y)
    fit!(mach, verbosity=1)
    history = MLJBase.report(mach).history
    @test map(event -> event.measurement[1], history) ≈ results[1:4]

    tm.n=100
    @test_logs (:info, r"Only 12") fit!(mach, verbosity=0)
    history = MLJBase.report(mach).history
    @test map(event -> event.measurement[1], history) ≈ results
end)

@everywhere begin

    # variation of the Explicit strategy that annotates the models
    # with metadata
    mutable struct MockExplicit <: MLJTuning.TuningStrategy end

    annotate(model) = (model, params(model)[1])

    _length(x) = length(x)
    _length(::Nothing) = 0
    MLJTuning.models(tuning::MockExplicit,
                     model,
                     history,
                     state,
                     n_remaining,
                     verbosity) =
                         annotate.(state)[_length(history) + 1:end], state

    function default_n(tuning::Explicit, range)
        try
            length(range)
        catch MethodError
            DEFAULT_N
        end

    end

end

@testset_accelerated("passing of model metadata", accel,
                  begin
                     tm = TunedModel(model=first(r), tuning=MockExplicit(),
                                     range=r, resampling=CV(nfolds=2),
                                     measures=[rms, l1], acceleration=accel)
                     fitresult, meta_state, report = fit(tm, 0, X, y);
                     history, _, state = meta_state;
                     @test all(history) do event
                         event.metadata == event.model.K
                     end
end)

true


text:
module CategoricalArrays
    export CategoricalPool, CategoricalValue, CategoricalString
    export AbstractCategoricalArray, AbstractCategoricalVector, AbstractCategoricalMatrix,
           CategoricalArray, CategoricalVector, CategoricalMatrix
    export AbstractMissingCategoricalArray, AbstractMissingCategoricalVector,
           AbstractMissingCategoricalMatrix,
           MissingCategoricalArray, MissingCategoricalVector, MissingCategoricalMatrix
    export LevelsException, OrderedLevelsException

    export categorical, compress, decompress, droplevels!, levels, levels!, isordered, ordered!
    export cut, recode, recode!

    using Compat
    using JSON
    using DataAPI
    using Reexport

    # TODO: cannot @reexport in conditional, the below should be removed when 0.6 is deprecated
    @reexport using Missings

    if VERSION >= v"0.7.0-DEV.3052"
        using Printf
    end

    include("typedefs.jl")

    include("buildfields.jl")

    include("pool.jl")
    include("value.jl")

    include("array.jl")
    include("missingarray.jl")
    include("subarray.jl")

    include("extras.jl")
    include("recode.jl")

    include("deprecated.jl")
end


text:
using TimeSeries

using MarketData

ohlc[1]

ohlc[[1:3;9]]

ohlc["Open","Close"]

ohlc[[Date(2000,1,3),Date(2000,2,4)]]

ohlc[Date(2000,1,10):Date(2000,2,10)]

ohlc["Open"][Date(2000,1,10)]

from(cl, Date(2001, 10, 24))

to(cl, Date(2000, 10, 24))

red = findwhen(ohlc["Close"] .< ohlc["Open"]);

ohlc[red]

green = find(ohlc["Close"] .> ohlc["Open"]);

ohlc[green]

cl[1:4]

lag(cl[1:4])

lead(cl[1:4])

lead(cl, 400)

percentchange(cl)

merge(op[1:4], cl[2:6], :left)

a = TimeArray([Date(2015, 10, 24), Date(2015, 11, 04)], [15, 16], ["Number"])

map((timestamp, values) -> (timestamp + Dates.Year(1), values), a)

max_stars_repo_path: Chapter 9/ch09-TimeSeries.jl

max_stars_repo_name: PacktPublishing/Julia-for-data-science

max_issues_repo_path: Chapter 9/ch09-TimeSeries.jl

max_issues_repo_name: PacktPublishing/Julia-for-data-science

max_forks_repo_path: Chapter 9/ch09-TimeSeries.jl

max_forks_repo_name: PacktPublishing/Julia-for-data-science


text:
using Distributions, SpecialFunctions

struct SupremumStable <: ContinuousUnivariateDistribution
  α::Float64
  β::Float64
  θ::Float64
  ρ::Float64
  SupremumStable(α::Real,β::Real) = ( β <- 1 || β > 1 || α <= 0 || α > 2 ) ?
    error("Parameters' requirements unmet:\n (α,β)∈(0,2]×[-1,1]") :
    α == 2 ? PositiveStable(2,-1) :
    β == -1 && α > 1 ? PositiveStable(α,β) :
    new(α,β,β*(α <= 1 ? 1 :
    (α-2)/α),(1 + β*(α <= 1 ? 1 : (α-2)/α))/2)
end

import Distributions.params
function params(d::SupremumStable)
  return (d.α,d.β,d.θ,d.ρ)
end

import Distributions.minimum
function minimum(d::SupremumStable)
  return (β == -1 && α <= 1) ? 0 : β == 1 && α == 1 ? 1. : 0.
end

import Distributions.maximum
function maximum(d::SupremumStable)
  return (β == -1 && α <= 1) ? 0 : β == 1 && α == 1 ? 1. : Inf
end

import Distributions.insupport
function insupport(d::SupremumStable,x::Real)
  return (β == -1 && α <= 1) ? x == 0 : x >= 0
end

import Distributions.mean
function mean(d::SupremumStable)
  return d.α*d.ρ*mean(PositiveStable(d.α,d.β))
end

struct PerfectSupremumStable <: Sampleable{Univariate,Continuous}
  α::Float64
  β::Float64
  θ::Float64
  ρ::Float64
  d::Float64
  η::Float64
  δ::Float64
  γ::Float64
  κ::Float64
  Δ::Int64
  mAst::Int64
  PerfectSupremumStable(α::Real,β::Real,d::Real,δ::Real,γ::Real,κ::Real,Δ::Int,mAst::Int) =
    (β < -1 || β > 1 || (β == -1 && α <= 1) || α <= 0 || α > 2) ?
    error("Parameters' requirements unmet: (α,β)∈(0,2]×[-1,1]-(0,1]×{-1}") : (0 >= γ || γ >= α) ?
    error("Parameters' requirements unmet: α>γ>0") : (0 >= δ || δ >= d || d >= 2/(α + β*(α <= 1 ? α : α-2))) ?
    error("Parameters' requirements unmet: 1/(αρ)>d>δ>0") : κ < 0 ?
    error("Parameters' requirements unmet: κ≥0") : Δ <= 0 ?
    error("Parameters' requirements unmet: Δ≥0") : mAst < 0 ?
    error("Parameters' requirements unmet: m*≥0") : new(α, β, β*(α <= 1 ? 1 : (α-2)/α),(1+β*(α <= 1 ? 1 : (α-2)/α))/2 , d,
      etaF(d*(α + β*(α <= 1 ? α : α-2))/2)*(α + β*(α <= 1 ? α : α-2))/2 , δ, γ, κ + Int(ceil(max(2/(α+β*(α <= 1 ? α : α-2)),
      log(2)*2/(3*etaF(d*(α+β*(α <= 1 ? α : α-2))/2)*(α+β*(α <= 1 ? α : α-2)) ) ))), Δ, mAst)
  PerfectSupremumStable(α::Real,β::Real,d::Real,δ::Real,γ::Real,κ::Real,Δ::Int) = PerfectSupremumStable(α,β,d,δ,γ,κ,Δ,12)
  PerfectSupremumStable(α::Real,β::Real,d::Real,δ::Real,γ::Real,κ::Real) = PerfectSupremumStable(α,β,d,δ,γ,κ,40)
  PerfectSupremumStable(α::Real,β::Real,d::Real,δ::Real,γ::Real) = PerfectSupremumStable(α,β,d,δ,γ,3)
  PerfectSupremumStable(α::Real,β::Real) = PerfectSupremumStable(α,β,(2/3)*2/(α+β*(α <= 1 ? α : α-2)),(1/3)*2/(α+β*(α <= 1 ? α : α-2)),.95*α)
end

import Distributions.sampler
function sampler(d::SupremumStable,dr::Real,δ::Real,γ::Real,κ::Real,r::Real,lag::Int64,mAst::Int64)
  return PerfectSupremumStable(d.α,d.β,dr,δ,γ,κ,r,lag,mAst)
end

function sampler(d::SupremumStable,dr::Real,δ::Real,γ::Real,κ::Real,r::Real,lag::Int64)
  return PerfectSupremumStable(d.α,d.β,dr,δ,γ,κ,r,lag)
end

function sampler(d::SupremumStable,dr::Real,δ::Real,γ::Real)
  return PerfectSupremumStable(d.α,d.β,dr,δ,γ)
end

function sampler(d::SupremumStable)
  return PerfectSupremumStable(d.α,d.β)
end

function params(d::PerfectSupremumStable)
  return (α,β,θ,ρ,d,η,δ,γ,κ,r,lag,mAst)
end

using LambertW
# @Input: normalised drift d'=αρd∈(0,1)
# @Returns: normalised η'=η/(αρ)>0
function etaF(d::Real)
  return -lambertw(-d*exp(-d),-1)/d-1
end

# @Input: drift d, η, 1/(αρ+η), and a bound M we want to know if we exceed
# @Returns: a sample of 1{R_0 <= M}
function reflectedProcess(d::Real,et::Real,et1::Real,M::Real)
  T = rand(Exponential())/et
  if T <= M
    return true
  end
  Sn = [0.]
  while Sn[end] < T
    push!(Sn,Sn[end]-rand(Exponential())*et1+d)
  end
  return maximum(Sn[1:(end-1)]) <= M
end

# @Input: drift d, η, 1/(αρ+η), a bound M that it should not exceed,
# and another bound M1 we want to know if we exceed
# @Returns: a sample of 1{R_0 <= M1} given R_0<M
function reflectedProcess(d::Real,et::Real,et1::Real,M::Real,M1::Real)
  m = exp(-M-d)
  Sn = [0.]
  while true
    T = -log(rand(Uniform(m,1)))/et # Exponential conditioned on <= M+d, since T>M+d always yields a rejection
    if T <= M1
      return true
    end
    while Sn[end] < T
      push!(Sn,Sn[end]-rand(Exponential())*et1+d)
    end
    max = maximum(Sn[1:(end-1)])
    if max <= M
      return max <= M1
    else
      Sn = [0.]
    end
  end
end

# @Input: drift d, η, 1/(αρ+η), κ and an upper bound x
# @Returns: A simulated run of the random walk up to the hitting time of the barrier
# -2κ conditioned on never exceeding x
function downRW(d::Real,rar::Real,et::Real,et1::Real,κ::Real,x::Real)
  Sn = [0.]
  INCn = [0.]
  if isfinite(x)
    while true
      while Sn[end] > -2 *κ
        push!(INCn,rand(Exponential())*rar)
        push!(Sn,Sn[end]-INCn[end]+d)
      end
      if maximum(Sn) < x && reflectedProcess(d,et,et1,x-Sn[end])
        return (Sn[2:end],INCn[2:end])
      else
        Sn = [0.]
        INCn = [0.]
      end
    end
  else
    while Sn[end] > -2 *κ
      push!(INCn,rand(Exponential())*rar)
      push!(Sn,Sn[end]-INCn[end]+d)
    end
    return (Sn[2:end],INCn[2:end])
  end
end

# @Input: drift d, η, 1/(αρ+η), κ, an upper bound x that will be attained
# @Returns: A simulated run of the random walk up to the hitting time of the barrier
# κ conditioned on never exceeding x
function upRW(d::Real,et::Real,et1::Real,κ::Real,x::Real)
  Sn = [0.]
  INCn = [0.]
  if x == Inf
    while true
      while Sn[end] < κ
        push!(INCn,rand(Exponential())*et1)
        push!(Sn,Sn[end]-INCn[end]+d)
      end
      if rand(Uniform()) <= exp(-et*Sn[end])
        return (Sn[2:end],INCn[2:end])
      else
        Sn = [0.]
        INCn = [0.]
      end
    end
  else
    while true
      while Sn[end] < κ
        push!(INCn,rand(Exponential())*et1)
        push!(Sn,Sn[end]-INCn[end]+d)
      end
      if rand(Uniform()) <= exp(-et*Sn[end]) && reflectedProcess(d,et,et1,x-Sn[end]) # The condition maximum(Sn) < x1 is trivially satisfied by construction of κ
        return (Sn[2:end],INCn[2:end])
      else
        Sn = [0.]
        INCn = [0.]
      end
    end
  end
end

# Blanchet-Sigman algorithm
# @Input: drift d, η, 1/(αρ+η), κ and an upper bound x, last value of random walk s,
# @Returns: A simulated run of the random walk up to the first time we know an upper bound for the walk,
# the increments of the RW, the new upper bound, and the last time at which we may compute D_n
function BSAlgorithm(d::Real,et::Real,et1::Real,κ::Real,x::Real,s::Real)
  Sn = [Float64(s)]
  INCn = [0.]
  x1 = x
  t = 0

  while true
    # Step 1
    (Sn1,INCn1) = downRW(d,et,et1,κ,x1-Sn[end])
    # Step 2
    append!(Sn,Sn[end] .+ Sn1)
    append!(INCn,INCn1)
    t = t+length(Sn1)
    # Step 3 and 4
    if reflectedProcess(d,et,et1,x1-Sn[end],κ)
      x1 = Sn[end]+κ
      t = t-length(Sn1)
      break
    else
      (Sn1,INCn1) = upRW(d,et,et1,κ,x1-Sn[end])
      append!(Sn,Sn[end] .+ Sn1)
      append!(INCn,INCn1)
      t = t+length(Sn1)
    end
  end

  return (Sn[2:end],INCn[2:end],x1,t)
end

# Algorithm 3 - 1 (unconditional probabilities)
# @Input: S^+(α,ρ), δ, dega = δ*γ, dega2 = -1/(1-exp(-dega)), mom = E(S_1^γ), shift = m-k >= m*-1
function chiStable1(d::PositiveStable,δ::Real,dega::Real,dega2::Real,mom::Real,shift::Integer)
  U = rand(Uniform())
  n = shift
  S = Float64[]
  while true
    n = n+1
    aux = exp(δ*n)
    p = cdf(d,aux) # 1-pn
    aux1 = exp(-(n+1)*dega)*mom
    q = p*exp(dega2*aux1/(1-aux1)) # qn
    if U > p
      aux2 = rand(d)
      while aux2 < aux
        aux2 = rand(d)
      end
      push!(S,aux2)
      U = (U-p)/(1-p)
    elseif U < q
      aux2 = rand(d)
      while aux2 > aux
        aux2 = rand(d)
      end
      push!(S,aux2)
      return S
    else
      aux2 = rand(d)
      while aux2 > aux
        aux2 = rand(d)
      end
      push!(S,aux2)
      U = U/p
    end
  end
end

# Algorithm 3 - 2 (conditional probabilities)
# @Input: S^+(α,ρ), δ, dega = δ*γ, dega2 = -1/(1-exp(-dega)), mom = E(S_1^γ)
function chiStable2(d::PositiveStable,δ::Real,dega::Real,dega2::Real,mom::Real,shift::Integer)
  U = rand(Uniform())
  n = shift
  S = Float64[]
  while true
    n = n+1
    aux = exp(δ*n)
    aux0 = exp(δ*(n+1))
    p = cdf(d,aux)/cdf(d,aux0) # 1-pn
    aux1 = exp(-(n+1)*dega)*mom
    q = p*exp(dega2*aux1/(1 -aux1)) # qn
    if U > p
      aux2 = rand(d)
      while aux2 < aux || aux2 > aux0
        aux2 = rand(d)
      end
      push!(S,aux2)
      U = (U-p)/(1 -p)
    elseif U < q
      aux2 = rand(d)
      while aux2 > aux
        aux2 = rand(d)
      end
      push!(S,aux2)
      return S
    else
      aux2 = rand(d)
      while aux2 > aux
        aux2 = rand(d)
      end
      push!(S,aux2)
      U = U/p
    end
  end
end

import Distributions.rand

# Algorithm 9
# @Input: PerfectSupremumStable
# @Output: A random sample from a the law d, σ, and counter of missed coalescences
function rand(d::PerfectSupremumStable)
  ar = d.α*d.ρ
  et1 = 1 /(ar+d.η)
  ra = 1 /d.α
  rar = 1 /ar
  # Conditionally positive stable distribution
  dPos = PositiveStable(d.α,d.β)
  sep = d.d - d.δ
  e2 = 1 /(1 -exp(-sep))
  mom = mellin(dPos,d.γ)
  dega = d.δ*d.γ
  dega2 = -1 /(1 -exp(-dega))
  mAst = d.mAst + Int(ceil( max(0,log(mom)/dega) + rar ))
  # θ sequence
  U = Float64[]
  Λ = Float64[]
  # Line 1
  x = Inf
  σ = 0
  # Line 2
  lagU = rand(Uniform(),d.Δ)
  lagΛ = 1 .+ rand(Bernoulli(1 - d.ρ),d.Δ) .* (rand(Uniform(),d.Δ) .^ rar .- 1)
  lagS = rand(dPos,d.Δ)

  # Line 3 (first iteration)
  # Line 4 (Algorithm 3 with unconditional probabilities)
  S = rand(dPos,mAst)
  append!(S,chiStable1(dPos,d.δ,dega,dega2,mom,mAst-1))

  R = Float64[]
  C = [0.]
  F = Float64[]
  # Last value of C
  endC = 0.
  # First iteration
  # Line 5
  while (length(R) == σ) || (length(S) >= length(C))
    t = length(C)
    # Lines 6 and 7
    (C1,F1) = downRW(d.d,rar,d.η,et1,d.κ,x-endC)
    append!(F,F1)
    append!(C,endC .+ C1)
    endC = C[end]
    # Lines 8 and 9
    if reflectedProcess(d.d,d.η,et1,d.κ,x-endC)
      # Line 10
      x = endC + d.κ
      R1 = [maximum(C[t:end])]
      for i = (t-1):-1:(length(R)+1)
        push!(R1,max(R1[end],C[i]))
      end
      append!(R,R1[end:-1:1] .- C[(length(R)+1):t])
    else # Line 11
      # Lines 12 and 13
      (C1,F1) = upRW(d.d,d.η,et1,d.κ,x-endC)
      append!(F,F1)
      append!(C,endC .+ C1)
      endC = C[end]
    end # Line 14
  end # Line 15
  # Line 16
  while length(U) < length(S)
    T = rand(Poisson(d.α*(1-d.ρ)*F[length(U)+1]))
    if T == 0
      push!(U,exp(-d.α*F[length(U)+1]))
      push!(Λ,1)
    else
      push!(U,exp(-d.α*F[length(U)+1]*rand(Beta(1,T))))
      push!(Λ,exp(-F[length(U)])/U[end]^ra)
    end
  end
  # Lines 17, 18 and 19
  σ = 1
  D = exp(R[σ])*( e2*exp(-sep*(length(S)-σ-1)) + sum(S[σ:end] .*
    exp.(-d.d .* (0:(length(S)-σ))) .* (1 .- U[σ:end]) .^ ra) )
  T1 = (1 - U[σ])^ra * S[σ]
  T2 = U[σ]^ra * D
  T2 = Λ[σ] * (T1+T2)
  coal = false
  # Run chain 'forward'
  if T2 <= T1
    coal = true
    D = rand(Uniform())^rar * T1
  else
    D = T2
  end
  for i = 1:d.Δ
    T1 = (1 - lagU[i])^ra * lagS[i]
    T2 = lagU[i]^ra * D
    T2 = lagΛ[i] * (T1+T2)
    if T2 <= T1
      coal = true
      D = rand(Uniform())^rar * T1
    else
      D = T2
    end
  end
  # Line 20
  if coal # Coalescence!
    # Line 21
    return (D,σ)
  end # Line 22
  # Line 3 (second to last iterations)
  while true
    # Line 4 (Algorithm 3 with conditional probabilities)
    append!(S,chiStable2(dPos,d.δ,dega,dega2,mom,length(S)-σ-1))
    # Line 5
    while (length(R) == σ) || (length(S) >= length(C))
      t = length(C)-1
      # Lines 6 and 7
      (C1,F1) = downRW(d.d,rar,d.η,et1,d.κ,x-endC)
      append!(F,F1)
      append!(C,endC .+ C1)
      endC = C[end]
      # Lines 8 and 9
      if reflectedProcess(d.d,d.η,et1,d.κ,x-endC)
        # Line 10
        x = endC + d.κ
        R1 = [maximum(C[t:end])]
        for i = (t-1):-1:(length(R)+1)
          push!(R1,max(R1[end],C[i]))
        end
        append!(R,R1[end:-1:1] .- C[(length(R)+1):t])
      else # Line 11
        # Lines 12 and 13
        (C1,F1) = upRW(d.d,d.η,et1,d.κ,x-endC)
        append!(F,F1)
        append!(C,endC .+ C1)
        endC = C[end]
      end # Line 14
    end # Line 15
    # Line 16
    while length(U) < length(S)
      T = rand(Poisson(d.α*(1-d.ρ)*F[length(U)+1]))
      if T == 0
        push!(U,exp(-d.α*F[length(U)+1]))
        push!(Λ,1)
      else
        push!(U,exp(-d.α*F[length(U)+1]*rand(Beta(1,T))))
        push!(Λ,exp(-F[length(U)]/U[end])^ra)
      end
    end
    # Lines 17, 18 and 19
    σ += 1
    D = exp(R[σ])*( e2*exp(-sep*(length(S)-σ-1)) + sum(S[σ:end] .*
      exp.(-d.d .* (0:(length(S)-σ))) .* (1 .- U[σ:end]) .^ ra) )
    T1 = (1 - U[σ])^ra * S[σ]
    T2 = U[σ]^ra * D
    T2 = Λ[σ] * (T1+T2)
    # Line 24
    if T2 <= T1 # Coalescence!
      D = rand(Uniform())^rar * T1
      # Run chain 'forward'
      for i = (σ-1):-1:1
        T1 = (1 - U[i])^ra * S[i]
        T2 = U[i]^ra * D
        T2 = Λ[i] * (T1+T2)
        if T2 <= T1
          D = rand(Uniform())^rar * T1
        else
          D = T2
        end
      end
      for i = 1:d.Δ
        T1 = (1 - lagU[i])^ra * lagS[i]
        T2 = lagU[i]^ra * D
        T2 = lagΛ[i] * (T1+T2)
        if T2 <= T1
          D = rand(Uniform())^rar * T1
        else
          D = T2
        end
      end
      # Line 25
      return (D,σ)
    end # Line 26
  end # Line 27
end

# @Input: SupremumStable
# @Output: A random sample from a the law d
function rand(d::SupremumStable)
  return (β == -1 && α <= 1) ? 0. : rand(sampler(d))[1]
end

export SupremumStable, rand, sampler, PerfectSupremumStable, minimum, maximum, insupport, mean, params


text:
# FMM for Modified Stokes, based on FMM for Modified Biharmonic

include("MBHFMM2D.jl")

const DEFAULT_MAXNODES = 30
const DEFAULT_MAXBOXES = 100000
const DEFAULT_IPREC = 4

## STOKESLET #########################################################

function fmm_stokeslet_direct(src, targ, str, alpha)
    ns = size(src, 2)
    nt = size(targ, 2)
    u = zeros(2, nt)

    ifcharge = false
    ifdipole = false
    ifquad = true
    ifoct = false

    ifpot = true
    ifgrad = false
    ifhess = false

    charge = Array{Float64}(0)
    dipstr = Array{Float64}(0)
    dipvec = Array{Float64}(2,0)
    quadstr = ones(ns)
    quadvec = Array{Float64}(3,ns)
    octstr = Array{Float64}(0)
    octvec = Array{Float64}(4,0)

    pottarg = Array{Float64}(nt)
    gradtarg = Array{Float64}(2,nt)
    hesstarg = Array{Float64}(3,nt)

    fmmpars = MBHFMM2DParams(alpha,src,targ,ifcharge, ifdipole,
                             ifquad, ifoct, charge, dipstr,
                             dipvec, quadstr, quadvec, octstr,
                             octvec, iprec = DEFAULT_IPREC, ifalltarg = false)

    for j=1:2
        ej = zeros(2)
        ej[j] = 1.0
        for i=1:ns
            f = str[:,i]
            quadvec[:, i] = f[j]*[1.0, 0.0, 1.0] - boxfmm2d_formquadvec(ej, f)
        end
        mbhfmm2d_direct!(fmmpars,targ,ifpot,pottarg,ifgrad,
                         gradtarg,ifhess,hesstarg)
        @. u[j, :] = pottarg
    end

    return u
end

function fmm_stokeslet_targ(src, targ, str, alpha;
                            maxnodes::Int=DEFAULT_MAXNODES,
                            maxboxes::Int=DEFAULT_MAXBOXES,
                            ifgrad::Bool=false)
    ns = size(src, 2)
    nt = size(targ, 2)
    u = Array{Float64}(2, nt)
    if ifgrad
        u1grad = Array{Float64}(2, nt)
        u2grad = Array{Float64}(2, nt)
    end

    ifcharge = false
    ifdipole = false
    ifquad = true
    ifoct = false

    ifpot = true
    ifhess = false

    charge = Array{Float64}(0)
    dipstr = Array{Float64}(0)
    dipvec = Array{Float64}(2,0)
    quadstr = ones(ns)
    quadvec = Array{Float64}(3,ns)
    octstr = Array{Float64}(0)
    octvec = Array{Float64}(4,0)

    pottarg = Array{Float64}(nt)
    gradtarg = Array{Float64}(2,0)
    hesstarg = Array{Float64}(3,0)

    fmmpars = MBHFMM2DParams(alpha,src,targ,ifcharge, ifdipole,
                             ifquad, ifoct, charge, dipstr,
                             dipvec, quadstr, quadvec, octstr,
                             octvec, iprec = DEFAULT_IPREC, ifalltarg = false)

    # Form tree
    tree, sorted_pts, ier = mbhfmm2d_tree(fmmpars, maxnodes=maxnodes, maxboxes=maxboxes)
    # Compute components
    for j=1:2
        ej = zeros(2)
        ej[j] = 1.0
        for i=1:ns
            f = str[:,i]
            quadvec[:, i] = f[j]*[1.0, 0.0, 1.0] - boxfmm2d_formquadvec(ej, f)
        end
        fmmstor = mbhfmm2d_form(fmmpars, tree, sorted_pts)
        if ifgrad
            gradtarg = (j==1 ? u1grad : u2grad)
        end
        mbhfmm2d_targ!(fmmpars,fmmstor,targ,ifpot,pottarg,ifgrad,
                       gradtarg,ifhess,hesstarg)
        @. u[j, :] = pottarg
    end
    if ifgrad
        return u, u1grad, u2grad
    else
        return u
    end
end

## STRESSLET #########################################################

function fmm_stresslet_direct(src, targ, fvec, nvec, alpha;
                              self::Bool=false,
                              ifgrad::Bool=false)
    ns = size(src, 2)
    nt = size(targ, 2)
    u = zeros(2, nt)
    if ifgrad
        u1grad = Array{Float64}(2, nt)
        u2grad = Array{Float64}(2, nt)
    end

    ifcharge = false
    ifdipole = true
    ifquad = false
    ifoct = true

    ifpot = true
    ifhess = false

    charge = Array{Float64}(0)
    dipstr = ones(ns)
    dipvec = Array{Float64}(2,ns)
    quadstr = Array{Float64}(0)
    quadvec = Array{Float64}(3,0)
    octstr = ones(ns)
    octvec = Array{Float64}(4,ns)

    pottarg = Array{Float64}(nt)
    gradtarg = Array{Float64}(2,nt)
    hesstarg = Array{Float64}(3,nt)

    fmmpars = MBHFMM2DParams(alpha,src,targ,ifcharge, ifdipole,
                             ifquad, ifoct, charge, dipstr,
                             dipvec, quadstr, quadvec, octstr,
                             octvec, iprec = DEFAULT_IPREC, ifalltarg = false)
    for j=1:2
        fmm_stresslet_pack_density!(fmmpars, fvec, nvec, alpha, j)
        if ifgrad
            gradtarg = (j==1 ? u1grad : u2grad)
        end
        if self
            fmmdirect = mbhfmm2d_direct_self!(fmmpars,ifpot,pottarg,ifgrad,
                                              gradtarg,ifhess,hesstarg)
        else
            fmmdirect = mbhfmm2d_direct!(fmmpars,targ,ifpot,pottarg,ifgrad,
                                         gradtarg,ifhess,hesstarg)
        end
        u[j, :] = pottarg
    end
    if ifgrad
        return u, u1grad, u2grad
    else
        return u
    end
end

## FMM TARGET

function fmm_stresslet_targ(src, targ, fvec, nvec, alpha;
                            maxnodes::Int=DEFAULT_MAXNODES,
                            maxboxes::Int=DEFAULT_MAXBOXES,
                            ifgrad::Bool=false,
                            exrad=Float64[])
    fmmpars, tree, sorted_pts = fmm_stresslet_prep(src, targ, alpha,
                                                   maxnodes=maxnodes,
                                                   maxboxes=maxboxes,
                                                   exrad=exrad)
    u = fmm_stresslet_targ(fmmpars, tree, sorted_pts, fvec, nvec, alpha; ifgrad=ifgrad)
    return u
end

function fmm_stresslet_targ(fmmpars::MBHFMM2DParams,
                            tree::BoxTree2D,
                            sorted_pts::SortedPts2D,
                            fvec, nvec, alpha;
                            ifgrad::Bool=false)
    ns = sorted_pts.ns
    nt = sorted_pts.nt
    u = Array{Float64}(2, nt)
    if ifgrad
        u1grad = Array{Float64}(2, nt)
        u2grad = Array{Float64}(2, nt)
    end
    ifpot = true
    ifhess = false
    pottarg = Array{Float64}(nt)
    gradtarg = Array{Float64}(2,0)
    hesstarg = Array{Float64}(3,0)
    for j=1:2
        fmm_stresslet_pack_density!(fmmpars, fvec, nvec, alpha, j)
        fmmstor = mbhfmm2d_form(fmmpars, tree, sorted_pts)
        if ifgrad
            gradtarg = (j==1 ? u1grad : u2grad)
        end
        mbhfmm2d_targ!(fmmpars,fmmstor,fmmpars.targ,ifpot,pottarg,ifgrad,
                       gradtarg,ifhess,hesstarg)
        u[j, :] = pottarg
    end
    if ifgrad
        return u, u1grad, u2grad
    else
        return u
    end
end

## FMM SELF

function fmm_stresslet_self(src, fvec, nvec, alpha;
                            maxnodes::Int=DEFAULT_MAXNODES,
                            maxboxes::Int=DEFAULT_MAXBOXES)
    fmmpars, tree, sorted_pts = fmm_stresslet_prep(src, src, alpha,
                                                   maxnodes=maxnodes,
                                                   maxboxes=maxboxes)
    u = fmm_stresslet_self(fmmpars, tree, sorted_pts, fvec, nvec, alpha)
    return u
end

function fmm_stresslet_self(fmmpars::MBHFMM2DParams,
                            tree::BoxTree2D,
                            sorted_pts::SortedPts2D,
                            fvec, nvec, alpha)
    ns = sorted_pts.ns
    nt = sorted_pts.nt
    u = Array{Float64}(2, nt)
    ifpot = true
    ifgrad = false
    ifhess = false
    pottarg = Array{Float64}(nt)
    gradtarg = Array{Float64}(2,0)
    hesstarg = Array{Float64}(3,0)
    for j=1:2
        fmm_stresslet_pack_density!(fmmpars, fvec, nvec, alpha, j)
        fmmstor = mbhfmm2d_form(fmmpars, tree, sorted_pts)
        mbhfmm2d_srcsrc!(fmmpars,fmmstor,ifpot,pottarg,ifgrad,
                         gradtarg,ifhess,hesstarg)
        u[j, :] = pottarg
    end
    return u
end

## HELPERS

function fmm_stresslet_prep(src, targ, alpha;
                            maxnodes::Int=DEFAULT_MAXNODES,
                            maxboxes::Int=DEFAULT_MAXBOXES,
                            exrad=Float64[])

    ns = size(src, 2)
    nt = size(targ, 2)

    ifcharge = false
    ifdipole = true
    ifquad = false
    ifoct = true

    charge = Array{Float64}(0)
    dipstr = ones(ns)
    dipvec = Array{Float64}(2,ns)
    quadstr = Array{Float64}(0)
    quadvec = Array{Float64}(3,0)
    octstr = ones(ns)
    octvec = Array{Float64}(4,ns)

    fmmpars = MBHFMM2DParams(alpha,src,targ,ifcharge, ifdipole,
                             ifquad, ifoct, charge, dipstr,
                             dipvec, quadstr, quadvec, octstr,
                             octvec, iprec = DEFAULT_IPREC, ifalltarg = false,
                             exrad = exrad)

    tree, sorted_pts, ier = mbhfmm2d_tree(fmmpars, maxnodes=maxnodes, maxboxes=maxboxes, exrad=exrad)
    return fmmpars, tree, sorted_pts
end

function fmm_stresslet_pack_density!(fmmpars, fvec, nvec, alpha, component)
    j = component
    ns = size(fvec, 2)
    ej = zeros(2)
    ej[j] = 1.0
    for i=1:ns
        f = fvec[:, i]
        n = nvec[:, i]
        fdotn = f[1]*n[1] + f[2]*n[2]
        fmmpars.octvec[:,i] = ( f[j]*[n[1], n[2], n[1], n[2]] +
                                n[j]*[f[1], f[2], f[1], f[2]] +
                                fdotn*[ej; ej] ) +
                                -2*boxfmm2d_formoctvec(ej, f, n)
        fmmpars.dipvec[:,i] = -alpha^2*fdotn*ej
    end
end


text:
using Fermionic
using SparseArrays
using Test

@testset "Fermionic.jl" begin
    @test ssp(State(spzeros(16), Op(4))) == 0
    @test ssp(State([0,0,0,1/sqrt(2),0,0,0,0,0,0,0,0,1/sqrt(2),0,0,0],Op(4))) == 1.0
    @test ssp(State([0,0,0,im/sqrt(2),0,0,0,0,0,0,0,0,1/sqrt(2),0,0,0],Op(4))) == 1.0
    @test ssp(State(1/sqrt(2)*(im*ad(Op(4),1)*ad(Op(4),2)+ad(Op(4),3)*ad(Op(4),4))*vacuum(Op(4)),Op(4))) == 1.0
    @test ssp(State_fixed(1/sqrt(2)*[1,0,0,0,0,1],Op_fixed(4,2))) == 1.0
    @test ssp(State_fixed(1/sqrt(2)*[1,0,0,0,0,im],Op_fixed(4,2))) == 1.0
    @test ssp(State_fixed(1/sqrt(2)*[1,0,0,0,0,1],Op_fixed(4,2))) == 1.0
    @test ssp(State_fixed(spzeros(6),Op_fixed(4,2))) == 0
    @test ssp(State_fixed(SparseVector(sparse([1,6],[1,1],[1/sqrt(2),im/sqrt(2)])),Op_fixed(4,2))) == 1.0
    @test sqsp(State(spzeros(16), Op(4))) == 0
    @test sqsp(State([0,0,0,1/sqrt(2),0,0,0,0,0,0,0,0,1/sqrt(2),0,0,0],Op(4))) == 1.0
    @test sqsp(State([0,0,0,im/2,0,0,0,0,0,0,0,0,sqrt(3)/2,0,0,0],Op(4))) == 0.8112781244591327
    @test sqsp(State(1/sqrt(2)*(im*ad(Op(4),1)*ad(Op(4),2)+ad(Op(4),3)*ad(Op(4),4))*vacuum(Op(4)),Op(4))) == 1
    @test majorization_sp(State([0,0,0,im/2,0,0,0,0,0,0,0,0,sqrt(3)/2,0,0,0],Op(4)),State([0,0,0,im/2,0,0,0,0,0,0,0,0,sqrt(3)/2,0,0,0],Op(4))) == 0
    @test majorization_qsp(State([0,0,0,im/2,0,0,0,0,0,0,0,0,sqrt(3)/2,0,0,0],Op(4)),State([0,0,0,im/sqrt(2),0,0,0,0,0,0,0,0,1/sqrt(2),0,0,0],Op(4))) == 1
    @test n_avg(State(1/sqrt(2)*(im*ad(Op(4),1)*ad(Op(4),2)+ad(Op(4),3)*ad(Op(4),4))*vacuum(Op(4)),Op(4))) == 2.0
    @test coef(State(1/sqrt(2)*(im*ad(Op(6),1)*ad(Op(6),2)*ad(Op(6),3)*ad(Op(6),4)+ad(Op(6),3)*ad(Op(6),4)*ad(Op(6),5)*ad(Op(6),6))*vacuum(Op(6)),Op(6)),2,5)[6,1] == round(1/sqrt(2),digits=5)
    @test coef(State_fixed(fixed_state(1/sqrt(2)*(ad(Op(6),1)*ad(Op(6),2)*ad(Op(6),3)*ad(Op(6),4)+ad(Op(6),3)*ad(Op(6),4)*ad(Op(6),5)*ad(Op(6),6))*vacuum(Op(6)),4),Op_fixed(6,4)),2,6)[13,10] == round(1/sqrt(2),digits=6)
    @test rhomd(State(1/sqrt(2)*(ad(Op(6),1)*ad(Op(6),2)*ad(Op(6),3)*ad(Op(6),4)+ad(Op(6),3)*ad(Op(6),4)*ad(Op(6),5)*ad(Op(6),6))*vacuum(Op(6)),Op(6)),2,5)[3,3] == 0.5
    @test rhomd(State(1/sqrt(2)*(im*ad(Op(6),1)*ad(Op(6),2)*ad(Op(6),3)*ad(Op(6),4)+ad(Op(6),3)*ad(Op(6),4)*ad(Op(6),5)*ad(Op(6),6))*vacuum(Op(6)),Op(6)),2,8)[3,3] == 0.5
    @test rhomd(State_fixed(fixed_state(1/sqrt(2)*(ad(Op(6),1)*ad(Op(6),2)*ad(Op(6),3)*ad(Op(6),4)+ad(Op(6),3)*ad(Op(6),4)*ad(Op(6),5)*ad(Op(6),6))*vacuum(Op(6)),4),Op_fixed(6,4)),2,7)[6,6] == 0.5
    @test rhomd(State_fixed(fixed_state(1/sqrt(2)*(im*ad(Op(6),1)*ad(Op(6),2)*ad(Op(6),3)*ad(Op(6),4)+ad(Op(6),3)*ad(Op(6),4)*ad(Op(6),5)*ad(Op(6),6))*vacuum(Op(6)),4),Op_fixed(6,4)),2,7)[1,1] == 0.5
    @test rhom(State_fixed(fixed_state(1/sqrt(2)*(im*ad(Op(6),1)*ad(Op(6),2)*ad(Op(6),3)*ad(Op(6),4)+ad(Op(6),3)*ad(Op(6),4)*ad(Op(6),5)*ad(Op(6),6))*vacuum(Op(6)),4),Op_fixed(6,4)),2,8)[1,15] == -0.5im
    @test rhom(State(1/sqrt(2)*(ad(Op(6),1)*ad(Op(6),2)*ad(Op(6),3)*ad(Op(6),4)+ad(Op(6),3)*ad(Op(6),4)*ad(Op(6),5)*ad(Op(6),6))*vacuum(Op(6)),Op(6)),2,7)[15,1] == 0.5
    @test rhom(State(1/sqrt(2)*(im*ad(Op(6),1)*ad(Op(6),2)*ad(Op(6),3)*ad(Op(6),4)+ad(Op(6),3)*ad(Op(6),4)*ad(Op(6),5)*ad(Op(6),6))*vacuum(Op(6)),Op(6)),2,7)[4,4] == 0.5
    @test rhom(State(1/sqrt(2)*(ad(Op(6),1)*ad(Op(6),2)*ad(Op(6),3)*ad(Op(6),4)+ad(Op(6),3)*ad(Op(6),4)*ad(Op(6),5)*ad(Op(6),6))*vacuum(Op(6)),Op(6)),2,4)[1,15] == 0.5
    @test rhom2(State_fixed(fixed_state(1/sqrt(2)*(im*ad(Op(6),1)*ad(Op(6),2)*ad(Op(6),3)*ad(Op(6),4)+ad(Op(6),3)*ad(Op(6),4)*ad(Op(6),5)*ad(Op(6),6))*vacuum(Op(6)),4),Op_fixed(6,4)))[1,15] == -0.5im
    @test trp(State(spzeros(16), Op(4)),[1])[1,1] == 0
    @test round(trp(State([0,0,0,1/sqrt(2),0,0,0,0,0,0,0,0,1/sqrt(2),0,0,0],Op(4)),[2,4])[2,2],digits=5) == 0.5
    @test round(trp(State([0,0,0,im/sqrt(2),0,0,0,0,0,0,0,0,1/sqrt(2),0,0,0],Op(4)),[1,4])[2,2],digits=5) == 0.5
    @test round(trp(State(1/sqrt(2)*(im*ad(Op(4),1)*ad(Op(4),2)+ad(Op(4),3)*ad(Op(4),4))*vacuum(Op(4)),Op(4)),[2,3])[2,2],digits=5) == 0.5
end


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

using AWS.Compat
using AWS.UUIDs
"""
    DescribeAffectedAccountsForOrganization()

Returns a list of accounts in the organization from AWS Organizations that are affected by the provided event. For more information about the different types of AWS Health events, see Event.  Before you can call this operation, you must first enable AWS Health to work with AWS Organizations. To do this, call the EnableHealthServiceAccessForOrganization operation from your organization's master account.  This API operation uses pagination. Specify the nextToken parameter in the next request to return more results.

# Required Parameters
- `eventArn`: The unique identifier for the event. Format: arn:aws:health:event-region::event/SERVICE/EVENT_TYPE_CODE/EVENT_TYPE_PLUS_ID . Example: Example: arn:aws:health:us-east-1::event/EC2/EC2_INSTANCE_RETIREMENT_SCHEDULED/EC2_INSTANCE_RETIREMENT_SCHEDULED_ABC123-DEF456

# Optional Parameters
- `maxResults`: The maximum number of items to return in one batch, between 10 and 100, inclusive.
- `nextToken`: If the results of a search are large, only a portion of the results are returned, and a nextToken pagination token is returned in the response. To retrieve the next batch of results, reissue the search request and include the returned token. When all results have been returned, the response does not contain a pagination token value.
"""

describe_affected_accounts_for_organization(eventArn; aws_config::AWSConfig=global_aws_config()) = health("DescribeAffectedAccountsForOrganization", Dict{String, Any}("eventArn"=>eventArn); aws_config=aws_config)
describe_affected_accounts_for_organization(eventArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = health("DescribeAffectedAccountsForOrganization", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("eventArn"=>eventArn), args)); aws_config=aws_config)

"""
    DescribeAffectedEntities()

Returns a list of entities that have been affected by the specified events, based on the specified filter criteria. Entities can refer to individual customer resources, groups of customer resources, or any other construct, depending on the AWS service. Events that have impact beyond that of the affected entities, or where the extent of impact is unknown, include at least one entity indicating this. At least one event ARN is required. Results are sorted by the lastUpdatedTime of the entity, starting with the most recent.  This API operation uses pagination. Specify the nextToken parameter in the next request to return more results.

# Required Parameters
- `filter`: Values to narrow the results returned. At least one event ARN is required.

# Optional Parameters
- `locale`: The locale (language) to return information in. English (en) is the default and the only supported value at this time.
- `maxResults`: The maximum number of items to return in one batch, between 10 and 100, inclusive.
- `nextToken`: If the results of a search are large, only a portion of the results are returned, and a nextToken pagination token is returned in the response. To retrieve the next batch of results, reissue the search request and include the returned token. When all results have been returned, the response does not contain a pagination token value.
"""

describe_affected_entities(filter; aws_config::AWSConfig=global_aws_config()) = health("DescribeAffectedEntities", Dict{String, Any}("filter"=>filter); aws_config=aws_config)
describe_affected_entities(filter, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = health("DescribeAffectedEntities", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("filter"=>filter), args)); aws_config=aws_config)

"""
    DescribeAffectedEntitiesForOrganization()

Returns a list of entities that have been affected by one or more events for one or more accounts in your organization in AWS Organizations, based on the filter criteria. Entities can refer to individual customer resources, groups of customer resources, or any other construct, depending on the AWS service. At least one event Amazon Resource Name (ARN) and account ID are required. Results are sorted by the lastUpdatedTime of the entity, starting with the most recent. Before you can call this operation, you must first enable AWS Health to work with AWS Organizations. To do this, call the EnableHealthServiceAccessForOrganization operation from your organization's master account.   This API operation uses pagination. Specify the nextToken parameter in the next request to return more results.

# Required Parameters
- `organizationEntityFilters`: A JSON set of elements including the awsAccountId and the eventArn.

# Optional Parameters
- `locale`: The locale (language) to return information in. English (en) is the default and the only supported value at this time.
- `maxResults`: The maximum number of items to return in one batch, between 10 and 100, inclusive.
- `nextToken`: If the results of a search are large, only a portion of the results are returned, and a nextToken pagination token is returned in the response. To retrieve the next batch of results, reissue the search request and include the returned token. When all results have been returned, the response does not contain a pagination token value.
"""

describe_affected_entities_for_organization(organizationEntityFilters; aws_config::AWSConfig=global_aws_config()) = health("DescribeAffectedEntitiesForOrganization", Dict{String, Any}("organizationEntityFilters"=>organizationEntityFilters); aws_config=aws_config)
describe_affected_entities_for_organization(organizationEntityFilters, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = health("DescribeAffectedEntitiesForOrganization", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("organizationEntityFilters"=>organizationEntityFilters), args)); aws_config=aws_config)

"""
    DescribeEntityAggregates()

Returns the number of entities that are affected by each of the specified events. If no events are specified, the counts of all affected entities are returned.

# Optional Parameters
- `eventArns`: A list of event ARNs (unique identifiers). For example: \"arn:aws:health:us-east-1::event/EC2/EC2_INSTANCE_RETIREMENT_SCHEDULED/EC2_INSTANCE_RETIREMENT_SCHEDULED_ABC123-CDE456\", \"arn:aws:health:us-west-1::event/EBS/AWS_EBS_LOST_VOLUME/AWS_EBS_LOST_VOLUME_CHI789_JKL101\"
"""

describe_entity_aggregates(; aws_config::AWSConfig=global_aws_config()) = health("DescribeEntityAggregates"; aws_config=aws_config)
describe_entity_aggregates(args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = health("DescribeEntityAggregates", args; aws_config=aws_config)

"""
    DescribeEventAggregates()

Returns the number of events of each event type (issue, scheduled change, and account notification). If no filter is specified, the counts of all events in each category are returned.  This API operation uses pagination. Specify the nextToken parameter in the next request to return more results.

# Required Parameters
- `aggregateField`: The only currently supported value is eventTypeCategory.

# Optional Parameters
- `filter`: Values to narrow the results returned.
- `maxResults`: The maximum number of items to return in one batch, between 10 and 100, inclusive.
- `nextToken`: If the results of a search are large, only a portion of the results are returned, and a nextToken pagination token is returned in the response. To retrieve the next batch of results, reissue the search request and include the returned token. When all results have been returned, the response does not contain a pagination token value.
"""

describe_event_aggregates(aggregateField; aws_config::AWSConfig=global_aws_config()) = health("DescribeEventAggregates", Dict{String, Any}("aggregateField"=>aggregateField); aws_config=aws_config)
describe_event_aggregates(aggregateField, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = health("DescribeEventAggregates", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("aggregateField"=>aggregateField), args)); aws_config=aws_config)

"""
    DescribeEventDetails()

Returns detailed information about one or more specified events. Information includes standard event data (Region, service, and so on, as returned by DescribeEvents), a detailed event description, and possible additional metadata that depends upon the nature of the event. Affected entities are not included. To retrieve those, use the DescribeAffectedEntities operation. If a specified event cannot be retrieved, an error message is returned for that event.

# Required Parameters
- `eventArns`: A list of event ARNs (unique identifiers). For example: \"arn:aws:health:us-east-1::event/EC2/EC2_INSTANCE_RETIREMENT_SCHEDULED/EC2_INSTANCE_RETIREMENT_SCHEDULED_ABC123-CDE456\", \"arn:aws:health:us-west-1::event/EBS/AWS_EBS_LOST_VOLUME/AWS_EBS_LOST_VOLUME_CHI789_JKL101\"

# Optional Parameters
- `locale`: The locale (language) to return information in. English (en) is the default and the only supported value at this time.
"""

describe_event_details(eventArns; aws_config::AWSConfig=global_aws_config()) = health("DescribeEventDetails", Dict{String, Any}("eventArns"=>eventArns); aws_config=aws_config)
describe_event_details(eventArns, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = health("DescribeEventDetails", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("eventArns"=>eventArns), args)); aws_config=aws_config)

"""
    DescribeEventDetailsForOrganization()

Returns detailed information about one or more specified events for one or more accounts in your organization. Information includes standard event data (Region, service, and so on, as returned by DescribeEventsForOrganization), a detailed event description, and possible additional metadata that depends upon the nature of the event. Affected entities are not included; to retrieve those, use the DescribeAffectedEntitiesForOrganization operation. Before you can call this operation, you must first enable AWS Health to work with AWS Organizations. To do this, call the EnableHealthServiceAccessForOrganization operation from your organization's master account. When you call the DescribeEventDetailsForOrganization operation, you specify the organizationEventDetailFilters object in the request. Depending on the AWS Health event type, note the following differences:   If the event is public, the awsAccountId parameter must be empty. If you specify an account ID for a public event, then an error message is returned. That's because the event might apply to all AWS accounts and isn't specific to an account in your organization.   If the event is specific to an account, then you must specify the awsAccountId parameter in the request. If you don't specify an account ID, an error message returns because the event is specific to an AWS account in your organization.    For more information, see Event.

# Required Parameters
- `organizationEventDetailFilters`: A set of JSON elements that includes the awsAccountId and the eventArn.

# Optional Parameters
- `locale`: The locale (language) to return information in. English (en) is the default and the only supported value at this time.
"""

describe_event_details_for_organization(organizationEventDetailFilters; aws_config::AWSConfig=global_aws_config()) = health("DescribeEventDetailsForOrganization", Dict{String, Any}("organizationEventDetailFilters"=>organizationEventDetailFilters); aws_config=aws_config)
describe_event_details_for_organization(organizationEventDetailFilters, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = health("DescribeEventDetailsForOrganization", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("organizationEventDetailFilters"=>organizationEventDetailFilters), args)); aws_config=aws_config)

"""
    DescribeEventTypes()

Returns the event types that meet the specified filter criteria. If no filter criteria are specified, all event types are returned, in no particular order.  This API operation uses pagination. Specify the nextToken parameter in the next request to return more results.

# Optional Parameters
- `filter`: Values to narrow the results returned.
- `locale`: The locale (language) to return information in. English (en) is the default and the only supported value at this time.
- `maxResults`: The maximum number of items to return in one batch, between 10 and 100, inclusive.
- `nextToken`: If the results of a search are large, only a portion of the results are returned, and a nextToken pagination token is returned in the response. To retrieve the next batch of results, reissue the search request and include the returned token. When all results have been returned, the response does not contain a pagination token value.
"""

describe_event_types(; aws_config::AWSConfig=global_aws_config()) = health("DescribeEventTypes"; aws_config=aws_config)
describe_event_types(args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = health("DescribeEventTypes", args; aws_config=aws_config)

"""
    DescribeEvents()

 Returns information about events that meet the specified filter criteria. Events are returned in a summary form and do not include the detailed description, any additional metadata that depends on the event type, or any affected resources. To retrieve that information, use the DescribeEventDetails and DescribeAffectedEntities operations. If no filter criteria are specified, all events are returned. Results are sorted by lastModifiedTime, starting with the most recent event.    When you call the DescribeEvents operation and specify an entity for the entityValues parameter, AWS Health might return public events that aren't specific to that resource. For example, if you call DescribeEvents and specify an ID for an Amazon Elastic Compute Cloud (Amazon EC2) instance, AWS Health might return events that aren't specific to that resource or service. To get events that are specific to a service, use the services parameter in the filter object. For more information, see Event.   This API operation uses pagination. Specify the nextToken parameter in the next request to return more results.

# Optional Parameters
- `filter`: Values to narrow the results returned.
- `locale`: The locale (language) to return information in. English (en) is the default and the only supported value at this time.
- `maxResults`: The maximum number of items to return in one batch, between 10 and 100, inclusive.
- `nextToken`: If the results of a search are large, only a portion of the results are returned, and a nextToken pagination token is returned in the response. To retrieve the next batch of results, reissue the search request and include the returned token. When all results have been returned, the response does not contain a pagination token value.
"""

describe_events(; aws_config::AWSConfig=global_aws_config()) = health("DescribeEvents"; aws_config=aws_config)
describe_events(args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = health("DescribeEvents", args; aws_config=aws_config)

"""
    DescribeEventsForOrganization()

Returns information about events across your organization in AWS Organizations. You can use thefilters parameter to specify the events that you want to return. Events are returned in a summary form and don't include the affected accounts, detailed description, any additional metadata that depends on the event type, or any affected resources. To retrieve that information, use the following operations:    DescribeAffectedAccountsForOrganization     DescribeEventDetailsForOrganization     DescribeAffectedEntitiesForOrganization    If you don't specify a filter, the DescribeEventsForOrganizations returns all events across your organization. Results are sorted by lastModifiedTime, starting with the most recent event.  For more information about the different types of AWS Health events, see Event. Before you can call this operation, you must first enable AWS Health to work with AWS Organizations. To do this, call the EnableHealthServiceAccessForOrganization operation from your organization's master AWS account.  This API operation uses pagination. Specify the nextToken parameter in the next request to return more results.

# Optional Parameters
- `filter`: Values to narrow the results returned.
- `locale`: The locale (language) to return information in. English (en) is the default and the only supported value at this time.
- `maxResults`: The maximum number of items to return in one batch, between 10 and 100, inclusive.
- `nextToken`: If the results of a search are large, only a portion of the results are returned, and a nextToken pagination token is returned in the response. To retrieve the next batch of results, reissue the search request and include the returned token. When all results have been returned, the response does not contain a pagination token value.
"""

describe_events_for_organization(; aws_config::AWSConfig=global_aws_config()) = health("DescribeEventsForOrganization"; aws_config=aws_config)
describe_events_for_organization(args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = health("DescribeEventsForOrganization", args; aws_config=aws_config)

"""
    DescribeHealthServiceStatusForOrganization()

This operation provides status information on enabling or disabling AWS Health to work with your organization. To call this operation, you must sign in as an IAM user, assume an IAM role, or sign in as the root user (not recommended) in the organization's master account.

"""

describe_health_service_status_for_organization(; aws_config::AWSConfig=global_aws_config()) = health("DescribeHealthServiceStatusForOrganization"; aws_config=aws_config)
describe_health_service_status_for_organization(args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = health("DescribeHealthServiceStatusForOrganization", args; aws_config=aws_config)

"""
    DisableHealthServiceAccessForOrganization()

Disables AWS Health from working with AWS Organizations. To call this operation, you must sign in as an AWS Identity and Access Management (IAM) user, assume an IAM role, or sign in as the root user (not recommended) in the organization's master AWS account. For more information, see Aggregating AWS Health events in the AWS Health User Guide. This operation doesn't remove the service-linked role (SLR) from the AWS master account in your organization. You must use the IAM console, API, or AWS Command Line Interface (AWS CLI) to remove the SLR. For more information, see Deleting a Service-Linked Role in the IAM User Guide.  You can also disable the organizational feature by using the Organizations DisableAWSServiceAccess API operation. After you call this operation, AWS Health stops aggregating events for all other AWS accounts in your organization. If you call the AWS Health API operations for organizational view, AWS Health returns an error. AWS Health continues to aggregate health events for your AWS account.

"""

disable_health_service_access_for_organization(; aws_config::AWSConfig=global_aws_config()) = health("DisableHealthServiceAccessForOrganization"; aws_config=aws_config)
disable_health_service_access_for_organization(args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = health("DisableHealthServiceAccessForOrganization", args; aws_config=aws_config)

"""
    EnableHealthServiceAccessForOrganization()

Calling this operation enables AWS Health to work with AWS Organizations. This applies a service-linked role (SLR) to the master account in the organization. To call this operation, you must sign in as an IAM user, assume an IAM role, or sign in as the root user (not recommended) in the organization's master account. For more information, see Aggregating AWS Health events in the AWS Health User Guide.

"""

enable_health_service_access_for_organization(; aws_config::AWSConfig=global_aws_config()) = health("EnableHealthServiceAccessForOrganization"; aws_config=aws_config)
enable_health_service_access_for_organization(args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = health("EnableHealthServiceAccessForOrganization", args; aws_config=aws_config)


text:
#
# utils-tests.jl -
#
# Test utility functions.
#
module TestingLazyAlgebraUtilities

using Random
using Test
using LazyAlgebra

@testset "Multipliers  " begin
    #
    # Tests for `promote_multiplier`.
    #
    let promote_multiplier = LazyAlgebra.promote_multiplier,
        types = (Float32, Float16, BigFloat, Float64, ComplexF32, ComplexF64),
        perms = randperm(length(types)), # prevent compilation-time optimization
        n = length(types)
        # The ≡ (or ===) operator is too restrictive, let's define our own
        # method to compare multipliers: they must have the same value and the
        # same type to be considered as identical.
        identical(a::T, b::T) where {T} = (a == b)
        identical(a, b) = false
        for i in 1:n
            T1 = types[perms[i]]
            T2 = types[perms[mod(i,   n) + 1]]
            T3 = types[perms[mod(i+1, n) + 1]]
            T4 = types[perms[mod(i+2, n) + 1]]
            A1 = zeros(T1, 1)
            A2 = zeros(T2, 2)
            A3 = zeros(T3, 3)
            A4 = zeros(T4, 4)
            for λ in (1, π, 2 - 1im)
                # Check with type arguments.
                @test identical(promote_multiplier(λ, T1),
                                convert(isa(λ, Complex) ?
                                        Complex{real(T1)} :
                                        real(T1), λ))
                @test identical(promote_multiplier(λ,T1,T2),
                                convert(isa(λ, Complex) ?
                                        Complex{real(promote_type(T1,T2))} :
                                        real(promote_type(T1,T2)), λ))
                @test identical(promote_multiplier(λ,T1,T2,T3),
                                convert(isa(λ, Complex) ?
                                        Complex{real(promote_type(T1,T2,T3))} :
                                        real(promote_type(T1,T2,T3)), λ))
                @test identical(promote_multiplier(λ,T1,T2,T3,T4),
                                convert(isa(λ, Complex) ?
                                        Complex{real(promote_type(T1,T2,T3,T4))} :
                                        real(promote_type(T1,T2,T3,T4)), λ))
                # Check with array arguments.
                @test identical(promote_multiplier(λ, A1),
                                convert(isa(λ, Complex) ?
                                        Complex{real(T1)} :
                                        real(T1), λ))
                @test identical(promote_multiplier(λ, A1, A2),
                                convert(isa(λ, Complex) ?
                                        Complex{real(promote_type(T1,T2))} :
                                        real(promote_type(T1,T2)), λ))
                @test identical(promote_multiplier(λ, A1, A2, A3),
                                convert(isa(λ, Complex) ?
                                        Complex{real(promote_type(T1,T2,T3))} :
                                        real(promote_type(T1,T2,T3)), λ))
                @test identical(promote_multiplier(λ, A1, A2, A3, A4),
                                convert(isa(λ, Complex) ?
                                        Complex{real(promote_type(T1,T2,T3,T4))} :
                                        real(promote_type(T1,T2,T3,T4)), λ))
            end
        end
        for T in (AbstractFloat, Real, Complex, Integer, Number, Unsigned)[randperm(6)]
            @test_throws ErrorException promote_multiplier(1, T)
        end
    end
end # testset

@testset "Miscellaneous" begin
    #
    # Tests for `to_tuple`.
    #
    let to_tuple = LazyAlgebra.to_tuple, x = randn(5)
        @test to_tuple(x) === (x...,)
        @test to_tuple(to_tuple(x)) === (x...,)
    end
end # testset

@testset "Messages     " begin
    #
    # Tests of message, etc.
    #
    let bad_argument = LazyAlgebra.bad_argument,
        bad_size = LazyAlgebra.bad_size,
        arguments_have_incompatible_axes = LazyAlgebra.arguments_have_incompatible_axes,
        operands_have_incompatible_axes = LazyAlgebra.operands_have_incompatible_axes,
        message = LazyAlgebra.message,
        warn = LazyAlgebra.warn,
        siz = (3,4,5)
        @test_throws ArgumentError bad_argument("argument must be nonnegative")
        @test_throws ArgumentError bad_argument("invalid size ", siz)
        @test_throws DimensionMismatch arguments_have_incompatible_axes()
        @test_throws DimensionMismatch operands_have_incompatible_axes()
        @test_throws DimensionMismatch bad_size("invalid size")
        @test_throws DimensionMismatch bad_size("invalid size ", siz)
        message("Info:", "array size ", siz; color=:magenta)
        message(stdout, "Info:", "array size ", siz; color=:yellow)
        warn("array size ", siz)
        warn(stdout, "Info:", "array size ", siz)
    end
end # testset

nothing

end # module