text:
export
    coordinated_strategy,
    modify_utilities,
    get_coordination_sense,
    select_action_and_signals,
    get_best_action_value,
    greedy_strategy
#=
This file contains the different strategies (i.e., algorithms) that
the uavs can use.
=#

#=
Description:
A strategy that uses a coordination table to decide which action to take.

Parameters:
- uav: the uav deciding which action it should take
- state: the current state of the system, which contains
    all variable information needed to optimally (given the
    constraints of the environment) decide which action to take
- utilities: the utilities of the different joint actions

Return Value:
- action: the action this uav should take, which is a float
- signals: the signals to send for both the current uav and other uav
- different_action: whether or not the coord table prevent a non coc action
=#
function coordinated_strategy(uav::UAV, state::State, utilities::Vector{Float64})
    # track whether the coordination table took a different action with this flag
    different_action = false

    # check if all the utilities are the same, in which case, take no action
    # this happens when we are in the "terminal" state of the table
    # i.e., one outside the bounds of the table
    if length(unique(utilities)) == 1
        action = COC_ACTION
        signals = [:no_signal, :no_signal]
    else
        # modify utilities based on signal
        modified_utilities = modify_utilities(uav, state, utilities)

        # get sense: :same_sense or :different_sense
        sense = get_coordination_sense(uav, state)

        # get action and signal
        prev_signals = state.signals
        action, signals = select_action_and_signals(uav, modified_utilities, sense, prev_signals)

        # check what the greedy action would be
        greedy_action_idx = indmax(utilities)
        greedy_action = uav.joint_actions[uav.uav_id, greedy_action_idx]

        if action == COC_ACTION && greedy_action != COC_ACTION
            different_action = true
        end

    end

    # return action and signals for both planes for the next timestep
    return action, signals, different_action
end

#=
Description:
Based on the coordination signals of the uavs, modifies utilities
that do not follow coordination signals to be -Inf, effectively
preventing the uav from taking this action.

Parameters:
- uav: the uav choosing an action
- state: state of the system
- utilities: the estimated q_values for the different joint_actions

Return Value:
- returns modified utility values that align with the coordination scheme
=#
function modify_utilities(uav::UAV, state::State, utilities::Vector{Float64})
    # if no signals emitted do not alter utilities
    # if the signal emitted was by this uav, then it should
    # not alter utilities because only one signal can be
    # active at a time
    if all(state.signals .== :no_signal)
        return utilities
    end

    if uav.is_policy_joint # joint policy
        # reaching this point means a signal was sent last
        # timestep that needs to be followed this timestep
        # signal is either :dont_turn_left or :dont_turn_right
        signal = state.signals[uav.uav_id]

        # go through each joint action adjusting value based on signal
        for aidx in 1:size(uav.joint_actions, 2)

            # determine whether the action for the current
            # uav in this joint action is right, left, or neither
            cur_uav_action = uav.joint_actions[uav.uav_id, aidx]

            # uav.actions[1 or 2] are right turns
            if cur_uav_action == uav.actions[1] || cur_uav_action == uav.actions[2]
                turn = :right

            # uav.actions[4 or 5] are left turns
            elseif cur_uav_action == uav.actions[4] || cur_uav_action == uav.actions[5]
                turn = :left

            # straight or coc
            else
                turn = :neither
            end

            # if the current uavs turn in this joint action
            # is in the direction it has been signalled not
            # to turn, then set that actions utility to 0
            if (turn == :right && signal == :dont_turn_right) ||
                    (turn == :left && signal == :dont_turn_left)
                utilities[aidx] = -Inf
            end
        end
    else # non-joint policy
        # reaching this point means a signal was sent last
        # timestep that needs to be followed this timestep
        # signal is either :dont_turn_left or :dont_turn_right
        signal = state.signals[uav.uav_id]

        # go through each joint action adjusting value based on signal
        for aidx in 1:length(uav.actions)

            # determine whether the action for the current
            # uav in this joint action is right, left, or neither

            # uav.actions[1 or 2] are right turns
            if aidx == 1 || aidx == 2
                turn = :right

            # uav.actions[4 or 5] are left turns
            elseif aidx == 4 || aidx == 5
                turn = :left

            # straight or coc
            else
                turn = :neither
            end

            # if the current uavs turn in this joint action
            # is in the direction it has been signalled not
            # to turn, then set that actions utility to 0
            if (turn == :right && signal == :dont_turn_right) ||
                    (turn == :left && signal == :dont_turn_left)
                utilities[aidx] = -Inf
            end
        end
    end

    return utilities
end

#=
Description:
Determines what sense to use in deciding action and signal

Parameters:
- uav: uav deciding what action and signal to execute
- state: state of the system

Return Value:
- sense: one of {-1 == different, +1 == same}
=#
function get_coordination_sense(uav::UAV, state::State)

    # otherwise use belief_state to decide which sense to use
    belief_state = get_belief_state(uav, state)

    # retrieve best sense from table
    sense = get_coordination_sense(uav.coordination_table, belief_state)

    return sense
end

#=
Description:
Choose an action for this uav and signals to send to the next timestep.

Parameters:
- uav: uav deciding which action to select
- utilities: the modified utilities for different actions
- sense: sense from coordination table
- prev_signals: the signals from the preceding timestep

Return Value:
- action: the action to take
- signals: the signals to send to the uavs at the next timestep
=#
function select_action_and_signals(uav::UAV, utilities::Vector{Float64},
            sense::Symbol, prev_signals::Array{Symbol})

    # alias this value for easier reference
    method = uav.action_selection_method

    # based on the method, select the way to accumulate across intruder actions
    # as well as the initial values of the dictionaries
    if method == "best"
        accumulator = max
    elseif method == "worst"
        accumulator = min
    elseif method == "average"
        accumulator = +
    else
        throw(ArgumentError("invalid action selection method $(method)"))
    end

    # create two dicts mapping actions to values
    # and initially populate with +infinity, -infinity, or 0
    # one for ownship going left and another for ownship going right
    ownship_left_action_values = Dict{Float64, Float64}()
    ownship_right_action_values = Dict{Float64, Float64}()

    # change process based on if the aircraft has a non-joint or joint policy
    if uav.is_policy_joint # joint policy
        # iterate over utilities populating dicts with values
        # enforce the coordination component here:
        # if the joint action is an invalid sense then skip it
        # because we can be sure that the other plane can be
        # prevented from taking that action
        for aidx in 1:size(uav.joint_actions, 2)
            own_action = uav.joint_actions[uav.uav_id, aidx]
            int_action = uav.joint_actions[get_other_uav_id(uav), aidx]
            action_sense = get_action_sense(own_action, int_action)

            # if the sense on this joint action is incorrect, then skip it
            if (sense != :neither_sense && action_sense != :neither_sense
                    && action_sense != sense)
                continue
            end

            # update the min value corresponding to this ownship action
            # if this action is _left_ or straight (including coc), then
            # that means it should go in the _left_ dict of the ownship
            if sign(own_action) == 1 || sign(own_action) == 0 || own_action == COC_ACTION

                if own_action in keys(ownship_left_action_values)
                ownship_left_action_values[own_action] =
                    accumulator(ownship_left_action_values[own_action], utilities[aidx])
                else
                ownship_left_action_values[own_action] = utilities[aidx]
                end
            end

            # update the min value corresponding to this ownship action
            # if this action is _right_ or straight (including coc), then
            # that means it should go in the _right_ dict of the ownship
            if sign(own_action) == -1 || sign(own_action) == 0 || own_action == COC_ACTION
                if own_action in keys(ownship_right_action_values)
                    ownship_right_action_values[own_action] =
                        accumulator(ownship_right_action_values[own_action], utilities[aidx])
                else
                    ownship_right_action_values[own_action] = utilities[aidx]
                end
            end
        end
    else
        # iterate over utilities populating dicts with values
        # dont have joint actions so just align with coordination messages
        # if the action is invalid then skip it
        for aidx in 1:length(uav.actions)
            own_action = uav.actions[aidx]

            # update the min value corresponding to this ownship action
            # if this action is _left_ or straight (including coc), then
            # that means it should go in the _left_ dict of the ownship
            if sign(own_action) == 1 || sign(own_action) == 0 || own_action == COC_ACTION

                if own_action in keys(ownship_left_action_values)
                ownship_left_action_values[own_action] =
                    accumulator(ownship_left_action_values[own_action], utilities[aidx])
                else
                ownship_left_action_values[own_action] = utilities[aidx]
                end
            end

            # update the min value corresponding to this ownship action
            # if this action is _right_ or straight (including coc), then
            # that means it should go in the _right_ dict of the ownship
            if sign(own_action) == -1 || sign(own_action) == 0 || own_action == COC_ACTION
                if own_action in keys(ownship_right_action_values)
                    ownship_right_action_values[own_action] =
                        accumulator(ownship_right_action_values[own_action], utilities[aidx])
                else
                    ownship_right_action_values[own_action] = utilities[aidx]
                end
            end
        end
    end

    # get the best action and the value of the worst action in each dict
    left_action, left_value = get_best_action_value(ownship_left_action_values, method)
    right_action, right_value = get_best_action_value(ownship_right_action_values, method)

    # comment on best case, with best action being straight for both:
    # the left value captures the max across intruder actions for straight
    # and so does the right value
    # so if one is greater than the other then we just take that signal (dlt or dlr)
    # if they are equal in value, then that means the best action for both was
    # straight + (straight or coc), in which case we either don't send a signal
    # or just propagate the signal from the previous timestep, which is accounted
    # for below in a separate if statement

    # left value greater
    if left_value > right_value
        own_action = left_action
        own_signal = :dont_turn_right
        int_signal = sense == :same_sense ? :dont_turn_right : :dont_turn_left

    # otherwise go with right action
    else
        own_action = right_action
        own_signal = :dont_turn_left
        int_signal = sense == :same_sense ? :dont_turn_left : :dont_turn_right
    end

    # if ownship action is straight and there was a previous coordination signal
    # then just propagate those signals
    # if there was not a previous signal then this does not come into play
    if own_action == 0.0 && (prev_signals[1] != :no_signal || prev_signals[2] != :no_signal)
        own_signal = prev_signals[1]
        int_signal = prev_signals[2]
    end

    # if coordination table gives neither sense then don't send signals
    if sense == :neither_sense || own_action == COC_ACTION
        own_signal = :no_signal
        int_signal = :no_signal
    end

    signals = [own_signal, int_signal]

    return own_action, signals
end

#=
Description:
Given a dictionary mapping actions to values, returns the best
action from the dictionary and the minimum value across actions
in the dictionary.

Parameters:
- action_value_dict: the dictionary to search for the best action

Return Values:
- best_action: best action
- return_value: value to be returned.
    best_case = value of best action
    worst_case = minimum value across the actions in the dict
    average_case = sum of values across the actions in the dict
=#
function get_best_action_value(action_value_dict::Dict{Float64, Float64},
            method::String)
    # choose actual action by going through dict and choosing action
    # that has either the largest value
    # in the best case, we just care what the max value is
    # in the worst case, we care what the min value across the dict is
    # in the average case, we care what the expected value across the dict is
    best_action = COC_ACTION
    max_value = -Inf
    min_value = Inf
    avg_value = 0
    for action in keys(action_value_dict)
        cur_value = action_value_dict[action]

        # best case
        if cur_value > max_value
            best_action = action
            max_value = cur_value
        end

        # worst case
        if cur_value < min_value
            min_value = cur_value
        end

        # average case
        avg_value += cur_value
    end

    # choose which value to return
    return_value = max_value

    return best_action, return_value
end

#=
Description:
A strategy that determines the optimal joint action
independently from the other uavs.

Parameters:
- uav: the uav deciding which action it should take
- state: the current state of the system
- utilities: the utilities of the different joint actions

Return Value:
- action: the action this uav should take, which is a float
- signals: the signals to send for both the current uav and other uav
- different_action: whether or not the coord table prevent a non coc action
=#
function greedy_strategy(uav::UAV, state::State, utilities::Vector{Float64})
    # track whether the actions changed due to coordination
    different_action = false

    # check if all the utilities are the same, in which case, take no action
    if length(unique(utilities)) == 1
        action = COC_ACTION
    else
        if uav.is_policy_joint # joint actions
            # always modify utilities in case this is the intruder
            # but will not impact anything if singals are both no_signal
            modified_utilities = modify_utilities(uav, state, utilities)
            best_action_idx = indmax(modified_utilities)
            action = uav.joint_actions[uav.uav_id, best_action_idx]

            # check what the greedy action would be
            greedy_action_idx = indmax(utilities)
            greedy_action = uav.joint_actions[uav.uav_id, greedy_action_idx]

            if action == COC_ACTION && greedy_action != COC_ACTION
                different_action = true
            end
        else # non joint actions
            # always modify utilities in case this is the intruder
            # but will not impact anything if singals are both no_signal
            modified_utilities = modify_utilities(uav, state, utilities)
            best_action_idx = indmax(modified_utilities)
            action = uav.actions[best_action_idx]

            # check what the greedy action would be
            greedy_action_idx = indmax(utilities)
            greedy_action = uav.actions[greedy_action_idx]

            if action == COC_ACTION && greedy_action != COC_ACTION
                different_action = true
            end
        end
    end

    # since this strategy does not use coordinated actions,
    # return no signals
    # return different_action to have same interface as
    # the coordinated strategy, as well as to wake intruder pilot
    # in the case that the ownship is running coordinated strategy
    # and intruder runs compliant greedy strategy
    return action, [:no_signal, :no_signal], different_action
end


text:
abstract type QuadratureRule end
abstract type NestedQuadratureRule <: QuadratureRule end
abstract type UnitNestedRule <: NestedQuadratureRule end
abstract type UnconstrainedNestedRule <: NestedQuadratureRule end

struct KronrodPatterson <: UnitNestedRule
#  nw::Dict{Int64,Tuple{Float64,Float64}}
  n::Dict{Int64,Float64}
  w::Dict{Int64,Float64}
  l::Int64
end
function KronrodPatterson(l::Int)
  @load Pkg.dir("SparseQuadratureGrids")*"/src/rules/KronrodPatterson/l_"*string(l)*".jld2" n w
  n::Dict{Int64,Float64}
  w::Dict{Int64,Float64}
  KronrodPatterson(n, w, l)
end
struct GenzKeister <: UnconstrainedNestedRule
#  nw::Dict{Int64,Tuple{Float64,Float64}}
  n::Dict{Int64,Float64}
  w::Dict{Int64,Float64}
  l::Int64
end
function GenzKeister(l::Int)
  @load Pkg.dir("SparseQuadratureGrids")*"/src/rules/GenzKeister/l_"*string(l)*".jld2" n w
  n::Dict{Int64,Float64}
  w::Dict{Int64,Float64}
  GenzKeister(n, w, l)
end
function delay_sequence(base_seq)
  seq = [1]
  pol_acc = 3
  seq_i = 2
  approx_pol_ac(x::Int) = round(Int, 3x/2+1/2)
  for i ∈ 2:length(base_seq)
    while approx_pol_ac(base_seq[i]) >= pol_acc
      push!(seq, base_seq[i])
      pol_acc += 2
    end
  end
  seq
end
default(::Type{q}) where q = throw("Default unimplemented for grid type " * string(q) * ".")
default(::Type{GenzKeister}) = [1, 3, 9, 19, 35, 103]
default(::Type{KronrodPatterson}) = [1, 3, 7, 15, 31, 63]
delayed(::Type{GenzKeister}, i::Int = 16) = [1, 3, 3, 9, 9, 9, 9, 19, 19, 19, 19, 19, 19, 19, 19, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103][1:i]
delayed(::Type{KronrodPatterson}, i::Int = 13) = [1, 3, 3, 7, 7, 7, 15, 15, 15, 15, 15, 15, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63][1:i]

function Base.isless(x::T, y::T) where {T <: NestedQuadratureRule}
  x.l < y.l
end

struct Δ{T <: NestedQuadratureRule}
  n::Dict{Int64,Float64}
  w::Dict{Int64,Float64}
end

function add_a_to_b(a::Dict{T,R}, b::Dict{T,R}) where {T, R <: Real}
  Dict{T,R}(i => b[i] + get(a, i, zero(R)) for i ∈ keys(b))
end
function Base.:-(x::T, y::T) where {T <: NestedQuadratureRule}
  if x.l >= y.l
    return Δ{T}(x.n, Dict{Int64, Float64}(i => x.w[i] - get(y.w, i, 0.0) for i ∈ keys(x.w)))
  else
    return Δ{T}(y.n, Dict{Int64, Float64}(i => get(x.w,i,0.0) - y.w[i] for i ∈ keys(y.w)))
  end
end
function Base.:+(x::Dict{T,R}, y::Dict{T,R}) where {T, R <: Real}
    Dict{T, R}(i => get(x, i, zero(R)) + get(y, i, zero(R)) for i ∈ keys(x) ∪ keys(y))
end
function Base.:+(x::Dict{T,R}...) where {T, R <: Real}
  Dict{T, R}(i => sum(get.(x, [i], zero(R))) for i ∈ union(keys.(x)...))
end
function Base.:+(x::T, y::T) where {T <: NestedQuadratureRule}
  x.l > y.l ? Δ{T}(x.n, add_a_to_b(y.w, x.w)) : Δ{T}(y.n, add_a_to_b(x.w, y.w))
end
function Base.:+(x::T...) where {T <: NestedQuadratureRule}
  max_q = maximum(x)
  Δ{T}(max_x.n, Dict{Int64, Float64}(i => sum(get.(x, [i], zero(R))) for i ∈ keys(max_x.w)))
end

ext: jl


text:
using PlotlyJS, Random, DSP, Dierckx, FileIO, JLD2

# This script makes the trace data to compare a step in the tine shifts

#ricker wavelet function
"""
ricker(omega)
returns Ricker wavelet

input:

    peak frequency   = 20 Hz
    sampling time    = 0.001 seconds
    number of points = 100;

output:
    s: ricker wavelet with length = number of points
    t: time
"""
function ricker(;f::Float64=20.0, n::Int64=100, dt::Float64=0.001, nargout::Bool=true)
    # Create the wavelet and shift in time if needed
    T = dt*(n-1);
    t = collect(0:dt:T);
    t0 = 1/f;
    tau = t.-t0;

    s = (1.0 .- tau.*tau.*f.^2*π.^2).*exp.(-tau.^2*π.^2*f.^2);

    if nargout
        trace = scatter(;x=t, y=s, mode="lines")
        layout = Layout(
            xaxis=attr(title="Time"),
            yaxis=attr(title="u"),
        )
        p=plot(trace, layout)
        display(p)
    end

    return (s, t)
end

# make Ricker wavelet

dt     = 0.05; # s
f      = 1.0; # Hz
w,tw = ricker(f=f, n=41, dt=dt, nargout=false);

## make random reflectivity sequence and convolve with Ricker

npts = 601; # length of time series

rng = MersenneTwister(20190603)
f    = randn(rng, Float64, npts);
u0   = conv(f,w)[1:npts]; # make waveform time series

## make time varying stretched + Noise
dvV = - 0.01 #dv over V [%] = dt over T, therfore dt = dvV * T

tvec  = collect(( 0:npts - 1 ) .* dt);
st   = tvec .* dvV
# add random noise (5 % of maximum st)
rng = MersenneTwister(20190603);
noise = randn(rng, Float64, npts);
noise = 0.05*maximum(abs.(st)).*(noise./maximum(abs.(st)))
st = st .+ noise;

tvec2 = tvec .+ st;

spl = Spline1D(tvec, u0)
u1 = spl(tvec2);

st = st;

@save "./StretchedData.jld2" dt u0 u1 st

if nargout

    #time shift curve

    function lineplot1()
        tr = scatter(;x=tvec, y=st, mode="lines", name="Timeshift")
        layout = Layout(
            xaxis=attr(title="Time"),
            yaxis=attr(title="Timeshift"),
        )
        plot(tr, layout)
    end

    function lineplot2()
        tr1 = scatter(;x=tvec, y=u0, mode="lines+markers", name="u0")
        tr2 = scatter(;x=tvec, y=u1, mode="lines+markers", name="u1")
        layout = Layout(
            xaxis=attr(title="Time"),
            yaxis=attr(title="Signal"),
        )
        plot([tr1, tr2], layout)
    end

    p = [lineplot1(), lineplot2()]

end


text:
using Base.Test
using PyCall
@pyimport os

println("finished loading PyCall")

function print_evalfile(fpath)
    path, fname = splitdir(fpath)
    println("EVALUATING ", fname, ":\n*************")
    result = evalfile(fpath)
    println("*************\n")
    return result
end

path, this_fname = splitdir(@__FILE__)

for fname in os.listdir(path)
    if endswith(fname, ".jl") && fname != this_fname
        print_evalfile("$path/$fname")
    end
end

max_stars_repo_name: floswald/JuliaByExample

max_issues_repo_name: floswald/JuliaByExample

max_forks_repo_name: floswald/JuliaByExample


text:
#=
Given an array of integers where every integer occurs three times except for one integer, which only occurs once, find and return the non-duplicated integer.

For example, given [6, 1, 3, 3, 3, 6, 6], return 1. Given [13, 19, 13, 13], return 19.

Do this in O(N) time and O(1) space.=
=#

using Test
include("Solutions/problem40_find_non_duplicated_int.jl")

@test nonduplicated([6, 1, 3, 3, 3, 6, 6]) == 1
@test nonduplicated([13, 19, 13, 13]) == 19

max_stars_repo_name: DominiqueCaron/daily-coding-problem

max_issues_repo_name: DominiqueCaron/daily-coding-problem

max_forks_repo_name: DominiqueCaron/daily-coding-problem


text:
"""
    splittext(s)

Split the text in string `s` into an array, but keep all the separators
attached to the preceding word.

!!! note

    this is copied from Luxor/text.jl
"""
function splittext(s::String)
    # split text into array, keeping all separators
    # hyphens stay with first word
    result = Array{String,1}()
    iobuffer = IOBuffer()
    for c in s
        if isspace(c)
            push!(result, String(take!(iobuffer)))
            iobuffer = IOBuffer()
        elseif c == '-' # hyphen splits words but needs keeping
            print(iobuffer, c)
            push!(result, String(take!(iobuffer)))
            iobuffer = IOBuffer()
        else
            print(iobuffer, c)
        end
    end
    push!(result, String(take!(iobuffer)))
    return result
end

"""
    splitlines(s, width = 80)

Split a given string into lines of width `80` characters.
"""
function splitlines(s, width = 80)
    words = splittext(s)
    lines = String[]
    current_line = String[]
    space_left = width
    for word in words
        word == "" && continue
        word_width = length(word)

        if space_left < word_width
            # start a new line
            push!(lines, strip(join(current_line)))
            current_line = String[]
            space_left = width
        end

        if endswith(word, "-")
            push!(current_line, word)
            space_left -= word_width
        else
            push!(current_line, word * " ")
            space_left -= word_width + 1
        end
    end
    isempty(current_line) || push!(lines, strip(join(current_line)))
    return lines
end

"""
    brief(text::String)

Use the first sentence as the brief description.
"""
function brief(text::String)
    index = findfirst(". ", text)
    if index === nothing
        index = findfirst(".", text)
    end

    if index === nothing
        return text
    else
        return text[1:first(index)]
    end
end


text:
module SupervisedLearning

export train!

using Reexport
@reexport using MLBase

include("common.jl")
include("state.jl")
include("classencoding.jl")
include("datasource.jl")
include("traininghistory.jl")
include("solver.jl")
include("supervisedmodel.jl")
include("empiricalrisks.jl")

end # module


text:
using MatrixColorings
#using ProfileView

# generate graph
n = 1000
A = sprand(n,n+1, 0.1)
bi = MatrixColorings.matrix2bipartie_graph(A)
bi = MatrixColorings.matrix2bipartie_graph(A)
# color graph
i=1
col = MatrixColorings.partial_dist2_coloring(bi,i)
@time col = MatrixColorings.partial_dist2_coloring(bi,i)
#ProfileView.view()

nothing


text:
int main() {
        if (true)
                return;
	;
        return 1;
}

max_stars_repo_name: carlostome/Javalette-Compiler

max_issues_repo_name: carlostome/Javalette-Compiler

max_forks_repo_name: carlostome/Javalette-Compiler


text:
@testset "$TEST $G" begin

adjmx1 = [0 1 0; 1 0 1; 0 1 0] # graph
adjmx2 = [0 1 0; 1 0 1; 1 1 0] # digraph
a1 = G(adjmx1)
a2 = DG(adjmx2)

distmx1 = EdgeMap(a1,[Inf 2.0 Inf; 2.0 Inf 4.2; Inf 4.2 Inf])
distmx2 = EdgeMap(a2,[Inf 2.0 Inf; 3.2 Inf 4.2; 5.5 6.1 Inf])

g4 = PathDiGraph(5, DG)
@test_throws ErrorException eccentricities(g4)
z = eccentricities(a1, distmx1)
@test z == [6.2, 4.2, 6.2]
@test maximum(z) == diameter(a1, distmx1) == 6.2
@test periphery(z) == periphery(a1, distmx1) == [1,3]
@test minimum(z) == radius(a1, distmx1) == 4.2
@test center(z) == center(a1, distmx1) == [2]

z = eccentricities(a2, distmx2)
@test z == [6.2, 4.2, 6.1]
@test maximum(z) == diameter(a2, distmx2) == 6.2
@test periphery(z) == periphery(a2, distmx2) == [1]
@test minimum(z) == radius(a2, distmx2) == 4.2
@test center(z) == center(a2, distmx2) == [2]
@test z[3] == eccentricity(a2, 3, distmx2)

end # testset


text:
const IntMatrix{w,T} = IntArray{w,T,2}

function IntMatrix{w,T}(m::Integer, n::Integer, mmap::Bool=false) where {w,T}
    return IntArray{w,T}((m, n), mmap)
end

function IntMatrix{w,T}(mmap::Bool=false) where {w,T}
    return IntArray{w,T}((0, 0), mmap)
end

function IntMatrix{w}(matrix::AbstractMatrix{T}) where {w,T}
    return IntArray{w,T,2}(matrix)
end

function Base.convert(::Type{IntMatrix{w}}, matrix::AbstractMatrix{T}) where {w,T}
    return convert(IntArray{w,T,2}, matrix)
end


text:
module Corners

export Corner, Wedge

using ..Elements
using ..Motions

"""
    Corner{N} <: Elements.Element

An immutable structure representing a corner (`N=1`)/wedge (`N=2`)

## Fields

- `σ::Real`: signed intensity
- `ν::Real`: interior angle factor (angle is νπ)
- `n₀::ComplexF64`: vector of bisector of interior angle
- `L::Real` : characteristic length of corner

## Constructors

- `Corner(σ,ν,θ)` : set up a corner with a bisector at angle `θ` and length `L=1`
- `Wedge(σ,ν,θ)`  : set up a wedge with a bisector at angle `θ` and length `L=1`
"""
struct Corner{N} <: Element
    σ::Real
    ν::Real
    n₀::ComplexF64
    L::Real
end

Corner(σ,ν,n₀,L) = Corner{1}(σ,ν,n₀,L)
Wedge(σ,ν,n₀,L) =  Corner{2}(σ,ν,n₀,L)

Corner(σ::Real,ν::Real,θ̄::Real) = Corner(σ,ν,exp(im*θ̄),1.0)
Wedge(σ::Real,ν::Real,θ̄::Real) = Wedge(σ,ν,exp(im*θ̄),1.0)

Elements.kind(::Corner) = Singleton
Elements.kind(::Type{Corner}) = Singleton

Base.angle(c::Corner) = angle(c.n₀)

function Elements.complexpotential(z::ComplexF64, c::Corner{N}) where {N}
    fact = exp(im*N*π/2)
    return fact*c.ν*c.σ*c.L^(1-1/c.ν).*(z*c.n₀').^(1/c.ν)
end

Elements.streamfunction(z::ComplexF64, c::Corner) = imag(complexpotential(z,c))

function Motions.induce_velocity(z::ComplexF64, c::Corner{N}, t) where {N}
    fact = exp(im*N*π/2)
    return conj(fact*c.σ*(z*c.n₀'/c.L).^(1/c.ν-1)*c.n₀')
end

end


text:
"""
GenX: An Configurable Capacity Expansion Model
Copyright (C) 2021,  Massachusetts Institute of Technology
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
A complete copy of the GNU General Public License v2 (GPLv2) is available
in LICENSE.txt.  Users uncompressing this from an archive may not have
received this license file.  If not, see <http://www.gnu.org/licenses/>.
"""

function configure_settings(settings_path::String)

    settings = YAML.load(open(settings_path))

    # Optional settings parameters ############################################
    # Write the model formulation as an output: 0 = active | 1 = not active.
    if (!haskey(settings, "PrintModel"))
        settings["PrintModel"] = 0
    end
    # Transmission network expansionl: 0 = not active | 1 = active system wide.
    if (!haskey(settings, "NetworkExpansion"))
        settings["NetworkExpansion"] = 0
    end
    # Number of segments used in piecewise linear approximation of transmission losses: 1 = linear | >2 = piecewise quadratic.
    if (!haskey(settings, "Trans_Loss_Segments"))
        settings["Trans_Loss_Segments"] = 1
    end
    # Regulation (primary) and operating (secondary) reserves: 0 = not active, 1 = active system wide.
    if (!haskey(settings, "Reserves"))
        settings["Reserves"] = 0
    end
    # Minimum qualifying renewables penetration: 0 = not active | 1 = active system wide.
    if (!haskey(settings, "EnergyShareRequirement"))
        settings["EnergyShareRequirement"] = 0
    end
    # Number of capacity reserve margin constraints: 0 = not active | 1 = active system wide.
    if (!haskey(settings, "CapacityReserveMargin"))
        settings["CapacityReserveMargin"] = 0
    end
    # CO2 emissions cap; 0 = not active (no CO2 emission limit): 1 = mass-based emission limit constraint | 2 = load + rate-based emission limit constraint | 3 = generation + rate-based emission limit constraint.
    if (!haskey(settings, "CO2Cap"))
        settings["CO2Cap"] = 0
    end
    # Energy Share Requirement and CO2 constraints account for energy lost: 0 = not active (DO NOT account for energy lost) | 1 = active system wide (DO account for energy lost).
    if (!haskey(settings, "StorageLosses"))
        settings["StorageLosses"] = 1
    end
    # Activate minimum technology carveout constraints: 0 = not active | 1 = active.
    if (!haskey(settings, "MinCapReq"))
        settings["MinCapReq"] = 0
    end
    # Available solvers: Gurobi, CPLEX, Clp, Cbc, GLPK(testing)
    if (!haskey(settings, "Solver"))
        settings["Solver"] = "Gurobi"
    end
    # Turn on parameter scaling wherein load, capacity and power variables are defined in GW rather than MW: 0 = not active | 1 = active system wide.
    if (!haskey(settings, "ParameterScale"))
        settings["ParameterScale"] = 0
    end
    # Write shadow prices of LP or relaxed MILP: 0 = not active | 1 = active.
    if (!haskey(settings, "WriteShadowPrices"))
        settings["WriteShadowPrices"] = 0
    end
    # Unit committment of thermal power plants: 0 = not active | 1 = active using integer clustering | 2 = active using linearized clustering.
    if (!haskey(settings, "UCommit"))
        settings["UCommit"] = 0
    end
    # Sets temporal resolution of the model: 0 = single period to represent the full year, with first-last time step linked | 1 = multiple representative periods
    if (!haskey(settings, "OperationWrapping"))
        settings["OperationWrapping"] = 0
    end
    # Inter-period energy exchange for storage technologies: 0 = not active | 1 = active system wide.
    if (!haskey(settings, "LongDurationStorage"))
        settings["LongDurationStorage"] = 0
    end
    # Directory name where results from time domain reduction will be saved. If results already exist here, these will be used without running time domain reduction script again.
    if (!haskey(settings, "TimeDomainReductionFolder"))
        settings["TimeDomainReductionFolder"] = "TDR_Results"
    end
    # Time domain reduce (i.e. cluster) inputs based on Load_data.csv, Generators_variability.csv, and Fuels_data.csv; 0 = not active (use input data as provided); 0 = active (cluster input data, or use data that has already been clustered)
    if (!haskey(settings, "TimeDomainReduction"))
        settings["TimeDomainReduction"] = 0
    end
    # Modeling to generate alternatives: 0 = not active | 1 = active. Note: produces a single solution as output
    if (!haskey(settings, "ModelingToGenerateAlternatives"))
        settings["ModelingToGenerateAlternatives"] = 0
    end
    # Slack value as a fraction of least-cost objective in budget constraint used for evaluating alternative model solutions (positive float value).
    if (!haskey(settings, "ModelingtoGenerateAlternativeSlack"))
        settings["ModelingtoGenerateAlternativeSlack"] = 0.1
    end

    return settings
end

max_stars_repo_name: Betristor/LTESOM

max_issues_repo_name: Betristor/LTESOM

max_forks_repo_name: Betristor/LTESOM


text:
using Gadfly, RDatasets

set_default_plot_size(14cm, 8cm)

haireye = dataset("datasets","HairEyeColor")
palette = ["brown","blue","tan","green"]

plot(haireye, y=:Sex, x=:Freq, color=:Eye, ygroup=:Hair,
  Geom.subplot_grid(Geom.bar(position=:stack, orientation=:horizontal),
        Guide.ylabel(orientation=:vertical) ),
    Scale.color_discrete_manual(palette...),
    Guide.colorkey(title="Eye\ncolor"),
    Guide.ylabel("Hair color"), Guide.xlabel("Frequency")
)


text:
function _check_permutation_format(x::Vector{Vector{T}}) where {T}
    nothing
end
_check_permutation_format(x) = nothing

"""
    Permutation(args...)

This module mostly implements SymPy's [Permutation](http://docs.sympy.org/latest/modules/combinatorics/permutations.html) module.

A permuation can be represented in different ways. Here a permutation is a reaarangment of the values 0, 1, ..., n. For example, the mapping `0->2, 1->3, 2->0, 3->1` can be presented by a vector: `sigma = [2,3,0,1]` where `sigma[i] = j` when `i -> j`. Otheriwse, it can be presented as a product of cycles: `(0 2)(1 3)` which reads 0 goes to 2 which goes to 0 (wrapping) and 1 goes to 3 and 3 goes to 1.

Either representation can be passed through the `Permutation` constructor.

For the vector notation -- 0-based -- it is passed directly to the constructor:

```jldoctest permutations
julia> using SymPy

julia> p = Permutation([2,3,0,1])
(0 2)(1 3)

```

If a range describes a permutation, it can be used as well:

```jldoctest permutations
julia> id = Permutation(10:-1:0)
(0 10)(1 9)(2 8)(3 7)(4 6)

```

Cycle notation can more compactly describe a permuation, it can be passed in as a container of cycles specified through tuples or vectors:

```jldoctest permutations
julia>  p = Permutation([(0,2), (1,3)])
(0 2)(1 3)

```

The latter can be be expresed more quickly as

```jldoctest permutations
julia> p = Permutation(0,2)(1,3)
(0 2)(1 3)

```

This works as a single cycle can be passed to the `Permutation`
constructor with values separated by commas and the "call" method for
`Permuation` objects is overloaded: for a single argument, the mapping
`i -> j` is created (also the notation `i^p` returns this) *but* if
more than one argument is given, a cycle is created and multiplied on
the *right* by `p`, so that the above becomes `(0,2) * (1,3)`.

Here are two permutations forming the symmetries of square, naturally represented in the two ways:

```jldoctest permutations
julia> flip = Permutation([[0,1],[2,3]])  # or Permutation(0,1)(2,3)
(0 1)(2 3)

julia> rotate = Permutation([1,2,3,0])    # or Permutation(0,1,2,3) in cycle notation
(0 1 2 3)

```

Operations on permutations include:

* a function call, `p(i)` to recover `j` where `i -> j`, also `i^p`.
* `*` for multiplication. The convention is `(p*q)(i) = q(p(i))` or with the `^` notation: `i^(p*q) = (i^p)^q`.
* `+` for multiplication when `p` and `q` commute, where a check on commuting is performed.
* `inv` for the inverse permutation.
* `/`, where `p/q` is `p * inv(q)`.
* `p^n` for powers. We have `inv(p) = p^(-1)` and `p^order(p)` is the identity.
* `p^q` for conjugate, defined by `inv(q) * p * q`.

We can see that a flip is an involution through:

```jldoctest permutations
julia> flip^2  # the identity
()

```

whereas a rotation is not (as it has order 4)

```jldoctest permutations
julia> rotate * rotate
(0 2)(1 3)

julia> rotate.order()
4

```

These two operations do not commute:

```jldoctest permutations
julia> flip * rotate
(0 2)

```

```jldoctest permutations
julia> rotate * flip  # (1 3)
(1 3)

```

We can see this is the correct mapping `1 -> 3` with

```jldoctest permutations
julia> (1^rotate)^flip, 1^(rotate*flip), flip(rotate(1))
(3, 3, 3)

```

We can check that `flip` and `rotate^2` do commute:

```jldoctest permutations
julia> id = Permutation(3)   # (n) is the identify
()

julia> flip.commutator(rotate^2) == id
true

```

The conjugate for flip and rotate does the inverse of the flip, then rotates, then flips:

```jldoctest permutations
julia> rotate^flip
(0 3 2 1)

```

This is different than `flip^rotate`. As `flip` commutes with `rotate^2` this will return `rotate^2`:

```jldoctest permutations
julia> (rotate^2)^flip
(0 2)(1 3)

```

!!! note "Differences"
    There is no support currently for the `Cycle` class

"""
function Permutation(x; kwargs...)
    if typeof(x) <: UnitRange
        x = collect(x)
    end
    _check_permutation_format(x)
    SymPermutation(sympy.combinatorics.permutations.Permutation(x; kwargs...))
end
function Permutation(i, j, xs...; kwargs...)
    Permutation([vcat(i,j,xs...)]; kwargs...)
end
Permutation(;kwargs...) = SymPermutation(sympy.combinatorics.permutations.Permutation(; kwargs...))
export Permutation

# left right
# check commutative
*(p::SymPermutation, q::SymPermutation)::SymPermutation = PyCall.py"$p * $q"
+(p::SymPermutation, i::Integer)::SymPermutation = PyCall.py"$p + $i"
-(p::SymPermutation, i::Integer)::SymPermutation = PyCall.py"$p - $i"
^(p::SymPermutation, i::Integer)::SymPermutation = PyCall.py"$p**$i"
^(p::SymPermutation, i::Sym) = p^N(i)
^(i::Integer, p::SymPermutation) = p(i)   # python has i^p = p(i)
^(i::Sym, p::SymPermutation) = p(i)       # SymPy has i^p = p(i)
^(p::SymPermutation, q::SymPermutation)::SymPermutation  = PyCall.py"$p^$q" # conjugate
inv(p::SymPermutation)::SymPermutation = PyCall.py"$p**(-1)"
/(p::SymPermutation, q::SymPermutation)::SymPermutation = p * inv(q)
import Base: ~
~(p::SymPermutation) = SymPermutation(~(PyCall.PyObject(p)))
Base.inv(p::SymPermutation) = ~p

function +(p::SymPermutation, q::SymPermutation)::SymPermutation
    !is_Identity(commutator(p,q)) && throw(DomainError("p and q do not commute"))
    p * q
end

# evaluation p:i -> j
(p::SymPermutation)(i::Integer) = p.__pyobject__(i)
function (p::SymPermutation)(i::Integer, j::Integer, xs...)
    q = Permutation([vcat(i, j, xs...)])
    p * q
end
(p::SymPermutation)(v::Vector) = PyCall.py"$p($v)"
(p::SymPermutation)(s::String) = p([s[i:i] for i in eachindex(s)])

==(p::SymPermutation, q::SymPermutation) = PyCall.py"$p == $q"
hash(p::SymPermutation) = hash(array_form(p))

Base.length(p::SymPermutation) = p.length
Base.max(p::SymPermutation) = p.max
Base.min(p::SymPermutation) = p.min
rank(p::SymPermutation) = p.rank

## we want perms, not tuples
transpositions(p::SymPermutation) = map(x -> Permutation([x]), object_meth(p, :transpositions))
export transpositions

"""
    PermutationGroup()

Create Permutation group from group generators

A PermutationGroup is one generated by a collection of permutations.

Some pre-defined groups are built-in:

* `SymmetricgGroup(n)`: S_n or all symmetries of an n-gon
* `CyclicGroup`: the group Z_n
* `DihedralGroup`: Group formed by a flip and rotation
* `AlternativeGroup`: Subgroup of S_n of even elements
* `AbelianGroup`: Returns the direct product of cyclic groups with the given orders.

Differences:

* use `collect(generate(G))` in place of `list(G.generate())`

"""
PermutationGroup(args...; kwargs...) = combinatorics.perm_groups.PermutationGroup(args...; kwargs...)
export PermutationGroup

## Algebra therof
import Base: *
*(G1::SymPermutationGroup, G2::SymPermutationGroup)::SymPermutationGroup = PyCall.py"$G1*$G2"

## Indexing into group
Base.getindex(Gp::SymPermutationGroup, i::Int) = PyCall.py"$(Gp.__pyobject__)[$(i-1)]"  # 1-base

elements(gp::SymPermutationGroup) = [a for a in gp.elements]

Base.length(G::SymPermutationGroup) =  PyCall.py"len($(G.__pyobject__))"

"""
   occursin(x, G::SymPermutationGroup)

Does G contain x. (In SymPy, this is `contains.)
"""
Base.occursin(x, G::SymPermutationGroup; kwargs...) = (G.contains(x; kwargs...) == Sym(true)) # was contains


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

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

Accepts the specified grant.

# Arguments
- `grant_arn`: Amazon Resource Name (ARN) of the grant.

"""
accept_grant(GrantArn; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("AcceptGrant", Dict{String, Any}("GrantArn"=>GrantArn); aws_config=aws_config)
accept_grant(GrantArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("AcceptGrant", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("GrantArn"=>GrantArn), params)); aws_config=aws_config)

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

Checks in the specified license. Check in a license when it is no longer in use.

# Arguments
- `license_consumption_token`: License consumption token.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Beneficiary"`: License beneficiary.
"""
check_in_license(LicenseConsumptionToken; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("CheckInLicense", Dict{String, Any}("LicenseConsumptionToken"=>LicenseConsumptionToken); aws_config=aws_config)
check_in_license(LicenseConsumptionToken, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("CheckInLicense", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("LicenseConsumptionToken"=>LicenseConsumptionToken), params)); aws_config=aws_config)

"""
    checkout_borrow_license(client_token, digital_signature_method, entitlements, license_arn)
    checkout_borrow_license(client_token, digital_signature_method, entitlements, license_arn, params::Dict{String,<:Any})

Checks out the specified license for offline use.

# Arguments
- `client_token`: Unique, case-sensitive identifier that you provide to ensure the
  idempotency of the request.
- `digital_signature_method`: Digital signature method. The possible value is JSON Web
  Signature (JWS) algorithm PS384. For more information, see RFC 7518 Digital Signature with
  RSASSA-PSS.
- `entitlements`: License entitlements. Partial checkouts are not supported.
- `license_arn`: Amazon Resource Name (ARN) of the license. The license must use the borrow
  consumption configuration.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"CheckoutMetadata"`: Information about constraints.
- `"NodeId"`: Node ID.
"""
checkout_borrow_license(ClientToken, DigitalSignatureMethod, Entitlements, LicenseArn; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("CheckoutBorrowLicense", Dict{String, Any}("ClientToken"=>ClientToken, "DigitalSignatureMethod"=>DigitalSignatureMethod, "Entitlements"=>Entitlements, "LicenseArn"=>LicenseArn); aws_config=aws_config)
checkout_borrow_license(ClientToken, DigitalSignatureMethod, Entitlements, LicenseArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("CheckoutBorrowLicense", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ClientToken"=>ClientToken, "DigitalSignatureMethod"=>DigitalSignatureMethod, "Entitlements"=>Entitlements, "LicenseArn"=>LicenseArn), params)); aws_config=aws_config)

"""
    checkout_license(checkout_type, client_token, entitlements, key_fingerprint, product_sku)
    checkout_license(checkout_type, client_token, entitlements, key_fingerprint, product_sku, params::Dict{String,<:Any})

Checks out the specified license.

# Arguments
- `checkout_type`: Checkout type.
- `client_token`: Unique, case-sensitive identifier that you provide to ensure the
  idempotency of the request.
- `entitlements`: License entitlements.
- `key_fingerprint`: Key fingerprint identifying the license.
- `product_sku`: Product SKU.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Beneficiary"`: License beneficiary.
- `"NodeId"`: Node ID.
"""
checkout_license(CheckoutType, ClientToken, Entitlements, KeyFingerprint, ProductSKU; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("CheckoutLicense", Dict{String, Any}("CheckoutType"=>CheckoutType, "ClientToken"=>ClientToken, "Entitlements"=>Entitlements, "KeyFingerprint"=>KeyFingerprint, "ProductSKU"=>ProductSKU); aws_config=aws_config)
checkout_license(CheckoutType, ClientToken, Entitlements, KeyFingerprint, ProductSKU, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("CheckoutLicense", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("CheckoutType"=>CheckoutType, "ClientToken"=>ClientToken, "Entitlements"=>Entitlements, "KeyFingerprint"=>KeyFingerprint, "ProductSKU"=>ProductSKU), params)); aws_config=aws_config)

"""
    create_grant(allowed_operations, client_token, grant_name, home_region, license_arn, principals)
    create_grant(allowed_operations, client_token, grant_name, home_region, license_arn, principals, params::Dict{String,<:Any})

Creates a grant for the specified license. A grant shares the use of license entitlements
with specific AWS accounts.

# Arguments
- `allowed_operations`: Allowed operations for the grant.
- `client_token`: Unique, case-sensitive identifier that you provide to ensure the
  idempotency of the request.
- `grant_name`: Grant name.
- `home_region`: Home Region of the grant.
- `license_arn`: Amazon Resource Name (ARN) of the license.
- `principals`: The grant principals.

"""
create_grant(AllowedOperations, ClientToken, GrantName, HomeRegion, LicenseArn, Principals; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("CreateGrant", Dict{String, Any}("AllowedOperations"=>AllowedOperations, "ClientToken"=>ClientToken, "GrantName"=>GrantName, "HomeRegion"=>HomeRegion, "LicenseArn"=>LicenseArn, "Principals"=>Principals); aws_config=aws_config)
create_grant(AllowedOperations, ClientToken, GrantName, HomeRegion, LicenseArn, Principals, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("CreateGrant", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("AllowedOperations"=>AllowedOperations, "ClientToken"=>ClientToken, "GrantName"=>GrantName, "HomeRegion"=>HomeRegion, "LicenseArn"=>LicenseArn, "Principals"=>Principals), params)); aws_config=aws_config)

"""
    create_grant_version(client_token, grant_arn)
    create_grant_version(client_token, grant_arn, params::Dict{String,<:Any})

Creates a new version of the specified grant.

# Arguments
- `client_token`: Unique, case-sensitive identifier that you provide to ensure the
  idempotency of the request.
- `grant_arn`: Amazon Resource Name (ARN) of the grant.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"AllowedOperations"`: Allowed operations for the grant.
- `"GrantName"`: Grant name.
- `"SourceVersion"`: Current version of the grant.
- `"Status"`: Grant status.
"""
create_grant_version(ClientToken, GrantArn; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("CreateGrantVersion", Dict{String, Any}("ClientToken"=>ClientToken, "GrantArn"=>GrantArn); aws_config=aws_config)
create_grant_version(ClientToken, GrantArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("CreateGrantVersion", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ClientToken"=>ClientToken, "GrantArn"=>GrantArn), params)); aws_config=aws_config)

"""
    create_license(beneficiary, client_token, consumption_configuration, entitlements, home_region, issuer, license_name, product_name, product_sku, validity)
    create_license(beneficiary, client_token, consumption_configuration, entitlements, home_region, issuer, license_name, product_name, product_sku, validity, params::Dict{String,<:Any})

Creates a license.

# Arguments
- `beneficiary`: License beneficiary.
- `client_token`: Unique, case-sensitive identifier that you provide to ensure the
  idempotency of the request.
- `consumption_configuration`: Configuration for consumption of the license. Choose a
  provisional configuration for workloads running with continuous connectivity. Choose a
  borrow configuration for workloads with offline usage.
- `entitlements`: License entitlements.
- `home_region`: Home Region for the license.
- `issuer`: License issuer.
- `license_name`: License name.
- `product_name`: Product name.
- `product_sku`: Product SKU.
- `validity`: Date and time range during which the license is valid, in ISO8601-UTC format.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"LicenseMetadata"`: Information about the license.
"""
create_license(Beneficiary, ClientToken, ConsumptionConfiguration, Entitlements, HomeRegion, Issuer, LicenseName, ProductName, ProductSKU, Validity; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("CreateLicense", Dict{String, Any}("Beneficiary"=>Beneficiary, "ClientToken"=>ClientToken, "ConsumptionConfiguration"=>ConsumptionConfiguration, "Entitlements"=>Entitlements, "HomeRegion"=>HomeRegion, "Issuer"=>Issuer, "LicenseName"=>LicenseName, "ProductName"=>ProductName, "ProductSKU"=>ProductSKU, "Validity"=>Validity); aws_config=aws_config)
create_license(Beneficiary, ClientToken, ConsumptionConfiguration, Entitlements, HomeRegion, Issuer, LicenseName, ProductName, ProductSKU, Validity, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("CreateLicense", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Beneficiary"=>Beneficiary, "ClientToken"=>ClientToken, "ConsumptionConfiguration"=>ConsumptionConfiguration, "Entitlements"=>Entitlements, "HomeRegion"=>HomeRegion, "Issuer"=>Issuer, "LicenseName"=>LicenseName, "ProductName"=>ProductName, "ProductSKU"=>ProductSKU, "Validity"=>Validity), params)); aws_config=aws_config)

"""
    create_license_configuration(license_counting_type, name)
    create_license_configuration(license_counting_type, name, params::Dict{String,<:Any})

Creates a license configuration. A license configuration is an abstraction of a customer
license agreement that can be consumed and enforced by License Manager. Components include
specifications for the license type (licensing by instance, socket, CPU, or vCPU), allowed
tenancy (shared tenancy, Dedicated Instance, Dedicated Host, or all of these), license
affinity to host (how long a license must be associated with a host), and the number of
licenses purchased and used.

# Arguments
- `license_counting_type`: Dimension used to track the license inventory.
- `name`: Name of the license configuration.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Description"`: Description of the license configuration.
- `"DisassociateWhenNotFound"`: When true, disassociates a resource when software is
  uninstalled.
- `"LicenseCount"`: Number of licenses managed by the license configuration.
- `"LicenseCountHardLimit"`: Indicates whether hard or soft license enforcement is used.
  Exceeding a hard limit blocks the launch of new instances.
- `"LicenseRules"`: License rules. The syntax is #name=value (for example,
  #allowedTenancy=EC2-DedicatedHost). The available rules vary by dimension, as follows.
  Cores dimension: allowedTenancy | licenseAffinityToHost | maximumCores | minimumCores
  Instances dimension: allowedTenancy | maximumCores | minimumCores | maximumSockets |
  minimumSockets | maximumVcpus | minimumVcpus     Sockets dimension: allowedTenancy |
  licenseAffinityToHost | maximumSockets | minimumSockets     vCPUs dimension: allowedTenancy
  | honorVcpuOptimization | maximumVcpus | minimumVcpus    The unit for licenseAffinityToHost
  is days and the range is 1 to 180. The possible values for allowedTenancy are EC2-Default,
  EC2-DedicatedHost, and EC2-DedicatedInstance. The possible values for honorVcpuOptimization
  are True and False.
- `"ProductInformationList"`: Product information.
- `"Tags"`: Tags to add to the license configuration.
"""
create_license_configuration(LicenseCountingType, Name; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("CreateLicenseConfiguration", Dict{String, Any}("LicenseCountingType"=>LicenseCountingType, "Name"=>Name); aws_config=aws_config)
create_license_configuration(LicenseCountingType, Name, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("CreateLicenseConfiguration", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("LicenseCountingType"=>LicenseCountingType, "Name"=>Name), params)); aws_config=aws_config)

"""
    create_license_version(client_token, consumption_configuration, entitlements, home_region, issuer, license_arn, license_name, product_name, status, validity)
    create_license_version(client_token, consumption_configuration, entitlements, home_region, issuer, license_arn, license_name, product_name, status, validity, params::Dict{String,<:Any})

Creates a new version of the specified license.

# Arguments
- `client_token`: Unique, case-sensitive identifier that you provide to ensure the
  idempotency of the request.
- `consumption_configuration`: Configuration for consumption of the license. Choose a
  provisional configuration for workloads running with continuous connectivity. Choose a
  borrow configuration for workloads with offline usage.
- `entitlements`: License entitlements.
- `home_region`: Home Region of the license.
- `issuer`: License issuer.
- `license_arn`: Amazon Resource Name (ARN) of the license.
- `license_name`: License name.
- `product_name`: Product name.
- `status`: License status.
- `validity`: Date and time range during which the license is valid, in ISO8601-UTC format.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"LicenseMetadata"`: Information about the license.
- `"SourceVersion"`: Current version of the license.
"""
create_license_version(ClientToken, ConsumptionConfiguration, Entitlements, HomeRegion, Issuer, LicenseArn, LicenseName, ProductName, Status, Validity; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("CreateLicenseVersion", Dict{String, Any}("ClientToken"=>ClientToken, "ConsumptionConfiguration"=>ConsumptionConfiguration, "Entitlements"=>Entitlements, "HomeRegion"=>HomeRegion, "Issuer"=>Issuer, "LicenseArn"=>LicenseArn, "LicenseName"=>LicenseName, "ProductName"=>ProductName, "Status"=>Status, "Validity"=>Validity); aws_config=aws_config)
create_license_version(ClientToken, ConsumptionConfiguration, Entitlements, HomeRegion, Issuer, LicenseArn, LicenseName, ProductName, Status, Validity, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("CreateLicenseVersion", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ClientToken"=>ClientToken, "ConsumptionConfiguration"=>ConsumptionConfiguration, "Entitlements"=>Entitlements, "HomeRegion"=>HomeRegion, "Issuer"=>Issuer, "LicenseArn"=>LicenseArn, "LicenseName"=>LicenseName, "ProductName"=>ProductName, "Status"=>Status, "Validity"=>Validity), params)); aws_config=aws_config)

"""
    create_token(client_token, license_arn)
    create_token(client_token, license_arn, params::Dict{String,<:Any})

Creates a long-lived token. A refresh token is a JWT token used to get an access token.
With an access token, you can call AssumeRoleWithWebIdentity to get role credentials that
you can use to call License Manager to manage the specified license.

# Arguments
- `client_token`: Idempotency token, valid for 10 minutes.
- `license_arn`: Amazon Resource Name (ARN) of the license. The ARN is mapped to the aud
  claim of the JWT token.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"ExpirationInDays"`: Token expiration, in days, counted from token creation. The default
  is 365 days.
- `"RoleArns"`: Amazon Resource Name (ARN) of the IAM roles to embed in the token. License
  Manager does not check whether the roles are in use.
- `"TokenProperties"`: Data specified by the caller to be included in the JWT token. The
  data is mapped to the amr claim of the JWT token.
"""
create_token(ClientToken, LicenseArn; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("CreateToken", Dict{String, Any}("ClientToken"=>ClientToken, "LicenseArn"=>LicenseArn); aws_config=aws_config)
create_token(ClientToken, LicenseArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("CreateToken", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ClientToken"=>ClientToken, "LicenseArn"=>LicenseArn), params)); aws_config=aws_config)

"""
    delete_grant(grant_arn, version)
    delete_grant(grant_arn, version, params::Dict{String,<:Any})

Deletes the specified grant.

# Arguments
- `grant_arn`: Amazon Resource Name (ARN) of the grant.
- `version`: Current version of the grant.

"""
delete_grant(GrantArn, Version; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("DeleteGrant", Dict{String, Any}("GrantArn"=>GrantArn, "Version"=>Version); aws_config=aws_config)
delete_grant(GrantArn, Version, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("DeleteGrant", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("GrantArn"=>GrantArn, "Version"=>Version), params)); aws_config=aws_config)

"""
    delete_license(license_arn, source_version)
    delete_license(license_arn, source_version, params::Dict{String,<:Any})

Deletes the specified license.

# Arguments
- `license_arn`: Amazon Resource Name (ARN) of the license.
- `source_version`: Current version of the license.

"""
delete_license(LicenseArn, SourceVersion; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("DeleteLicense", Dict{String, Any}("LicenseArn"=>LicenseArn, "SourceVersion"=>SourceVersion); aws_config=aws_config)
delete_license(LicenseArn, SourceVersion, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("DeleteLicense", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("LicenseArn"=>LicenseArn, "SourceVersion"=>SourceVersion), params)); aws_config=aws_config)

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

Deletes the specified license configuration. You cannot delete a license configuration that
is in use.

# Arguments
- `license_configuration_arn`: ID of the license configuration.

"""
delete_license_configuration(LicenseConfigurationArn; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("DeleteLicenseConfiguration", Dict{String, Any}("LicenseConfigurationArn"=>LicenseConfigurationArn); aws_config=aws_config)
delete_license_configuration(LicenseConfigurationArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("DeleteLicenseConfiguration", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("LicenseConfigurationArn"=>LicenseConfigurationArn), params)); aws_config=aws_config)

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

Deletes the specified token. Must be called in the license home Region.

# Arguments
- `token_id`: Token ID.

"""
delete_token(TokenId; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("DeleteToken", Dict{String, Any}("TokenId"=>TokenId); aws_config=aws_config)
delete_token(TokenId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("DeleteToken", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("TokenId"=>TokenId), params)); aws_config=aws_config)

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

Extends the expiration date for license consumption.

# Arguments
- `license_consumption_token`: License consumption token.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"DryRun"`: Checks whether you have the required permissions for the action, without
  actually making the request. Provides an error response if you do not have the required
  permissions.
"""
extend_license_consumption(LicenseConsumptionToken; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("ExtendLicenseConsumption", Dict{String, Any}("LicenseConsumptionToken"=>LicenseConsumptionToken); aws_config=aws_config)
extend_license_consumption(LicenseConsumptionToken, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("ExtendLicenseConsumption", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("LicenseConsumptionToken"=>LicenseConsumptionToken), params)); aws_config=aws_config)

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

Gets a temporary access token to use with AssumeRoleWithWebIdentity. Access tokens are
valid for one hour.

# Arguments
- `token`: Refresh token, encoded as a JWT token.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"TokenProperties"`: Token properties to validate against those present in the JWT token.
"""
get_access_token(Token; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("GetAccessToken", Dict{String, Any}("Token"=>Token); aws_config=aws_config)
get_access_token(Token, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("GetAccessToken", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Token"=>Token), params)); aws_config=aws_config)

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

Gets detailed information about the specified grant.

# Arguments
- `grant_arn`: Amazon Resource Name (ARN) of the grant.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Version"`: Grant version.
"""
get_grant(GrantArn; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("GetGrant", Dict{String, Any}("GrantArn"=>GrantArn); aws_config=aws_config)
get_grant(GrantArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("GetGrant", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("GrantArn"=>GrantArn), params)); aws_config=aws_config)

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

Gets detailed information about the specified license.

# Arguments
- `license_arn`: Amazon Resource Name (ARN) of the license.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Version"`: License version.
"""
get_license(LicenseArn; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("GetLicense", Dict{String, Any}("LicenseArn"=>LicenseArn); aws_config=aws_config)
get_license(LicenseArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("GetLicense", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("LicenseArn"=>LicenseArn), params)); aws_config=aws_config)

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

Gets detailed information about the specified license configuration.

# Arguments
- `license_configuration_arn`: Amazon Resource Name (ARN) of the license configuration.

"""
get_license_configuration(LicenseConfigurationArn; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("GetLicenseConfiguration", Dict{String, Any}("LicenseConfigurationArn"=>LicenseConfigurationArn); aws_config=aws_config)
get_license_configuration(LicenseConfigurationArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("GetLicenseConfiguration", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("LicenseConfigurationArn"=>LicenseConfigurationArn), params)); aws_config=aws_config)

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

Gets detailed information about the usage of the specified license.

# Arguments
- `license_arn`: Amazon Resource Name (ARN) of the license.

"""
get_license_usage(LicenseArn; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("GetLicenseUsage", Dict{String, Any}("LicenseArn"=>LicenseArn); aws_config=aws_config)
get_license_usage(LicenseArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("GetLicenseUsage", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("LicenseArn"=>LicenseArn), params)); aws_config=aws_config)

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

Gets the License Manager settings for the current Region.

"""
get_service_settings(; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("GetServiceSettings"; aws_config=aws_config)
get_service_settings(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("GetServiceSettings", params; aws_config=aws_config)

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

Lists the resource associations for the specified license configuration. Resource
associations need not consume licenses from a license configuration. For example, an AMI or
a stopped instance might not consume a license (depending on the license rules).

# Arguments
- `license_configuration_arn`: Amazon Resource Name (ARN) of a license configuration.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"MaxResults"`: Maximum number of results to return in a single call.
- `"NextToken"`: Token for the next set of results.
"""
list_associations_for_license_configuration(LicenseConfigurationArn; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("ListAssociationsForLicenseConfiguration", Dict{String, Any}("LicenseConfigurationArn"=>LicenseConfigurationArn); aws_config=aws_config)
list_associations_for_license_configuration(LicenseConfigurationArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("ListAssociationsForLicenseConfiguration", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("LicenseConfigurationArn"=>LicenseConfigurationArn), params)); aws_config=aws_config)

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

Lists the grants distributed for the specified license.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Filters"`: Filters to scope the results. The following filters are supported:
  LicenseARN     Status     PrincipalARN     ParentARN
- `"GrantArns"`: Amazon Resource Names (ARNs) of the grants.
- `"MaxResults"`: Maximum number of results to return in a single call.
- `"NextToken"`: Token for the next set of results.
"""
list_distributed_grants(; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("ListDistributedGrants"; aws_config=aws_config)
list_distributed_grants(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("ListDistributedGrants", params; aws_config=aws_config)

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

Lists the license configuration operations that failed.

# Arguments
- `license_configuration_arn`: Amazon Resource Name of the license configuration.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"MaxResults"`: Maximum number of results to return in a single call.
- `"NextToken"`: Token for the next set of results.
"""
list_failures_for_license_configuration_operations(LicenseConfigurationArn; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("ListFailuresForLicenseConfigurationOperations", Dict{String, Any}("LicenseConfigurationArn"=>LicenseConfigurationArn); aws_config=aws_config)
list_failures_for_license_configuration_operations(LicenseConfigurationArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("ListFailuresForLicenseConfigurationOperations", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("LicenseConfigurationArn"=>LicenseConfigurationArn), params)); aws_config=aws_config)

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

Lists the license configurations for your account.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Filters"`: Filters to scope the results. The following filters and logical operators
  are supported:    licenseCountingType - The dimension on which licenses are counted.
  Possible values are vCPU | Instance | Core | Socket. Logical operators are EQUALS |
  NOT_EQUALS.    enforceLicenseCount - A Boolean value that indicates whether hard license
  enforcement is used. Logical operators are EQUALS | NOT_EQUALS.    usagelimitExceeded - A
  Boolean value that indicates whether the available licenses have been exceeded. Logical
  operators are EQUALS | NOT_EQUALS.
- `"LicenseConfigurationArns"`: Amazon Resource Names (ARN) of the license configurations.
- `"MaxResults"`: Maximum number of results to return in a single call.
- `"NextToken"`: Token for the next set of results.
"""
list_license_configurations(; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("ListLicenseConfigurations"; aws_config=aws_config)
list_license_configurations(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("ListLicenseConfigurations", params; aws_config=aws_config)

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

Describes the license configurations for the specified resource.

# Arguments
- `resource_arn`: Amazon Resource Name (ARN) of a resource that has an associated license
  configuration.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"MaxResults"`: Maximum number of results to return in a single call.
- `"NextToken"`: Token for the next set of results.
"""
list_license_specifications_for_resource(ResourceArn; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("ListLicenseSpecificationsForResource", Dict{String, Any}("ResourceArn"=>ResourceArn); aws_config=aws_config)
list_license_specifications_for_resource(ResourceArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("ListLicenseSpecificationsForResource", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ResourceArn"=>ResourceArn), params)); aws_config=aws_config)

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

Lists all versions of the specified license.

# Arguments
- `license_arn`: Amazon Resource Name (ARN) of the license.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"MaxResults"`: Maximum number of results to return in a single call.
- `"NextToken"`: Token for the next set of results.
"""
list_license_versions(LicenseArn; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("ListLicenseVersions", Dict{String, Any}("LicenseArn"=>LicenseArn); aws_config=aws_config)
list_license_versions(LicenseArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("ListLicenseVersions", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("LicenseArn"=>LicenseArn), params)); aws_config=aws_config)

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

Lists the licenses for your account.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Filters"`: Filters to scope the results. The following filters are supported:
  Beneficiary     ProductSKU     KeyFingerprint     Status
- `"LicenseArns"`: Amazon Resource Names (ARNs) of the licenses.
- `"MaxResults"`: Maximum number of results to return in a single call.
- `"NextToken"`: Token for the next set of results.
"""
list_licenses(; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("ListLicenses"; aws_config=aws_config)
list_licenses(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("ListLicenses", params; aws_config=aws_config)

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

Lists grants that are received but not accepted.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Filters"`: Filters to scope the results. The following filters are supported:
  LicenseARN     Status
- `"GrantArns"`: Amazon Resource Names (ARNs) of the grants.
- `"MaxResults"`: Maximum number of results to return in a single call.
- `"NextToken"`: Token for the next set of results.
"""
list_received_grants(; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("ListReceivedGrants"; aws_config=aws_config)
list_received_grants(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("ListReceivedGrants", params; aws_config=aws_config)

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

Lists received licenses.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Filters"`: Filters to scope the results. The following filters are supported:
  ProductSKU     Status     KeyFingerprint     Issuer
- `"LicenseArns"`: Amazon Resource Names (ARNs) of the licenses.
- `"MaxResults"`: Maximum number of results to return in a single call.
- `"NextToken"`: Token for the next set of results.
"""
list_received_licenses(; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("ListReceivedLicenses"; aws_config=aws_config)
list_received_licenses(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("ListReceivedLicenses", params; aws_config=aws_config)

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

Lists resources managed using Systems Manager inventory.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Filters"`: Filters to scope the results. The following filters and logical operators
  are supported:    account_id - The ID of the AWS account that owns the resource. Logical
  operators are EQUALS | NOT_EQUALS.    application_name - The name of the application.
  Logical operators are EQUALS | BEGINS_WITH.    license_included - The type of license
  included. Logical operators are EQUALS | NOT_EQUALS. Possible values are
  sql-server-enterprise | sql-server-standard | sql-server-web | windows-server-datacenter.
   platform - The platform of the resource. Logical operators are EQUALS | BEGINS_WITH.
  resource_id - The ID of the resource. Logical operators are EQUALS | NOT_EQUALS.
  tag:<key> - The key/value combination of a tag assigned to the resource. Logical
  operators are EQUALS (single account) or EQUALS | NOT_EQUALS (cross account).
- `"MaxResults"`: Maximum number of results to return in a single call.
- `"NextToken"`: Token for the next set of results.
"""
list_resource_inventory(; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("ListResourceInventory"; aws_config=aws_config)
list_resource_inventory(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("ListResourceInventory", params; aws_config=aws_config)

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

Lists the tags for the specified license configuration.

# Arguments
- `resource_arn`: Amazon Resource Name (ARN) of the license configuration.

"""
list_tags_for_resource(ResourceArn; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("ListTagsForResource", Dict{String, Any}("ResourceArn"=>ResourceArn); aws_config=aws_config)
list_tags_for_resource(ResourceArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("ListTagsForResource", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ResourceArn"=>ResourceArn), params)); aws_config=aws_config)

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

Lists your tokens.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Filters"`: Filters to scope the results. The following filter is supported:
  licenseArns
- `"MaxResults"`: Maximum number of results to return in a single call.
- `"NextToken"`: Token for the next set of results.
- `"TokenIds"`: Token IDs.
"""
list_tokens(; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("ListTokens"; aws_config=aws_config)
list_tokens(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("ListTokens", params; aws_config=aws_config)

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

Lists all license usage records for a license configuration, displaying license consumption
details by resource at a selected point in time. Use this action to audit the current
license consumption for any license inventory and configuration.

# Arguments
- `license_configuration_arn`: Amazon Resource Name (ARN) of the license configuration.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Filters"`: Filters to scope the results. The following filters and logical operators
  are supported:    resourceArn - The ARN of the license configuration resource. Logical
  operators are EQUALS | NOT_EQUALS.    resourceType - The resource type (EC2_INSTANCE |
  EC2_HOST | EC2_AMI | SYSTEMS_MANAGER_MANAGED_INSTANCE). Logical operators are EQUALS |
  NOT_EQUALS.    resourceAccount - The ID of the account that owns the resource. Logical
  operators are EQUALS | NOT_EQUALS.
- `"MaxResults"`: Maximum number of results to return in a single call.
- `"NextToken"`: Token for the next set of results.
"""
list_usage_for_license_configuration(LicenseConfigurationArn; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("ListUsageForLicenseConfiguration", Dict{String, Any}("LicenseConfigurationArn"=>LicenseConfigurationArn); aws_config=aws_config)
list_usage_for_license_configuration(LicenseConfigurationArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("ListUsageForLicenseConfiguration", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("LicenseConfigurationArn"=>LicenseConfigurationArn), params)); aws_config=aws_config)

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

Rejects the specified grant.

# Arguments
- `grant_arn`: Amazon Resource Name (ARN) of the grant.

"""
reject_grant(GrantArn; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("RejectGrant", Dict{String, Any}("GrantArn"=>GrantArn); aws_config=aws_config)
reject_grant(GrantArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("RejectGrant", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("GrantArn"=>GrantArn), params)); aws_config=aws_config)

"""
    tag_resource(resource_arn, tags)
    tag_resource(resource_arn, tags, params::Dict{String,<:Any})

Adds the specified tags to the specified license configuration.

# Arguments
- `resource_arn`: Amazon Resource Name (ARN) of the license configuration.
- `tags`: One or more tags.

"""
tag_resource(ResourceArn, Tags; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("TagResource", Dict{String, Any}("ResourceArn"=>ResourceArn, "Tags"=>Tags); aws_config=aws_config)
tag_resource(ResourceArn, Tags, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("TagResource", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ResourceArn"=>ResourceArn, "Tags"=>Tags), params)); aws_config=aws_config)

"""
    untag_resource(resource_arn, tag_keys)
    untag_resource(resource_arn, tag_keys, params::Dict{String,<:Any})

Removes the specified tags from the specified license configuration.

# Arguments
- `resource_arn`: Amazon Resource Name (ARN) of the license configuration.
- `tag_keys`: Keys identifying the tags to remove.

"""
untag_resource(ResourceArn, TagKeys; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("UntagResource", Dict{String, Any}("ResourceArn"=>ResourceArn, "TagKeys"=>TagKeys); aws_config=aws_config)
untag_resource(ResourceArn, TagKeys, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("UntagResource", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ResourceArn"=>ResourceArn, "TagKeys"=>TagKeys), params)); aws_config=aws_config)

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

Modifies the attributes of an existing license configuration.

# Arguments
- `license_configuration_arn`: Amazon Resource Name (ARN) of the license configuration.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Description"`: New description of the license configuration.
- `"DisassociateWhenNotFound"`: When true, disassociates a resource when software is
  uninstalled.
- `"LicenseConfigurationStatus"`: New status of the license configuration.
- `"LicenseCount"`: New number of licenses managed by the license configuration.
- `"LicenseCountHardLimit"`: New hard limit of the number of available licenses.
- `"LicenseRules"`: New license rule. The only rule that you can add after you create a
  license configuration is licenseAffinityToHost.
- `"Name"`: New name of the license configuration.
- `"ProductInformationList"`: New product information.
"""
update_license_configuration(LicenseConfigurationArn; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("UpdateLicenseConfiguration", Dict{String, Any}("LicenseConfigurationArn"=>LicenseConfigurationArn); aws_config=aws_config)
update_license_configuration(LicenseConfigurationArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("UpdateLicenseConfiguration", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("LicenseConfigurationArn"=>LicenseConfigurationArn), params)); aws_config=aws_config)

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

Adds or removes the specified license configurations for the specified AWS resource. You
can update the license specifications of AMIs, instances, and hosts. You cannot update the
license specifications for launch templates and AWS CloudFormation templates, as they send
license configurations to the operation that creates the resource.

# Arguments
- `resource_arn`: Amazon Resource Name (ARN) of the AWS resource.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"AddLicenseSpecifications"`: ARNs of the license configurations to add.
- `"RemoveLicenseSpecifications"`: ARNs of the license configurations to remove.
"""
update_license_specifications_for_resource(ResourceArn; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("UpdateLicenseSpecificationsForResource", Dict{String, Any}("ResourceArn"=>ResourceArn); aws_config=aws_config)
update_license_specifications_for_resource(ResourceArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("UpdateLicenseSpecificationsForResource", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ResourceArn"=>ResourceArn), params)); aws_config=aws_config)

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

Updates License Manager settings for the current Region.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"EnableCrossAccountsDiscovery"`: Activates cross-account discovery.
- `"OrganizationConfiguration"`: Enables integration with AWS Organizations for
  cross-account discovery.
- `"S3BucketArn"`: Amazon Resource Name (ARN) of the Amazon S3 bucket where the License
  Manager information is stored.
- `"SnsTopicArn"`: Amazon Resource Name (ARN) of the Amazon SNS topic used for License
  Manager alerts.
"""
update_service_settings(; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("UpdateServiceSettings"; aws_config=aws_config)
update_service_settings(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = license_manager("UpdateServiceSettings", params; aws_config=aws_config)


text:
abstract type AbstractBifurcationPoint end
abstract type AbstractBranchPoint <: AbstractBifurcationPoint end
abstract type AbstractSimpleBranchPoint <: AbstractBranchPoint end

istranscritical(bp::AbstractBranchPoint) = false
####################################################################################################
"""
$(TYPEDEF)

Structure to record a generic special (bifurcation) point.

$(TYPEDFIELDS)
"""
@with_kw struct SpecialPoint{T, Tp, Tv} <: AbstractBifurcationPoint
	"Bifurcation type, `:hopf, :bp...`."
	type::Symbol = :none

	"Index in `br.eig` (see [`ContResult`](@ref)) for which the bifurcation occurs."
	idx::Int64 = 0

	"Parameter value at the special (bifurcation) point, this is an estimate."
	param::T = 0.

	"Norm of the equilibrium at the special (bifurcation) point"
	norm::T  = 0.

	"`printsol = printSolution(x, param)` where `printSolution` is one of the arguments to [`continuation`](@ref)"
	printsol::Tp = 0.

	"Equilibrium at the special (bifurcation) point"
	x::Tv = Vector{T}(undef, 0)

	"Tangent along the branch at the special (bifurcation) point"
	tau::BorderedArray{Tv, T} = BorderedArray(x, T(0))

	"Eigenvalue index responsible for the special (bifurcation) (if applicable)"
	ind_ev::Int64 = 0

	"Continuation step at which the special (bifurcation) occurs"
	step::Int64 = 0

	"`status ∈ {:converged, :guess}` indicates whether the bisection algorithm was successful in detecting the special (bifurcation) point"
	status::Symbol = :guess

	"`δ = (δr, δi)` where δr indicates the change in the number of unstable eigenvalues and δi indicates the change in the number of unstable eigenvalues with nonzero imaginary part. `abs(δr)` is thus an estimate of the dimension of the kernel of the Jacobian at the special (bifurcation) point."
	δ::Tuple{Int64, Int64} = (0,0)

	"Precision in the location of the special (bifurcation) point"
	precision::T = -1

	"Interval containing the special (bifurcation) point"
	interval::Tuple{T, T} = (0, 0)
end

getVectorType(::Type{SpecialPoint{T, Tp, Tv}}) where {T, Tp, Tv} = Tv
type(bp::SpecialPoint) = bp.type

"""
$(SIGNATURES)

Return the dimension of the kernel of the special point.
"""
@inline kernelDim(bp::SpecialPoint) = abs(bp.δ[1])

# constructors
SpecialPoint(x0, T, printsol) = SpecialPoint(type = :none, idx = 0, param = T(0), norm  = T(0), printsol = namedprintsol(printsol), x = x0, tau = BorderedArray(x0, T(0)), ind_ev = 0, step = 0, status = :guess, δ = (0, 0), precision = T(-1), interval = (T(0), T(0)))

SpecialPoint(state::ContState, type::Symbol, status::Symbol, printsolution, normC, interval; ind_ev = 0, δ = (0,0), idx = state.step ) = SpecialPoint(
				type = type,
				idx = idx,
				param = getp(state),
				norm = normC(getx(state)),
				printsol = namedprintsol(printsolution(getx(state), getp(state))),
				x = _copy(getx(state)),
				tau = copy(state.tau),
				ind_ev = ind_ev,
				step = state.step,
				status = status,
				δ = δ,
				precision = abs(interval[2] - interval[1]),
				interval = interval)

function _show(io::IO, bp::SpecialPoint, ii::Int, p::String = "p")
	if bp.type == :none ; return; end
	if bp.status == :converged
		@printf(io, "- #%3i,\e[1;34m %5s\e[0m at %s ≈ %+4.8f ∈ (%+4.8f, %+4.8f), |δp|=%1.0e, [\e[1;32m%9s\e[0m], δ = (%2i, %2i), step = %3i, eigenelements in eig[%3i], ind_ev = %3i\n", ii, bp.type, p, bp.param, bp.interval..., bp.precision, bp.status, bp.δ..., bp.step, bp.idx, bp.ind_ev)
	else
		@printf(io, "- #%3i,\e[1;34m %5s\e[0m at %s ≈ %+4.8f ∈ (%+4.8f, %+4.8f), |δp|=%1.0e, [\e[1;31m%9s\e[0m], δ = (%2i, %2i), step = %3i, eigenelements in eig[%3i], ind_ev = %3i\n", ii, bp.type, p, bp.param, bp.interval..., bp.precision, bp.status, bp.δ..., bp.step, bp.idx, bp.ind_ev)
	end
end

####################################################################################################
# types for bifurcation point with 1d kernel for the jacobian

for op in (:Pitchfork, :Fold, :Transcritical)
	@eval begin
		"""
		$(TYPEDEF)

		$(TYPEDFIELDS)

		## Associated methods

		You can call `istranscritical(bp::AbstractSimpleBranchPoint), type(bp::AbstractSimpleBranchPoint)`

		## Predictor

		You can call `predictor(bp, ds; kwargs...)` on such bifurcation point `bp`
		to find the zeros of the normal form polynomials.
		"""
		mutable struct $op{Tv, T, Tpar, Tlens <: Lens, Tevl, Tevr, Tnf} <: AbstractSimpleBranchPoint
			"bifurcation point."
			x0::Tv

			"Parameter value at the bifurcation point."
			p::T

			"Parameters used by the vector field."
			params::Tpar

			"Parameter axis used to compute the branch on which this bifurcation point was detected."
			lens::Tlens

			"Right eigenvector(s)."
			ζ::Tevr

			"Left eigenvector(s)."
			ζstar::Tevl

			"Normal form coefficients."
			nf::Tnf

			"Type of bifurcation point"
			type::Symbol
		end
	end
end

Pitchfork(x0, p, params, lens, ζ, ζstar, nf) = Pitchfork(x0, p, params, lens, ζ, ζstar, nf, real(nf.b1) * real(nf.b3) < 0 ? :SuperCritical : :SubCritical)

isTranscritical(bp::AbstractSimpleBranchPoint) = bp isa Transcritical
type(bp::Pitchfork) = :Pitchfork
type(bp::Fold) = :Fold
type(bp::Transcritical) = :Transcritical
type(::Nothing) = nothing

function Base.show(io::IO, bp::AbstractBifurcationPoint)
	println(io, type(bp), " bifurcation point at ", getLensSymbol(bp.lens)," ≈ $(bp.p).")
	println(io, "Normal form: ", bp.nf)
end

function Base.show(io::IO, bp::Pitchfork) #a⋅(p - pbif) + x⋅(b1⋅(p - pbif) + b2⋅x/2 + b3⋅x^2/6)
	print(io, bp.type, " - ")
	println(io, type(bp), " bifurcation point at ", getLensSymbol(bp.lens)," ≈ $(bp.p).")
	println(io, "Normal form x⋅(b1⋅δp + b3⋅x²/6): \n", bp.nf)
end

####################################################################################################
# type for bifurcation point Nd kernel for the jacobian

"""
This is a type which holds information for the bifurcation points of equilibria with dim(Ker)>1.

$(TYPEDEF)

$(TYPEDFIELDS)

## Associated methods

You can call `type(bp::NdBranchPoint), length(bp::NdBranchPoint)`.

## Predictor

You can call `predictor(bp, ds)` on such bifurcation point `bp` to find the zeros of the normal form polynomials.

## Manipulating the normal form

- You can use `bp(Val(:reducedForm), x, p)` to evaluate the normal form polynomials on the vector `x` for (scalar) parameter `p`.

- You can use `bp(x, δp::Real)` to get the (large dimensional guess) associated to the low dimensional vector `x`. Note that we must have `length(x) == length(bp)`.

- You can use `BifurcationKit.nf(bp; kwargs...)` to pretty print the normal form with a string.
"""
mutable struct NdBranchPoint{Tv, T, Tpar, Tlens <: Lens, Tevl, Tevr, Tnf} <: AbstractBranchPoint
	"bifurcation point"
	x0::Tv

	"Parameter value at the bifurcation point"
	p::T

	"Parameters used by the vector field."
	params::Tpar

	"Parameter axis used to compute the branch on which this bifurcation point was detected."
	lens::Tlens

	"Right eigenvectors"
	ζ::Tevr

	"Left eigenvectors"
	ζstar::Tevl

	"Normal form coefficients"
	nf::Tnf

	"Type of bifurcation point"
	type::Symbol
end

type(bp::NdBranchPoint) = :NonSimpleBranchPoint
Base.length(bp::NdBranchPoint) = length(bp.ζ)

function Base.show(io::IO, bp::NdBranchPoint)
	println(io, "Non simple bifurcation point at ", getLensSymbol(bp.lens), " ≈ $(bp.p). \nKernel dimension = ", length(bp))
	println(io, "Normal form :")
	println(io, mapreduce(x -> x * "\n", *, nf(bp)) )
end
####################################################################################################
# type for Hopf bifurcation point

"""
$(TYPEDEF)

$(TYPEDFIELDS)

# Associated methods

## Predictor

You can call `predictor(bp::Hopf, ds)` on such bifurcation point `bp` to get the guess for the periodic orbit.
"""
mutable struct Hopf{Tv, T, Tω, Tpar, Tlens <: Lens, Tevr, Tevl, Tnf} <: AbstractSimpleBranchPoint
	"Hopf point"
	x0::Tv

	"Parameter value at the Hopf point"
	p::T

	"Frequency of the Hopf point"
	ω::Tω

	"Parameters used by the vector field."
	params::Tpar

	"Parameter axis used to compute the branch on which this Hopf point was detected."
	lens::Tlens

	"Right eigenvector"
	ζ::Tevr

	"Left eigenvector"
	ζstar::Tevl

	"Normal form coefficient ex: (a = 0., b = 1 + 1im)"
	nf::Tnf

	"Type of Hopf bifurcation"
	type::Symbol
end

type(bp::Hopf) = :Hopf
Hopf(x0, p, ω, params, lens, ζ, ζstar, nf) = Hopf(x0, p, ω, params, lens, ζ, ζstar, nf, real(nf.b1) * real(nb.b3) < 0 ? :SuperCritical : :SubCritical)

function Base.show(io::IO, bp::Hopf)
	print(io, bp.type, " - ")
	println(io, type(bp), " bifurcation point at ", getLensSymbol(bp.lens)," ≈ $(bp.p).")
	println(io, "Period of the periodic orbit ≈ ", (2pi/bp.ω))
	println(io, "Normal form z⋅(a⋅δp + b⋅|z|²): \n", bp.nf)
end


text:
# uses variables from setup_tests.jl

# check symmetry
@test srmgmkt.u_m ≈ srmgmkt.u_f #expected symmetry of singles

# check that supermodular surplus results in positive assortative matching
@test srmgmkt.α[1,1,1,1] + srmgmkt.α[end,end,end,end] >
      srmgmkt.α[1,1,end,end] + srmgmkt.α[end,end,1,1] #expected positive assortativity


text:
module Variable

import MathOptInterface
const MOI = MathOptInterface
const MOIU = MOI.Utilities
const MOIB = MOI.Bridges

import SumOfSquares
const SOS = SumOfSquares

include("psd2x2.jl")
include("scaled_diagonally_dominant.jl")
include("copositive_inner.jl")

end


text:
module ER

using Random: GLOBAL_RNG
using Distributions

function coin_flip(n, k, m, rng=GLOBAL_RNG)
    size = n^k
    p = m/size
    out = NTuple{k, Int}[]
    sizehint!(out, m+ceil(Integer,sqrt(m)))
    coin_flip_kernal(Iterators.product([1:n for _ in 1:k]...), rng, p, out)
    out
end
function coin_flip_kernal(iter, rng, p, out)
    for i in iter
        if rand(rng) < p
            push!(out, i)
        end
    end
    out
end

function grass_hop(n, k, m, rng=GLOBAL_RNG)
    size = n^k
    p = m/size
    out = Vector{Int}[]
    sizehint!(out, m+ceil(Integer,sqrt(m)))
    d = Geometric(p)
    i = ones(Int, k)
    i[1] = 0
    while true
        skip = rand(rng, d)+1
        j = 1
        while skip > 0
            if j > k
                return out
            end
            skip += i[j]
            i[j] = (skip-1)%n+1
            skip = (skip-1)÷n
            j += 1
        end
        push!(out, copy(i))
    end
end

end