text:
using Random
using DataFrames
using Distributions

export generate_simdata, simulate

"""
    generate_simdata(n::Integer)

Generate `n` simulation datasets returned in a `DataFrame`.
"""
function generate_simdata(Nlc::Integer)
    inclination = asin.(sqrt.(rand(Nlc)))
    ar = 10 .^ rand(Uniform(-2, 1), Nlc)
    clen = 10 .^ rand(Uniform(0, 1.6), Nlc)
    cover = 10 .^ rand(Uniform(-1, 0.5), Nlc)
    θ_low = rand(Uniform(0, 40), Nlc)
    θ_high = rand.(Uniform.(θ_low .+ 5, 80))
    period = 10 .^ rand(Uniform(-1, 2), Nlc)
    τ_evol = 10 .^ rand(Nlc)
    butterfly = Bool.(rand(Bernoulli(0.8), Nlc))
    Δω = 10 .^ rand(Uniform(-1, 0), Nlc)

    ω = 24.5 ./ period
    Δω .*= ω

    return DataFrame(
        ar = ar,
        clen = clen,
        cover = cover,
        inclination = inclination,
        θ_low = θ_low,
        θ_high = θ_high,
        period = period,
        ω = ω,
        Δω = Δω,
        τ_decay = τ_evol,
        butterfly = butterfly
    )
end

"""
    simulate(::DataFrameRow; duration=3650, cadence=30)

Given a row from a dataframe with simulation data, will simulate the lightcurve modulation over `duration` days every `cadence` minutes.
"""
function simulate(simrow::DataFrameRow; duration = 3650, cadence=30)
    spots = evolve(
            butterfly = simrow.butterfly,
            activity_rate = simrow.ar,
            cycle_length = simrow.clen,
            cycle_overlap = simrow.cover,
            max_ave_lat = simrow.θ_high,
            min_ave_lat = simrow.θ_low,
            tsim = duration)

    length(spots) == 0 && return zeros(length(0:cadence/1440:duration))

    S = SpotDynamics(spots;
        inclination = simrow.inclination,
        ω = simrow.ω,
        Δω = simrow.Δω,
        alpha_med = 3e-4sqrt(simrow.ar),
        τ_decay = simrow.τ_decay)

    return simulate(S, duration=duration, cadence=cadence)
end

"""
    simulate(::DataFrame; duration=3650, cadence=30)

Given a full dataframe with simulation data, will return a `Vector` of lightcurve modulations over `duration` days every `cadence` minutes.
"""
function simulate(simdata::DataFrame; duration=3650, cadence=30)
    dFs = []
    for row in eachrow(simdata)
        df = simulate(row, duration=duration, cadence=cadence)
        push!(dFs, df)
    end
    return dFs
end

"""
    simulate(::SpotDynamics; duration=3650, cadence=30)

Simulate the lightcurve modulation over `duration` days every `cadence` minutes.
"""
function simulate(r::SpotDynamics; duration=3650, cadence=30)
    t = 0:cadence/1440:duration
    dF = Vector{Float64}(undef, length(t))
    Threads.@threads for i in eachindex(t)
        @inbounds dF[i] = modulate(r, t[i])
    end
    return dF
end

max_stars_repo_name: zclaytor/butterpy

max_issues_repo_name: zclaytor/butterpy

max_forks_repo_name: zclaytor/butterpy


text:
module Skipped_Outer_Module

""
f_0() = ()

end

module PlainDocs

using Compat; import Compat.String

if VERSION < v"0.4-dev+4319"
    tup(args...) = tuple(args...)
else
    tup(args...) = Tuple{args...}
end

include(joinpath("PlainDocs", "functions.jl"))
include(joinpath("PlainDocs", "globals.jl"))
include(joinpath("PlainDocs", "macros.jl"))
include(joinpath("PlainDocs", "types.jl"))

module Inner_Module()

""
f_0() = ()

end

end

ext: jl


text:
"""
  function tail(v1::Vector{Float}, v2::Vector{Float}, α::Float = 0.002, tail::String)

Returns empirical left and right tail dependency of bivariate data
"""
function tail(v1::Vector{T}, v2::Vector{T}, tail::String, α::T = 0.002) where T <: AbstractFloat
  if tail == "l"
    return sum((v1 .< α) .* (v2 .< α))./(length(v1)*α)
  elseif tail == "r"
    return sum((v1 .> (1-α)) .* (v2 .> (1-α)))./(length(v1)*α)
  end
  0.
end

@testset "tail dependencies test" begin
  v1 = vcat(zeros(5), 0.5*ones(5), zeros(5), 0.5*ones(70), ones(5), 0.5*ones(5), ones(5));
  v2 = vcat(zeros(10), 0.5*ones(80), ones(10))
  @test tail(v1, v2,  "l", 0.1) ≈ 0.5
  @test tail(v1, v2, "r", 0.1) ≈ 0.5
end


text:
@testset "Random generator" begin

    modelStr = "(x, θ) -> θ[1] * x[1] + θ[2]"

    model = eval(Meta.parse(modelStr))

    n = 2

    np = 5

    p = 1

    datf = "test.dat"

    solf = "sol.dat"

    generate_test_problems(datf, solf, model, modelStr, n, np, p)

    open(solf, "r") do fp

        @test n == parse(Int, readline(fp))
        @test n == length(split(readline(fp)))
        @test modelStr == readline(fp)

    end

    nLines = 0
    nNoise = 0

    open(datf, "r") do fp

        # Check the dimension of the problem
        @test 1 == parse(Int, readline(fp))

        for line in eachline(fp)

            nLines += 1

            (parse(Int, split(line)[3]) != 0.0) && (nNoise += 1)

        end

    end

    @test (np - p) == nNoise
    @test np == nLines

    @testset "Unique" begin

        @test length(RAFF.get_unique_random_points(5,  2)) == 2

        @test length(RAFF.get_unique_random_points(0, -1)) == 0

        @test length(RAFF.get_unique_random_points(5,  0)) == 0

        @test length(RAFF.get_unique_random_points(1,  2)) == 1

        v = RAFF.get_unique_random_points(5, 5)

        @test length(v) == 5

        cnt = 0

        for i = 1:length(v)

            (i in v) && (cnt += 1)

        end

        @test cnt == 5

        @test length(RAFF.get_unique_random_points(1, -1)) == 0

        @test length(RAFF.get_unique_random_points(-1, 1)) == 0

        #

        @test_throws(DimensionMismatch,
                     RAFF.get_unique_random_points!(
                         Vector{Int}(undef, 1), 3, 2))

    end

    @testset "Noisy" begin

        n, model, model_s = RAFF.model_list["linear"]

        θSol = [1.0, 1.0]

        np = 5

        p = 4

        # No outliers

        data, θSol1, v = RAFF.generate_noisy_data(model, n, np, np)

        @test length(v) == 0

        @test length(θSol1) == n

        @test size(data) == (np, 3)

        @test all(data[:, 3] .== 0.0)

        # All outliers

        data, θSol1, v = RAFF.generate_noisy_data(model, n, np, 0)

        @test length(v) == np

        @test length(θSol1) == n

        @test size(data) == (np, 3)

        @test all(data[:, 3] .!= 0.0)

        #

        data, θSol1, v = RAFF.generate_noisy_data(model, n, np, p)

        @test length(v) == np - p

        @test length(θSol1) == n

        @test size(data) == (np, 3)

        @test sum(data[:, 3] .!= 0.0) == np - p

        # Test if the solution provided is maintained and also the interval

        xMin = -10.0

        xMax =  10.0

        data, θSol1, v = RAFF.generate_noisy_data(model, n, np, p, θSol, xMin, xMax)

        @test all(data[:, 1] .>= xMin)

        @test all(data[:, 1] .<= xMax)

        @test θSol == θSol1

        # Test if the solution provided is maintained and also the interval

        x_interval = (-10.0, 10.0)

        data, θSol1, v = RAFF.generate_noisy_data(model, n, np, p, θSol, x_interval)

        @test all(data[:, 1] .>= x_interval[1])

        @test all(data[:, 1] .<= x_interval[2])

        @test θSol == θSol1

        # Test the memory efficient version

        data = Array{Float64}(undef, np, 3)

        v = Vector{Int64}(undef, np)

        data1, θSol1, v1 = RAFF.generate_noisy_data!(data, v, model, n, np, p)

        @test data == data1

        @test v == v1

    end

    @testset "Cluster" begin

        n, model, model_s = RAFF.model_list["linear"]

        θSol = [1.0, 1.0]

        np = 10

        p = 7

        x_int = (-10.0, 10.0)

        c_int = (0.0, 5.0)

        data, θSol1, v = generate_clustered_noisy_data(model, n, np,
            p, x_int, c_int)

        @test size(data) == (np, 3)

        @test length(θSol1) == n

        @test length(v) == np - p

        out_ind = findall(abs.(data[:, 3]) .> 0.0)

        @test length(out_ind) == length(v)

        @test all(data[v, 1] .>= c_int[1])

        @test all(data[v, 1] .<= c_int[2])

        # This loop checks if the points are generated in order and
        # there is no repetition between groups of points
        is_ordered = true
        for i = 1:np - 1
            (data[i, 1] >= data[i + 1, 1]) && (is_ordered = false)
        end

        @test is_ordered

        # Cluster interval at the beginning

        x_int = (-10.0, 10.0)

        c_int = (-10.0, 0.0)

        data, θSol1, v = generate_clustered_noisy_data(model, n, np,
            p, x_int, c_int)

        @test length(v) == np - p

        @test any(data[:, 1] .> 0.0)

        # Non enclosing cluster interval

        x_int = (-10.0, 10.0)

        c_int = (-11.0, 0.0)

        @test_throws ErrorException generate_clustered_noisy_data(model, n, np,
            p, x_int, c_int)

        # Singleton cluster interval with np - p > 1

        np = 10

        p = 5

        x_int = (-10.0, 10.0)

        c_int = (1.0, 1.0)

        @test_throws ErrorException generate_clustered_noisy_data(model, n, np,
            p, x_int, c_int)

        # Singleton cluster interval with no outliers

        np = 10

        p = 10

        x_int = (-10.0, 10.0)

        c_int = (1.0, 1.0)

        data, θSol1, v = generate_clustered_noisy_data(model, n, np,
            p, x_int, c_int)

        @test length(v) == 0

        # Cluster with only one element

        np = 10

        p = 8

        x_int = (1.0, 30.0)

        c_int = (5.0, 10.0)

        data, θSol1, v = generate_clustered_noisy_data(model, n, np,
            p, x_int, c_int)

        @test length(findall(data[:, 1] .<= 5.0)) == 1

    end

    @testset "Rand Interv." begin

        n = 2

        x = Vector{Float64}(undef, n)

        l = [1.0, -5.0]
        u = [2.0, -1.0]

        interval = [i for i in zip(l, u)]

        RAFF.interval_rand!(x, interval)

        @test all(x .>= l)

        @test all(x .<= u)

        n = 5

        x = zeros(Float64, n)

        RAFF.interval_rand!(x, interval)

        @test all(x[1:2] .>= l)

        @test all(x[1:2] .<= u)

        @test all(x[3:n] .== 0.0)

        n = 1

        x = zeros(Float64, n)

        @test_throws ErrorException RAFF.interval_rand!(x, interval)

        # Bad interval

        n = 2

        x = Vector{Float64}(undef, n)

        l = [ 1.0, -5.0]
        u = [-1.0, -1.0]

        interval = [i for i in zip(l, u)]

        @test_throws ErrorException RAFF.interval_rand!(x, interval)

    end

    @testset "Model list $(type)" for (type, (n, model, model_str)) in RAFF.model_list

        # TODO: Maybe we need to get the dimension of the model?
        x = (type == "circle" || type == "ellipse") ? rand(2) : rand()

        θ = rand(n)

        model2 = eval(Meta.parse(model_str))

        @test model(x, θ) ≈ model2(x, θ)

    end

    @testset "Circle generator" begin

        data, v = generate_circle("circle_remove1.dat", 2, 1)

        @test(size(data) == (2, 4))
        @test(length(v) == 1)

        open("circle_remove1.dat", "r") do fp

            @test(parse(Int, readline(fp)) == 2)

            dataf = DelimitedFiles.readdlm(fp)

            @test(dataf ≈ data, atol=1.0e-15)
            @test(dataf[v[1], 4] == 1)

        end

        rm("./circle_remove1.dat")

        # Test bad interval

        @test_throws(ErrorException,
                     generate_circle("circle_remove2.dat", 5, 2;
                                     interval=[0.0, π]))
        @test_throws(SystemError, open("circle_remove2.dat"))

        # Test good interval

        data, v = generate_circle("circle_remove3.dat", 5, 4;
                     interval=[0.0, π/4, π / 2, 3 * π / 4, π ])

        @test(size(data) == (5, 4))
        @test(length(v) == 1)

        rm("circle_remove3.dat")

    end

    @testset "Circle uniform generator" begin

        data, v = generate_ncircle("circle_remove1.dat", 2, 1)

        @test(size(data) == (2, 4))
        @test(length(v) == 1)

        open("circle_remove1.dat", "r") do fp

            @test(parse(Int, readline(fp)) == 2)

            dataf = DelimitedFiles.readdlm(fp)

            @test(dataf ≈ data, atol=1.0e-14)
            @test(dataf[v[1], 4] > 0)

        end

        rm("./circle_remove1.dat")

        # Test bad interval

        @test_throws(ErrorException,
                     generate_circle("circle_remove2.dat", 5, 2;
                                     interval=[0.0, π]))
        @test_throws(SystemError, open("circle_remove2.dat"))

        # Test uniform distribution

        np = 100
        p  = 10
        θSol = [7.0, 7.0, 5.0]

        data, v = generate_circle("circle_remove3.dat", np, p;
                                  θSol=θSol)

        @test(size(data) == (100, 4))
        @test(length(v) == np - p)

        open("circle_remove3.dat") do fp

            @test(parse(Int, readline(fp)) == 2)

            dataf = DelimitedFiles.readdlm(fp)
            @test(dataf ≈ data, atol=1.0e-14)
            @test(all(dataf[v, 4] .> 0))

            @test(all(θSol[1] - 2 * θSol[3] .<= dataf[v, 1] .<= θSol[1] + 2 * θSol[3]))
            @test(all(θSol[2] - 2 * θSol[3] .<= dataf[v, 1] .<= θSol[2] + 2 * θSol[3]))

        end

        rm("circle_remove3.dat")

    end

    @testset "Noisy images" begin

        n, model, mstr = RAFF.model_list["linear"]

        fname = "line_image_remove.dat"

        img = RAFF.generate_image_noisy_data(fname, 400, 400, model,
                                             n, 500, 100)

        @test(size(img) == (400, 400))

        open(fname, "r") do fp

            readline(fp)

            while !eof(fp)

                l = readline(fp)

                x, y, f, e = map(x -> parse(Int, x), split(l))

                @test(img[y, x] == 1)
                @test(f == 0)
                @test(e == 0)

            end

        end

        rm(fname)

        fname = "circle_image_remove.dat"

        img = RAFF.generate_image_circle(fname, 400, 400, 1000, 100)

        @test(size(img) == (400, 400))

        open(fname, "r") do fp

            readline(fp)

            while !eof(fp)

                l = readline(fp)

                x, y, f, e = map(x -> parse(Int, x), split(l))

                @test(img[y, x] == 1)
                @test(f == 0)
                @test(e == 0)

            end

        end

        rm(fname)

    end

end


text:
using NGWP, LightGraphs, MTSG, Plots, LaTeXStrings

## Build Graph
N = 512; G = path_graph(N)
X = zeros(N,2); X[:, 1] = 1:N
L = Matrix(laplacian_matrix(G))
𝛌, 𝚽 = eigen(L); 𝚽 = 𝚽 .* sign.(𝚽[1,:])'
W = 1.0 * adjacency_matrix(G)

Gstar_Sig = GraphSig(W)
G_Sig = GraphSig(W, xy = X)
GP_dual = partition_tree_fiedler(Gstar_Sig; swapRegion = false)
GP_primal = pairclustering(𝚽, GP_dual)

## utility functions
function find_mainsupport(w; ϵ = 0.01)
   N = length(w)
   l, r = 1, N
   for i in 1:N
      if abs(w[i]) >= ϵ
         l = i
         break
      end
   end
   for i in N:-1:l
      if abs(w[i]) >= ϵ
         r = i
         break
      end
   end
   return [l, r]
end

function findlocalmaxima(signal::Vector)
    inds = Int[]
    if length(signal)>1
        if signal[1]>signal[2]
            push!(inds,1)
        end
        for i=2:length(signal)-1
            if signal[i-1]<signal[i]>signal[i+1]
               push!(inds,i)
            end
        end
        if signal[end]>signal[end-1]
            push!(inds,length(signal))
        end
    end
    inds
end

function sidelobe_attenuation(w)
   locmax_ind = findlocalmaxima(w)
   locmax_val = sort(w[locmax_ind]; rev = true)
   return locmax_val[2] / locmax_val[1]
end


text:
# generated from AutoScalingTypeDict via AWS/src/codegen.jl
# do not edit, edit specification file and regenerate instead

type DeleteNotificationConfigurationRequest <: AbstractAWSType
    autoScalingGroupName::Union{Void,String}
    topicARN::Union{Void,Array{String,1}}
    function DeleteNotificationConfigurationRequest(;autoScalingGroupName=nothing, topicARN=nothing)
        new(autoScalingGroupName, topicARN)
    end
    DeleteNotificationConfigurationRequest(pd) = parse_from_xml(DeleteNotificationConfigurationRequest, AutoScalingTypeDict, pd)
end # DeleteNotificationConfigurationRequest
export DeleteNotificationConfigurationRequest

function DeleteNotificationConfiguration(env::AWSEnv, msg::DeleteNotificationConfigurationRequest)
    resp::AutoScalingResponse = autoscaling_execute(env, "DeleteNotificationConfiguration", msg)
    resp
end
DeleteNotificationConfiguration(env::AWSEnv; kwargs...) = DeleteNotificationConfiguration(env, DeleteNotificationConfigurationRequest(; kwargs...))
export DeleteNotificationConfiguration

type DetachInstancesResult <: AbstractAWSType
    activities::Union{Void,Array{Activity,1}}
    function DetachInstancesResult(;activities=nothing)
        new(activities)
    end
    DetachInstancesResult(pd) = parse_from_xml(DetachInstancesResult, AutoScalingTypeDict, pd)
end # DetachInstancesResult
export DetachInstancesResult

type DetachInstancesRequest <: AbstractAWSType
    autoScalingGroupName::Union{Void,String}
    instanceIds::Union{Void,Array{String,1}}
    shouldDecrementDesiredCapacity::Union{Void,Bool}
    function DetachInstancesRequest(;autoScalingGroupName=nothing, instanceIds=nothing, shouldDecrementDesiredCapacity=nothing)
        new(autoScalingGroupName, instanceIds, shouldDecrementDesiredCapacity)
    end
    DetachInstancesRequest(pd) = parse_from_xml(DetachInstancesRequest, AutoScalingTypeDict, pd)
end # DetachInstancesRequest
export DetachInstancesRequest

function DetachInstances(env::AWSEnv, msg::DetachInstancesRequest)
    resp::AutoScalingResponse = autoscaling_execute(env, "DetachInstances", msg)
    if (resp.pd !== nothing) && (resp.obj === nothing)
        resp.obj = DetachInstancesResult(resp.pd)
    end
    resp
end
DetachInstances(env::AWSEnv; kwargs...) = DetachInstances(env, DetachInstancesRequest(; kwargs...))
export DetachInstances

type DescribeMetricCollectionTypesResult <: AbstractAWSType
    granularities::Union{Void,Array{MetricGranularityType,1}}
    metrics::Union{Void,Array{MetricCollectionType,1}}
    function DescribeMetricCollectionTypesResult(;granularities=nothing, metrics=nothing)
        new(granularities, metrics)
    end
    DescribeMetricCollectionTypesResult(pd) = parse_from_xml(DescribeMetricCollectionTypesResult, AutoScalingTypeDict, pd)
end # DescribeMetricCollectionTypesResult
export DescribeMetricCollectionTypesResult

function DescribeMetricCollectionTypes(env::AWSEnv)
    resp::AutoScalingResponse = autoscaling_execute(env, "DescribeMetricCollectionTypes")
    if (resp.pd !== nothing) && (resp.obj === nothing)
        resp.obj = DescribeMetricCollectionTypesResult(resp.pd)
    end
    resp
end
export DescribeMetricCollectionTypes

type SetInstanceHealthRequest <: AbstractAWSType
    healthStatus::Union{Void,String}
    instanceId::Union{Void,String}
    shouldRespectGracePeriod::Union{Void,Bool}
    function SetInstanceHealthRequest(;healthStatus=nothing, instanceId=nothing, shouldRespectGracePeriod=nothing)
        new(healthStatus, instanceId, shouldRespectGracePeriod)
    end
    SetInstanceHealthRequest(pd) = parse_from_xml(SetInstanceHealthRequest, AutoScalingTypeDict, pd)
end # SetInstanceHealthRequest
export SetInstanceHealthRequest

function SetInstanceHealth(env::AWSEnv, msg::SetInstanceHealthRequest)
    resp::AutoScalingResponse = autoscaling_execute(env, "SetInstanceHealth", msg)
    resp
end
SetInstanceHealth(env::AWSEnv; kwargs...) = SetInstanceHealth(env, SetInstanceHealthRequest(; kwargs...))
export SetInstanceHealth

type DeleteLaunchConfigurationRequest <: AbstractAWSType
    launchConfigurationName::Union{Void,String}
    function DeleteLaunchConfigurationRequest(;launchConfigurationName=nothing)
        new(launchConfigurationName)
    end
    DeleteLaunchConfigurationRequest(pd) = parse_from_xml(DeleteLaunchConfigurationRequest, AutoScalingTypeDict, pd)
end # DeleteLaunchConfigurationRequest
export DeleteLaunchConfigurationRequest

function DeleteLaunchConfiguration(env::AWSEnv, msg::DeleteLaunchConfigurationRequest)
    resp::AutoScalingResponse = autoscaling_execute(env, "DeleteLaunchConfiguration", msg)
    resp
end
DeleteLaunchConfiguration(env::AWSEnv; kwargs...) = DeleteLaunchConfiguration(env, DeleteLaunchConfigurationRequest(; kwargs...))
export DeleteLaunchConfiguration

type DescribeAutoScalingInstancesResult <: AbstractAWSType
    autoScalingInstances::Union{Void,Array{AutoScalingInstanceDetails,1}}
    nextToken::Union{Void,String}
    function DescribeAutoScalingInstancesResult(;autoScalingInstances=nothing, nextToken=nothing)
        new(autoScalingInstances, nextToken)
    end
    DescribeAutoScalingInstancesResult(pd) = parse_from_xml(DescribeAutoScalingInstancesResult, AutoScalingTypeDict, pd)
end # DescribeAutoScalingInstancesResult
export DescribeAutoScalingInstancesResult

type DescribeAutoScalingInstancesRequest <: AbstractAWSType
    instanceIds::Union{Void,Array{String,1}}
    maxRecords::Union{Void,Int64}
    nextToken::Union{Void,String}
    function DescribeAutoScalingInstancesRequest(;instanceIds=nothing, maxRecords=nothing, nextToken=nothing)
        new(instanceIds, maxRecords, nextToken)
    end
    DescribeAutoScalingInstancesRequest(pd) = parse_from_xml(DescribeAutoScalingInstancesRequest, AutoScalingTypeDict, pd)
end # DescribeAutoScalingInstancesRequest
export DescribeAutoScalingInstancesRequest

function DescribeAutoScalingInstances(env::AWSEnv, msg::DescribeAutoScalingInstancesRequest)
    resp::AutoScalingResponse = autoscaling_execute(env, "DescribeAutoScalingInstances", msg)
    if (resp.pd !== nothing) && (resp.obj === nothing)
        resp.obj = DescribeAutoScalingInstancesResult(resp.pd)
    end
    resp
end
DescribeAutoScalingInstances(env::AWSEnv; kwargs...) = DescribeAutoScalingInstances(env, DescribeAutoScalingInstancesRequest(; kwargs...))
export DescribeAutoScalingInstances

type CreateLaunchConfigurationRequest <: AbstractAWSType
    associatePublicIpAddress::Union{Void,Bool}
    blockDeviceMappings::Union{Void,Array{BlockDeviceMapping,1}}
    classicLinkVPCId::Union{Void,String}
    classicLinkVPCSecurityGroups::Union{Void,Array{String,1}}
    ebsOptimized::Union{Void,Bool}
    iamInstanceProfile::Union{Void,String}
    imageId::Union{Void,String}
    instanceId::Union{Void,String}
    instanceMonitoring::Union{Void,InstanceMonitoring}
    instanceType::Union{Void,String}
    kernelId::Union{Void,String}
    keyName::Union{Void,String}
    launchConfigurationName::Union{Void,String}
    placementTenancy::Union{Void,String}
    ramdiskId::Union{Void,String}
    securityGroups::Union{Void,Array{String,1}}
    spotPrice::Union{Void,String}
    userData::Union{Void,String}
    function CreateLaunchConfigurationRequest(;associatePublicIpAddress=nothing, blockDeviceMappings=nothing, classicLinkVPCId=nothing, classicLinkVPCSecurityGroups=nothing, ebsOptimized=nothing, iamInstanceProfile=nothing, imageId=nothing, instanceId=nothing, instanceMonitoring=nothing, instanceType=nothing, kernelId=nothing, keyName=nothing, launchConfigurationName=nothing, placementTenancy=nothing, ramdiskId=nothing, securityGroups=nothing, spotPrice=nothing, userData=nothing)
        new(associatePublicIpAddress, blockDeviceMappings, classicLinkVPCId, classicLinkVPCSecurityGroups, ebsOptimized, iamInstanceProfile, imageId, instanceId, instanceMonitoring, instanceType, kernelId, keyName, launchConfigurationName, placementTenancy, ramdiskId, securityGroups, spotPrice, userData)
    end
    CreateLaunchConfigurationRequest(pd) = parse_from_xml(CreateLaunchConfigurationRequest, AutoScalingTypeDict, pd)
end # CreateLaunchConfigurationRequest
export CreateLaunchConfigurationRequest

function CreateLaunchConfiguration(env::AWSEnv, msg::CreateLaunchConfigurationRequest)
    resp::AutoScalingResponse = autoscaling_execute(env, "CreateLaunchConfiguration", msg)
    resp
end
CreateLaunchConfiguration(env::AWSEnv; kwargs...) = CreateLaunchConfiguration(env, CreateLaunchConfigurationRequest(; kwargs...))
export CreateLaunchConfiguration

type DescribeLifecycleHookTypesResult <: AbstractAWSType
    lifecycleHookTypes::Union{Void,Array{String,1}}
    function DescribeLifecycleHookTypesResult(;lifecycleHookTypes=nothing)
        new(lifecycleHookTypes)
    end
    DescribeLifecycleHookTypesResult(pd) = parse_from_xml(DescribeLifecycleHookTypesResult, AutoScalingTypeDict, pd)
end # DescribeLifecycleHookTypesResult
export DescribeLifecycleHookTypesResult

function DescribeLifecycleHookTypes(env::AWSEnv)
    resp::AutoScalingResponse = autoscaling_execute(env, "DescribeLifecycleHookTypes")
    if (resp.pd !== nothing) && (resp.obj === nothing)
        resp.obj = DescribeLifecycleHookTypesResult(resp.pd)
    end
    resp
end
export DescribeLifecycleHookTypes

type PutNotificationConfigurationRequest <: AbstractAWSType
    autoScalingGroupName::Union{Void,String}
    notificationTypes::Union{Void,Array{String,1}}
    topicARN::Union{Void,String}
    function PutNotificationConfigurationRequest(;autoScalingGroupName=nothing, notificationTypes=nothing, topicARN=nothing)
        new(autoScalingGroupName, notificationTypes, topicARN)
    end
    PutNotificationConfigurationRequest(pd) = parse_from_xml(PutNotificationConfigurationRequest, AutoScalingTypeDict, pd)
end # PutNotificationConfigurationRequest
export PutNotificationConfigurationRequest

function PutNotificationConfiguration(env::AWSEnv, msg::PutNotificationConfigurationRequest)
    resp::AutoScalingResponse = autoscaling_execute(env, "PutNotificationConfiguration", msg)
    resp
end
PutNotificationConfiguration(env::AWSEnv; kwargs...) = PutNotificationConfiguration(env, PutNotificationConfigurationRequest(; kwargs...))
export PutNotificationConfiguration

type DeleteAutoScalingGroupRequest <: AbstractAWSType
    autoScalingGroupName::Union{Void,String}
    forceDelete::Union{Void,Bool}
    function DeleteAutoScalingGroupRequest(;autoScalingGroupName=nothing, forceDelete=nothing)
        new(autoScalingGroupName, forceDelete)
    end
    DeleteAutoScalingGroupRequest(pd) = parse_from_xml(DeleteAutoScalingGroupRequest, AutoScalingTypeDict, pd)
end # DeleteAutoScalingGroupRequest
export DeleteAutoScalingGroupRequest

function DeleteAutoScalingGroup(env::AWSEnv, msg::DeleteAutoScalingGroupRequest)
    resp::AutoScalingResponse = autoscaling_execute(env, "DeleteAutoScalingGroup", msg)
    resp
end
DeleteAutoScalingGroup(env::AWSEnv; kwargs...) = DeleteAutoScalingGroup(env, DeleteAutoScalingGroupRequest(; kwargs...))
export DeleteAutoScalingGroup

type SetDesiredCapacityRequest <: AbstractAWSType
    autoScalingGroupName::Union{Void,String}
    desiredCapacity::Union{Void,Int64}
    honorCooldown::Union{Void,Bool}
    function SetDesiredCapacityRequest(;autoScalingGroupName=nothing, desiredCapacity=nothing, honorCooldown=nothing)
        new(autoScalingGroupName, desiredCapacity, honorCooldown)
    end
    SetDesiredCapacityRequest(pd) = parse_from_xml(SetDesiredCapacityRequest, AutoScalingTypeDict, pd)
end # SetDesiredCapacityRequest
export SetDesiredCapacityRequest

function SetDesiredCapacity(env::AWSEnv, msg::SetDesiredCapacityRequest)
    resp::AutoScalingResponse = autoscaling_execute(env, "SetDesiredCapacity", msg)
    resp
end
SetDesiredCapacity(env::AWSEnv; kwargs...) = SetDesiredCapacity(env, SetDesiredCapacityRequest(; kwargs...))
export SetDesiredCapacity

type CreateOrUpdateTagsRequest <: AbstractAWSType
    tags::Union{Void,Array{Tag,1}}
    function CreateOrUpdateTagsRequest(;tags=nothing)
        new(tags)
    end
    CreateOrUpdateTagsRequest(pd) = parse_from_xml(CreateOrUpdateTagsRequest, AutoScalingTypeDict, pd)
end # CreateOrUpdateTagsRequest
export CreateOrUpdateTagsRequest

function CreateOrUpdateTags(env::AWSEnv, msg::CreateOrUpdateTagsRequest)
    resp::AutoScalingResponse = autoscaling_execute(env, "CreateOrUpdateTags", msg)
    resp
end
CreateOrUpdateTags(env::AWSEnv; kwargs...) = CreateOrUpdateTags(env, CreateOrUpdateTagsRequest(; kwargs...))
export CreateOrUpdateTags

type DescribeLoadBalancerTargetGroupsResult <: AbstractAWSType
    loadBalancerTargetGroups::Union{Void,Array{LoadBalancerTargetGroupState,1}}
    nextToken::Union{Void,String}
    function DescribeLoadBalancerTargetGroupsResult(;loadBalancerTargetGroups=nothing, nextToken=nothing)
        new(loadBalancerTargetGroups, nextToken)
    end
    DescribeLoadBalancerTargetGroupsResult(pd) = parse_from_xml(DescribeLoadBalancerTargetGroupsResult, AutoScalingTypeDict, pd)
end # DescribeLoadBalancerTargetGroupsResult
export DescribeLoadBalancerTargetGroupsResult

type DescribeLoadBalancerTargetGroupsRequest <: AbstractAWSType
    autoScalingGroupName::Union{Void,String}
    maxRecords::Union{Void,Int64}
    nextToken::Union{Void,String}
    function DescribeLoadBalancerTargetGroupsRequest(;autoScalingGroupName=nothing, maxRecords=nothing, nextToken=nothing)
        new(autoScalingGroupName, maxRecords, nextToken)
    end
    DescribeLoadBalancerTargetGroupsRequest(pd) = parse_from_xml(DescribeLoadBalancerTargetGroupsRequest, AutoScalingTypeDict, pd)
end # DescribeLoadBalancerTargetGroupsRequest
export DescribeLoadBalancerTargetGroupsRequest

function DescribeLoadBalancerTargetGroups(env::AWSEnv, msg::DescribeLoadBalancerTargetGroupsRequest)
    resp::AutoScalingResponse = autoscaling_execute(env, "DescribeLoadBalancerTargetGroups", msg)
    if (resp.pd !== nothing) && (resp.obj === nothing)
        resp.obj = DescribeLoadBalancerTargetGroupsResult(resp.pd)
    end
    resp
end
DescribeLoadBalancerTargetGroups(env::AWSEnv; kwargs...) = DescribeLoadBalancerTargetGroups(env, DescribeLoadBalancerTargetGroupsRequest(; kwargs...))
export DescribeLoadBalancerTargetGroups

type DescribeAutoScalingNotificationTypesResult <: AbstractAWSType
    autoScalingNotificationTypes::Union{Void,Array{String,1}}
    function DescribeAutoScalingNotificationTypesResult(;autoScalingNotificationTypes=nothing)
        new(autoScalingNotificationTypes)
    end
    DescribeAutoScalingNotificationTypesResult(pd) = parse_from_xml(DescribeAutoScalingNotificationTypesResult, AutoScalingTypeDict, pd)
end # DescribeAutoScalingNotificationTypesResult
export DescribeAutoScalingNotificationTypesResult

function DescribeAutoScalingNotificationTypes(env::AWSEnv)
    resp::AutoScalingResponse = autoscaling_execute(env, "DescribeAutoScalingNotificationTypes")
    if (resp.pd !== nothing) && (resp.obj === nothing)
        resp.obj = DescribeAutoScalingNotificationTypesResult(resp.pd)
    end
    resp
end
export DescribeAutoScalingNotificationTypes

type PutLifecycleHookRequest <: AbstractAWSType
    autoScalingGroupName::Union{Void,String}
    defaultResult::Union{Void,String}
    heartbeatTimeout::Union{Void,Int64}
    lifecycleHookName::Union{Void,String}
    lifecycleTransition::Union{Void,String}
    notificationMetadata::Union{Void,String}
    notificationTargetARN::Union{Void,String}
    roleARN::Union{Void,String}
    function PutLifecycleHookRequest(;autoScalingGroupName=nothing, defaultResult=nothing, heartbeatTimeout=nothing, lifecycleHookName=nothing, lifecycleTransition=nothing, notificationMetadata=nothing, notificationTargetARN=nothing, roleARN=nothing)
        new(autoScalingGroupName, defaultResult, heartbeatTimeout, lifecycleHookName, lifecycleTransition, notificationMetadata, notificationTargetARN, roleARN)
    end
    PutLifecycleHookRequest(pd) = parse_from_xml(PutLifecycleHookRequest, AutoScalingTypeDict, pd)
end # PutLifecycleHookRequest
export PutLifecycleHookRequest

function PutLifecycleHook(env::AWSEnv, msg::PutLifecycleHookRequest)
    resp::AutoScalingResponse = autoscaling_execute(env, "PutLifecycleHook", msg)
    resp
end
PutLifecycleHook(env::AWSEnv; kwargs...) = PutLifecycleHook(env, PutLifecycleHookRequest(; kwargs...))
export PutLifecycleHook

type DescribeTagsResult <: AbstractAWSType
    nextToken::Union{Void,String}
    tags::Union{Void,Array{TagDescription,1}}
    function DescribeTagsResult(;nextToken=nothing, tags=nothing)
        new(nextToken, tags)
    end
    DescribeTagsResult(pd) = parse_from_xml(DescribeTagsResult, AutoScalingTypeDict, pd)
end # DescribeTagsResult
export DescribeTagsResult

type DescribeTagsRequest <: AbstractAWSType
    filters::Union{Void,Array{Filter,1}}
    maxRecords::Union{Void,Int64}
    nextToken::Union{Void,String}
    function DescribeTagsRequest(;filters=nothing, maxRecords=nothing, nextToken=nothing)
        new(filters, maxRecords, nextToken)
    end
    DescribeTagsRequest(pd) = parse_from_xml(DescribeTagsRequest, AutoScalingTypeDict, pd)
end # DescribeTagsRequest
export DescribeTagsRequest

function DescribeTags(env::AWSEnv, msg::DescribeTagsRequest)
    resp::AutoScalingResponse = autoscaling_execute(env, "DescribeTags", msg)
    if (resp.pd !== nothing) && (resp.obj === nothing)
        resp.obj = DescribeTagsResult(resp.pd)
    end
    resp
end
DescribeTags(env::AWSEnv; kwargs...) = DescribeTags(env, DescribeTagsRequest(; kwargs...))
export DescribeTags

type DetachLoadBalancersRequest <: AbstractAWSType
    autoScalingGroupName::Union{Void,String}
    loadBalancerNames::Union{Void,Array{String,1}}
    function DetachLoadBalancersRequest(;autoScalingGroupName=nothing, loadBalancerNames=nothing)
        new(autoScalingGroupName, loadBalancerNames)
    end
    DetachLoadBalancersRequest(pd) = parse_from_xml(DetachLoadBalancersRequest, AutoScalingTypeDict, pd)
end # DetachLoadBalancersRequest
export DetachLoadBalancersRequest

function DetachLoadBalancers(env::AWSEnv, msg::DetachLoadBalancersRequest)
    resp::AutoScalingResponse = autoscaling_execute(env, "DetachLoadBalancers", msg)
    resp
end
DetachLoadBalancers(env::AWSEnv; kwargs...) = DetachLoadBalancers(env, DetachLoadBalancersRequest(; kwargs...))
export DetachLoadBalancers

type DescribeLifecycleHooksResult <: AbstractAWSType
    lifecycleHooks::Union{Void,Array{LifecycleHook,1}}
    function DescribeLifecycleHooksResult(;lifecycleHooks=nothing)
        new(lifecycleHooks)
    end
    DescribeLifecycleHooksResult(pd) = parse_from_xml(DescribeLifecycleHooksResult, AutoScalingTypeDict, pd)
end # DescribeLifecycleHooksResult
export DescribeLifecycleHooksResult

type DescribeLifecycleHooksRequest <: AbstractAWSType
    autoScalingGroupName::Union{Void,String}
    lifecycleHookNames::Union{Void,Array{String,1}}
    function DescribeLifecycleHooksRequest(;autoScalingGroupName=nothing, lifecycleHookNames=nothing)
        new(autoScalingGroupName, lifecycleHookNames)
    end
    DescribeLifecycleHooksRequest(pd) = parse_from_xml(DescribeLifecycleHooksRequest, AutoScalingTypeDict, pd)
end # DescribeLifecycleHooksRequest
export DescribeLifecycleHooksRequest

function DescribeLifecycleHooks(env::AWSEnv, msg::DescribeLifecycleHooksRequest)
    resp::AutoScalingResponse = autoscaling_execute(env, "DescribeLifecycleHooks", msg)
    if (resp.pd !== nothing) && (resp.obj === nothing)
        resp.obj = DescribeLifecycleHooksResult(resp.pd)
    end
    resp
end
DescribeLifecycleHooks(env::AWSEnv; kwargs...) = DescribeLifecycleHooks(env, DescribeLifecycleHooksRequest(; kwargs...))
export DescribeLifecycleHooks

type DeleteScheduledActionRequest <: AbstractAWSType
    autoScalingGroupName::Union{Void,String}
    scheduledActionName::Union{Void,String}
    function DeleteScheduledActionRequest(;autoScalingGroupName=nothing, scheduledActionName=nothing)
        new(autoScalingGroupName, scheduledActionName)
    end
    DeleteScheduledActionRequest(pd) = parse_from_xml(DeleteScheduledActionRequest, AutoScalingTypeDict, pd)
end # DeleteScheduledActionRequest
export DeleteScheduledActionRequest

function DeleteScheduledAction(env::AWSEnv, msg::DeleteScheduledActionRequest)
    resp::AutoScalingResponse = autoscaling_execute(env, "DeleteScheduledAction", msg)
    resp
end
DeleteScheduledAction(env::AWSEnv; kwargs...) = DeleteScheduledAction(env, DeleteScheduledActionRequest(; kwargs...))
export DeleteScheduledAction

type SuspendProcessesRequest <: AbstractAWSType
    autoScalingGroupName::Union{Void,String}
    scalingProcesses::Union{Void,Array{String,1}}
    function SuspendProcessesRequest(;autoScalingGroupName=nothing, scalingProcesses=nothing)
        new(autoScalingGroupName, scalingProcesses)
    end
    SuspendProcessesRequest(pd) = parse_from_xml(SuspendProcessesRequest, AutoScalingTypeDict, pd)
end # SuspendProcessesRequest
export SuspendProcessesRequest

function SuspendProcesses(env::AWSEnv, msg::SuspendProcessesRequest)
    resp::AutoScalingResponse = autoscaling_execute(env, "SuspendProcesses", msg)
    resp
end
SuspendProcesses(env::AWSEnv; kwargs...) = SuspendProcesses(env, SuspendProcessesRequest(; kwargs...))
export SuspendProcesses

type ResumeProcessesRequest <: AbstractAWSType
    autoScalingGroupName::Union{Void,String}
    scalingProcesses::Union{Void,Array{String,1}}
    function ResumeProcessesRequest(;autoScalingGroupName=nothing, scalingProcesses=nothing)
        new(autoScalingGroupName, scalingProcesses)
    end
    ResumeProcessesRequest(pd) = parse_from_xml(ResumeProcessesRequest, AutoScalingTypeDict, pd)
end # ResumeProcessesRequest
export ResumeProcessesRequest

function ResumeProcesses(env::AWSEnv, msg::ResumeProcessesRequest)
    resp::AutoScalingResponse = autoscaling_execute(env, "ResumeProcesses", msg)
    resp
end
ResumeProcesses(env::AWSEnv; kwargs...) = ResumeProcesses(env, ResumeProcessesRequest(; kwargs...))
export ResumeProcesses

type DisableMetricsCollectionRequest <: AbstractAWSType
    autoScalingGroupName::Union{Void,String}
    metrics::Union{Void,Array{String,1}}
    function DisableMetricsCollectionRequest(;autoScalingGroupName=nothing, metrics=nothing)
        new(autoScalingGroupName, metrics)
    end
    DisableMetricsCollectionRequest(pd) = parse_from_xml(DisableMetricsCollectionRequest, AutoScalingTypeDict, pd)
end # DisableMetricsCollectionRequest
export DisableMetricsCollectionRequest

function DisableMetricsCollection(env::AWSEnv, msg::DisableMetricsCollectionRequest)
    resp::AutoScalingResponse = autoscaling_execute(env, "DisableMetricsCollection", msg)
    resp
end
DisableMetricsCollection(env::AWSEnv; kwargs...) = DisableMetricsCollection(env, DisableMetricsCollectionRequest(; kwargs...))
export DisableMetricsCollection

type DescribeLoadBalancersResult <: AbstractAWSType
    loadBalancers::Union{Void,Array{LoadBalancerState,1}}
    nextToken::Union{Void,String}
    function DescribeLoadBalancersResult(;loadBalancers=nothing, nextToken=nothing)
        new(loadBalancers, nextToken)
    end
    DescribeLoadBalancersResult(pd) = parse_from_xml(DescribeLoadBalancersResult, AutoScalingTypeDict, pd)
end # DescribeLoadBalancersResult
export DescribeLoadBalancersResult

type DescribeLoadBalancersRequest <: AbstractAWSType
    autoScalingGroupName::Union{Void,String}
    maxRecords::Union{Void,Int64}
    nextToken::Union{Void,String}
    function DescribeLoadBalancersRequest(;autoScalingGroupName=nothing, maxRecords=nothing, nextToken=nothing)
        new(autoScalingGroupName, maxRecords, nextToken)
    end
    DescribeLoadBalancersRequest(pd) = parse_from_xml(DescribeLoadBalancersRequest, AutoScalingTypeDict, pd)
end # DescribeLoadBalancersRequest
export DescribeLoadBalancersRequest

function DescribeLoadBalancers(env::AWSEnv, msg::DescribeLoadBalancersRequest)
    resp::AutoScalingResponse = autoscaling_execute(env, "DescribeLoadBalancers", msg)
    if (resp.pd !== nothing) && (resp.obj === nothing)
        resp.obj = DescribeLoadBalancersResult(resp.pd)
    end
    resp
end
DescribeLoadBalancers(env::AWSEnv; kwargs...) = DescribeLoadBalancers(env, DescribeLoadBalancersRequest(; kwargs...))
export DescribeLoadBalancers

type PutScheduledUpdateGroupActionRequest <: AbstractAWSType
    autoScalingGroupName::Union{Void,String}
    desiredCapacity::Union{Void,Int64}
    endTime::Union{Void,DateTime}
    maxSize::Union{Void,Int64}
    minSize::Union{Void,Int64}
    recurrence::Union{Void,String}
    scheduledActionName::Union{Void,String}
    startTime::Union{Void,DateTime}
    time::Union{Void,DateTime}
    function PutScheduledUpdateGroupActionRequest(;autoScalingGroupName=nothing, desiredCapacity=nothing, endTime=nothing, maxSize=nothing, minSize=nothing, recurrence=nothing, scheduledActionName=nothing, startTime=nothing, time=nothing)
        new(autoScalingGroupName, desiredCapacity, endTime, maxSize, minSize, recurrence, scheduledActionName, startTime, time)
    end
    PutScheduledUpdateGroupActionRequest(pd) = parse_from_xml(PutScheduledUpdateGroupActionRequest, AutoScalingTypeDict, pd)
end # PutScheduledUpdateGroupActionRequest
export PutScheduledUpdateGroupActionRequest

function PutScheduledUpdateGroupAction(env::AWSEnv, msg::PutScheduledUpdateGroupActionRequest)
    resp::AutoScalingResponse = autoscaling_execute(env, "PutScheduledUpdateGroupAction", msg)
    resp
end
PutScheduledUpdateGroupAction(env::AWSEnv; kwargs...) = PutScheduledUpdateGroupAction(env, PutScheduledUpdateGroupActionRequest(; kwargs...))
export PutScheduledUpdateGroupAction

type AttachLoadBalancersRequest <: AbstractAWSType
    autoScalingGroupName::Union{Void,String}
    loadBalancerNames::Union{Void,Array{String,1}}
    function AttachLoadBalancersRequest(;autoScalingGroupName=nothing, loadBalancerNames=nothing)
        new(autoScalingGroupName, loadBalancerNames)
    end
    AttachLoadBalancersRequest(pd) = parse_from_xml(AttachLoadBalancersRequest, AutoScalingTypeDict, pd)
end # AttachLoadBalancersRequest
export AttachLoadBalancersRequest

function AttachLoadBalancers(env::AWSEnv, msg::AttachLoadBalancersRequest)
    resp::AutoScalingResponse = autoscaling_execute(env, "AttachLoadBalancers", msg)
    resp
end
AttachLoadBalancers(env::AWSEnv; kwargs...) = AttachLoadBalancers(env, AttachLoadBalancersRequest(; kwargs...))
export AttachLoadBalancers

type AttachInstancesRequest <: AbstractAWSType
    autoScalingGroupName::Union{Void,String}
    instanceIds::Union{Void,Array{String,1}}
    function AttachInstancesRequest(;autoScalingGroupName=nothing, instanceIds=nothing)
        new(autoScalingGroupName, instanceIds)
    end
    AttachInstancesRequest(pd) = parse_from_xml(AttachInstancesRequest, AutoScalingTypeDict, pd)
end # AttachInstancesRequest
export AttachInstancesRequest

function AttachInstances(env::AWSEnv, msg::AttachInstancesRequest)
    resp::AutoScalingResponse = autoscaling_execute(env, "AttachInstances", msg)
    resp
end
AttachInstances(env::AWSEnv; kwargs...) = AttachInstances(env, AttachInstancesRequest(; kwargs...))
export AttachInstances

type DescribeScheduledActionsResult <: AbstractAWSType
    nextToken::Union{Void,String}
    scheduledUpdateGroupActions::Union{Void,Array{ScheduledUpdateGroupAction,1}}
    function DescribeScheduledActionsResult(;nextToken=nothing, scheduledUpdateGroupActions=nothing)
        new(nextToken, scheduledUpdateGroupActions)
    end
    DescribeScheduledActionsResult(pd) = parse_from_xml(DescribeScheduledActionsResult, AutoScalingTypeDict, pd)
end # DescribeScheduledActionsResult
export DescribeScheduledActionsResult

type DescribeScheduledActionsRequest <: AbstractAWSType
    autoScalingGroupName::Union{Void,String}
    endTime::Union{Void,DateTime}
    maxRecords::Union{Void,Int64}
    nextToken::Union{Void,String}
    scheduledActionNames::Union{Void,Array{String,1}}
    startTime::Union{Void,DateTime}
    function DescribeScheduledActionsRequest(;autoScalingGroupName=nothing, endTime=nothing, maxRecords=nothing, nextToken=nothing, scheduledActionNames=nothing, startTime=nothing)
        new(autoScalingGroupName, endTime, maxRecords, nextToken, scheduledActionNames, startTime)
    end
    DescribeScheduledActionsRequest(pd) = parse_from_xml(DescribeScheduledActionsRequest, AutoScalingTypeDict, pd)
end # DescribeScheduledActionsRequest
export DescribeScheduledActionsRequest

function DescribeScheduledActions(env::AWSEnv, msg::DescribeScheduledActionsRequest)
    resp::AutoScalingResponse = autoscaling_execute(env, "DescribeScheduledActions", msg)
    if (resp.pd !== nothing) && (resp.obj === nothing)
        resp.obj = DescribeScheduledActionsResult(resp.pd)
    end
    resp
end
DescribeScheduledActions(env::AWSEnv; kwargs...) = DescribeScheduledActions(env, DescribeScheduledActionsRequest(; kwargs...))
export DescribeScheduledActions

type EnterStandbyResult <: AbstractAWSType
    activities::Union{Void,Array{Activity,1}}
    function EnterStandbyResult(;activities=nothing)
        new(activities)
    end
    EnterStandbyResult(pd) = parse_from_xml(EnterStandbyResult, AutoScalingTypeDict, pd)
end # EnterStandbyResult
export EnterStandbyResult

type EnterStandbyRequest <: AbstractAWSType
    autoScalingGroupName::Union{Void,String}
    instanceIds::Union{Void,Array{String,1}}
    shouldDecrementDesiredCapacity::Union{Void,Bool}
    function EnterStandbyRequest(;autoScalingGroupName=nothing, instanceIds=nothing, shouldDecrementDesiredCapacity=nothing)
        new(autoScalingGroupName, instanceIds, shouldDecrementDesiredCapacity)
    end
    EnterStandbyRequest(pd) = parse_from_xml(EnterStandbyRequest, AutoScalingTypeDict, pd)
end # EnterStandbyRequest
export EnterStandbyRequest

function EnterStandby(env::AWSEnv, msg::EnterStandbyRequest)
    resp::AutoScalingResponse = autoscaling_execute(env, "EnterStandby", msg)
    if (resp.pd !== nothing) && (resp.obj === nothing)
        resp.obj = EnterStandbyResult(resp.pd)
    end
    resp
end
EnterStandby(env::AWSEnv; kwargs...) = EnterStandby(env, EnterStandbyRequest(; kwargs...))
export EnterStandby

type DescribeAccountLimitsResult <: AbstractAWSType
    maxNumberOfAutoScalingGroups::Union{Void,Int64}
    maxNumberOfLaunchConfigurations::Union{Void,Int64}
    numberOfAutoScalingGroups::Union{Void,Int64}
    numberOfLaunchConfigurations::Union{Void,Int64}
    function DescribeAccountLimitsResult(;maxNumberOfAutoScalingGroups=nothing, maxNumberOfLaunchConfigurations=nothing, numberOfAutoScalingGroups=nothing, numberOfLaunchConfigurations=nothing)
        new(maxNumberOfAutoScalingGroups, maxNumberOfLaunchConfigurations, numberOfAutoScalingGroups, numberOfLaunchConfigurations)
    end
    DescribeAccountLimitsResult(pd) = parse_from_xml(DescribeAccountLimitsResult, AutoScalingTypeDict, pd)
end # DescribeAccountLimitsResult
export DescribeAccountLimitsResult

function DescribeAccountLimits(env::AWSEnv)
    resp::AutoScalingResponse = autoscaling_execute(env, "DescribeAccountLimits")
    if (resp.pd !== nothing) && (resp.obj === nothing)
        resp.obj = DescribeAccountLimitsResult(resp.pd)
    end
    resp
end
export DescribeAccountLimits

type CompleteLifecycleActionRequest <: AbstractAWSType
    autoScalingGroupName::Union{Void,String}
    instanceId::Union{Void,String}
    lifecycleActionResult::Union{Void,String}
    lifecycleActionToken::Union{Void,String}
    lifecycleHookName::Union{Void,String}
    function CompleteLifecycleActionRequest(;autoScalingGroupName=nothing, instanceId=nothing, lifecycleActionResult=nothing, lifecycleActionToken=nothing, lifecycleHookName=nothing)
        new(autoScalingGroupName, instanceId, lifecycleActionResult, lifecycleActionToken, lifecycleHookName)
    end
    CompleteLifecycleActionRequest(pd) = parse_from_xml(CompleteLifecycleActionRequest, AutoScalingTypeDict, pd)
end # CompleteLifecycleActionRequest
export CompleteLifecycleActionRequest

function CompleteLifecycleAction(env::AWSEnv, msg::CompleteLifecycleActionRequest)
    resp::AutoScalingResponse = autoscaling_execute(env, "CompleteLifecycleAction", msg)
    resp
end
CompleteLifecycleAction(env::AWSEnv; kwargs...) = CompleteLifecycleAction(env, CompleteLifecycleActionRequest(; kwargs...))
export CompleteLifecycleAction

type ExecutePolicyRequest <: AbstractAWSType
    autoScalingGroupName::Union{Void,String}
    breachThreshold::Union{Void,Float64}
    honorCooldown::Union{Void,Bool}
    metricValue::Union{Void,Float64}
    policyName::Union{Void,String}
    function ExecutePolicyRequest(;autoScalingGroupName=nothing, breachThreshold=nothing, honorCooldown=nothing, metricValue=nothing, policyName=nothing)
        new(autoScalingGroupName, breachThreshold, honorCooldown, metricValue, policyName)
    end
    ExecutePolicyRequest(pd) = parse_from_xml(ExecutePolicyRequest, AutoScalingTypeDict, pd)
end # ExecutePolicyRequest
export ExecutePolicyRequest

function ExecutePolicy(env::AWSEnv, msg::ExecutePolicyRequest)
    resp::AutoScalingResponse = autoscaling_execute(env, "ExecutePolicy", msg)
    resp
end
ExecutePolicy(env::AWSEnv; kwargs...) = ExecutePolicy(env, ExecutePolicyRequest(; kwargs...))
export ExecutePolicy

type DescribeLaunchConfigurationsResult <: AbstractAWSType
    launchConfigurations::Union{Void,Array{LaunchConfiguration,1}}
    nextToken::Union{Void,String}
    function DescribeLaunchConfigurationsResult(;launchConfigurations=nothing, nextToken=nothing)
        new(launchConfigurations, nextToken)
    end
    DescribeLaunchConfigurationsResult(pd) = parse_from_xml(DescribeLaunchConfigurationsResult, AutoScalingTypeDict, pd)
end # DescribeLaunchConfigurationsResult
export DescribeLaunchConfigurationsResult

type DescribeLaunchConfigurationsRequest <: AbstractAWSType
    launchConfigurationNames::Union{Void,Array{String,1}}
    maxRecords::Union{Void,Int64}
    nextToken::Union{Void,String}
    function DescribeLaunchConfigurationsRequest(;launchConfigurationNames=nothing, maxRecords=nothing, nextToken=nothing)
        new(launchConfigurationNames, maxRecords, nextToken)
    end
    DescribeLaunchConfigurationsRequest(pd) = parse_from_xml(DescribeLaunchConfigurationsRequest, AutoScalingTypeDict, pd)
end # DescribeLaunchConfigurationsRequest
export DescribeLaunchConfigurationsRequest

function DescribeLaunchConfigurations(env::AWSEnv, msg::DescribeLaunchConfigurationsRequest)
    resp::AutoScalingResponse = autoscaling_execute(env, "DescribeLaunchConfigurations", msg)
    if (resp.pd !== nothing) && (resp.obj === nothing)
        resp.obj = DescribeLaunchConfigurationsResult(resp.pd)
    end
    resp
end
DescribeLaunchConfigurations(env::AWSEnv; kwargs...) = DescribeLaunchConfigurations(env, DescribeLaunchConfigurationsRequest(; kwargs...))
export DescribeLaunchConfigurations

type UpdateAutoScalingGroupRequest <: AbstractAWSType
    autoScalingGroupName::Union{Void,String}
    availabilityZones::Union{Void,Array{String,1}}
    defaultCooldown::Union{Void,Int64}
    desiredCapacity::Union{Void,Int64}
    healthCheckGracePeriod::Union{Void,Int64}
    healthCheckType::Union{Void,String}
    launchConfigurationName::Union{Void,String}
    maxSize::Union{Void,Int64}
    minSize::Union{Void,Int64}
    newInstancesProtectedFromScaleIn::Union{Void,Bool}
    placementGroup::Union{Void,String}
    terminationPolicies::Union{Void,Array{String,1}}
    vPCZoneIdentifier::Union{Void,String}
    function UpdateAutoScalingGroupRequest(;autoScalingGroupName=nothing, availabilityZones=nothing, defaultCooldown=nothing, desiredCapacity=nothing, healthCheckGracePeriod=nothing, healthCheckType=nothing, launchConfigurationName=nothing, maxSize=nothing, minSize=nothing, newInstancesProtectedFromScaleIn=nothing, placementGroup=nothing, terminationPolicies=nothing, vPCZoneIdentifier=nothing)
        new(autoScalingGroupName, availabilityZones, defaultCooldown, desiredCapacity, healthCheckGracePeriod, healthCheckType, launchConfigurationName, maxSize, minSize, newInstancesProtectedFromScaleIn, placementGroup, terminationPolicies, vPCZoneIdentifier)
    end
    UpdateAutoScalingGroupRequest(pd) = parse_from_xml(UpdateAutoScalingGroupRequest, AutoScalingTypeDict, pd)
end # UpdateAutoScalingGroupRequest
export UpdateAutoScalingGroupRequest

function UpdateAutoScalingGroup(env::AWSEnv, msg::UpdateAutoScalingGroupRequest)
    resp::AutoScalingResponse = autoscaling_execute(env, "UpdateAutoScalingGroup", msg)
    resp
end
UpdateAutoScalingGroup(env::AWSEnv; kwargs...) = UpdateAutoScalingGroup(env, UpdateAutoScalingGroupRequest(; kwargs...))
export UpdateAutoScalingGroup

type DescribeTerminationPolicyTypesResult <: AbstractAWSType
    terminationPolicyTypes::Union{Void,Array{String,1}}
    function DescribeTerminationPolicyTypesResult(;terminationPolicyTypes=nothing)
        new(terminationPolicyTypes)
    end
    DescribeTerminationPolicyTypesResult(pd) = parse_from_xml(DescribeTerminationPolicyTypesResult, AutoScalingTypeDict, pd)
end # DescribeTerminationPolicyTypesResult
export DescribeTerminationPolicyTypesResult

function DescribeTerminationPolicyTypes(env::AWSEnv)
    resp::AutoScalingResponse = autoscaling_execute(env, "DescribeTerminationPolicyTypes")
    if (resp.pd !== nothing) && (resp.obj === nothing)
        resp.obj = DescribeTerminationPolicyTypesResult(resp.pd)
    end
    resp
end
export DescribeTerminationPolicyTypes

type DescribeAutoScalingGroupsResult <: AbstractAWSType
    autoScalingGroups::Union{Void,Array{AutoScalingGroup,1}}
    nextToken::Union{Void,String}
    function DescribeAutoScalingGroupsResult(;autoScalingGroups=nothing, nextToken=nothing)
        new(autoScalingGroups, nextToken)
    end
    DescribeAutoScalingGroupsResult(pd) = parse_from_xml(DescribeAutoScalingGroupsResult, AutoScalingTypeDict, pd)
end # DescribeAutoScalingGroupsResult
export DescribeAutoScalingGroupsResult

type DescribeAutoScalingGroupsRequest <: AbstractAWSType
    autoScalingGroupNames::Union{Void,Array{String,1}}
    maxRecords::Union{Void,Int64}
    nextToken::Union{Void,String}
    function DescribeAutoScalingGroupsRequest(;autoScalingGroupNames=nothing, maxRecords=nothing, nextToken=nothing)
        new(autoScalingGroupNames, maxRecords, nextToken)
    end
    DescribeAutoScalingGroupsRequest(pd) = parse_from_xml(DescribeAutoScalingGroupsRequest, AutoScalingTypeDict, pd)
end # DescribeAutoScalingGroupsRequest
export DescribeAutoScalingGroupsRequest

function DescribeAutoScalingGroups(env::AWSEnv, msg::DescribeAutoScalingGroupsRequest)
    resp::AutoScalingResponse = autoscaling_execute(env, "DescribeAutoScalingGroups", msg)
    if (resp.pd !== nothing) && (resp.obj === nothing)
        resp.obj = DescribeAutoScalingGroupsResult(resp.pd)
    end
    resp
end
DescribeAutoScalingGroups(env::AWSEnv; kwargs...) = DescribeAutoScalingGroups(env, DescribeAutoScalingGroupsRequest(; kwargs...))
export DescribeAutoScalingGroups

type SetInstanceProtectionRequest <: AbstractAWSType
    autoScalingGroupName::Union{Void,String}
    instanceIds::Union{Void,Array{String,1}}
    protectedFromScaleIn::Union{Void,Bool}
    function SetInstanceProtectionRequest(;autoScalingGroupName=nothing, instanceIds=nothing, protectedFromScaleIn=nothing)
        new(autoScalingGroupName, instanceIds, protectedFromScaleIn)
    end
    SetInstanceProtectionRequest(pd) = parse_from_xml(SetInstanceProtectionRequest, AutoScalingTypeDict, pd)
end # SetInstanceProtectionRequest
export SetInstanceProtectionRequest

function SetInstanceProtection(env::AWSEnv, msg::SetInstanceProtectionRequest)
    resp::AutoScalingResponse = autoscaling_execute(env, "SetInstanceProtection", msg)
    resp
end
SetInstanceProtection(env::AWSEnv; kwargs...) = SetInstanceProtection(env, SetInstanceProtectionRequest(; kwargs...))
export SetInstanceProtection

type DescribePoliciesResult <: AbstractAWSType
    nextToken::Union{Void,String}
    scalingPolicies::Union{Void,Array{ScalingPolicy,1}}
    function DescribePoliciesResult(;nextToken=nothing, scalingPolicies=nothing)
        new(nextToken, scalingPolicies)
    end
    DescribePoliciesResult(pd) = parse_from_xml(DescribePoliciesResult, AutoScalingTypeDict, pd)
end # DescribePoliciesResult
export DescribePoliciesResult

type DescribePoliciesRequest <: AbstractAWSType
    autoScalingGroupName::Union{Void,String}
    maxRecords::Union{Void,Int64}
    nextToken::Union{Void,String}
    policyNames::Union{Void,Array{String,1}}
    policyTypes::Union{Void,Array{String,1}}
    function DescribePoliciesRequest(;autoScalingGroupName=nothing, maxRecords=nothing, nextToken=nothing, policyNames=nothing, policyTypes=nothing)
        new(autoScalingGroupName, maxRecords, nextToken, policyNames, policyTypes)
    end
    DescribePoliciesRequest(pd) = parse_from_xml(DescribePoliciesRequest, AutoScalingTypeDict, pd)
end # DescribePoliciesRequest
export DescribePoliciesRequest

function DescribePolicies(env::AWSEnv, msg::DescribePoliciesRequest)
    resp::AutoScalingResponse = autoscaling_execute(env, "DescribePolicies", msg)
    if (resp.pd !== nothing) && (resp.obj === nothing)
        resp.obj = DescribePoliciesResult(resp.pd)
    end
    resp
end
DescribePolicies(env::AWSEnv; kwargs...) = DescribePolicies(env, DescribePoliciesRequest(; kwargs...))
export DescribePolicies

type EnableMetricsCollectionRequest <: AbstractAWSType
    autoScalingGroupName::Union{Void,String}
    granularity::Union{Void,String}
    metrics::Union{Void,Array{String,1}}
    function EnableMetricsCollectionRequest(;autoScalingGroupName=nothing, granularity=nothing, metrics=nothing)
        new(autoScalingGroupName, granularity, metrics)
    end
    EnableMetricsCollectionRequest(pd) = parse_from_xml(EnableMetricsCollectionRequest, AutoScalingTypeDict, pd)
end # EnableMetricsCollectionRequest
export EnableMetricsCollectionRequest

function EnableMetricsCollection(env::AWSEnv, msg::EnableMetricsCollectionRequest)
    resp::AutoScalingResponse = autoscaling_execute(env, "EnableMetricsCollection", msg)
    resp
end
EnableMetricsCollection(env::AWSEnv; kwargs...) = EnableMetricsCollection(env, EnableMetricsCollectionRequest(; kwargs...))
export EnableMetricsCollection

type ExitStandbyResult <: AbstractAWSType
    activities::Union{Void,Array{Activity,1}}
    function ExitStandbyResult(;activities=nothing)
        new(activities)
    end
    ExitStandbyResult(pd) = parse_from_xml(ExitStandbyResult, AutoScalingTypeDict, pd)
end # ExitStandbyResult
export ExitStandbyResult

type ExitStandbyRequest <: AbstractAWSType
    autoScalingGroupName::Union{Void,String}
    instanceIds::Union{Void,Array{String,1}}
    function ExitStandbyRequest(;autoScalingGroupName=nothing, instanceIds=nothing)
        new(autoScalingGroupName, instanceIds)
    end
    ExitStandbyRequest(pd) = parse_from_xml(ExitStandbyRequest, AutoScalingTypeDict, pd)
end # ExitStandbyRequest
export ExitStandbyRequest

function ExitStandby(env::AWSEnv, msg::ExitStandbyRequest)
    resp::AutoScalingResponse = autoscaling_execute(env, "ExitStandby", msg)
    if (resp.pd !== nothing) && (resp.obj === nothing)
        resp.obj = ExitStandbyResult(resp.pd)
    end
    resp
end
ExitStandby(env::AWSEnv; kwargs...) = ExitStandby(env, ExitStandbyRequest(; kwargs...))
export ExitStandby

type DescribeNotificationConfigurationsResult <: AbstractAWSType
    nextToken::Union{Void,String}
    notificationConfigurations::Union{Void,Array{NotificationConfiguration,1}}
    function DescribeNotificationConfigurationsResult(;nextToken=nothing, notificationConfigurations=nothing)
        new(nextToken, notificationConfigurations)
    end
    DescribeNotificationConfigurationsResult(pd) = parse_from_xml(DescribeNotificationConfigurationsResult, AutoScalingTypeDict, pd)
end # DescribeNotificationConfigurationsResult
export DescribeNotificationConfigurationsResult

type DescribeNotificationConfigurationsRequest <: AbstractAWSType
    autoScalingGroupNames::Union{Void,Array{String,1}}
    maxRecords::Union{Void,Int64}
    nextToken::Union{Void,String}
    function DescribeNotificationConfigurationsRequest(;autoScalingGroupNames=nothing, maxRecords=nothing, nextToken=nothing)
        new(autoScalingGroupNames, maxRecords, nextToken)
    end
    DescribeNotificationConfigurationsRequest(pd) = parse_from_xml(DescribeNotificationConfigurationsRequest, AutoScalingTypeDict, pd)
end # DescribeNotificationConfigurationsRequest
export DescribeNotificationConfigurationsRequest

function DescribeNotificationConfigurations(env::AWSEnv, msg::DescribeNotificationConfigurationsRequest)
    resp::AutoScalingResponse = autoscaling_execute(env, "DescribeNotificationConfigurations", msg)
    if (resp.pd !== nothing) && (resp.obj === nothing)
        resp.obj = DescribeNotificationConfigurationsResult(resp.pd)
    end
    resp
end
DescribeNotificationConfigurations(env::AWSEnv; kwargs...) = DescribeNotificationConfigurations(env, DescribeNotificationConfigurationsRequest(; kwargs...))
export DescribeNotificationConfigurations

type CreateAutoScalingGroupRequest <: AbstractAWSType
    autoScalingGroupName::Union{Void,String}
    availabilityZones::Union{Void,Array{String,1}}
    defaultCooldown::Union{Void,Int64}
    desiredCapacity::Union{Void,Int64}
    healthCheckGracePeriod::Union{Void,Int64}
    healthCheckType::Union{Void,String}
    instanceId::Union{Void,String}
    launchConfigurationName::Union{Void,String}
    loadBalancerNames::Union{Void,Array{String,1}}
    maxSize::Union{Void,Int64}
    minSize::Union{Void,Int64}
    newInstancesProtectedFromScaleIn::Union{Void,Bool}
    placementGroup::Union{Void,String}
    tags::Union{Void,Array{Tag,1}}
    targetGroupARNs::Union{Void,Array{String,1}}
    terminationPolicies::Union{Void,Array{String,1}}
    vPCZoneIdentifier::Union{Void,String}
    function CreateAutoScalingGroupRequest(;autoScalingGroupName=nothing, availabilityZones=nothing, defaultCooldown=nothing, desiredCapacity=nothing, healthCheckGracePeriod=nothing, healthCheckType=nothing, instanceId=nothing, launchConfigurationName=nothing, loadBalancerNames=nothing, maxSize=nothing, minSize=nothing, newInstancesProtectedFromScaleIn=nothing, placementGroup=nothing, tags=nothing, targetGroupARNs=nothing, terminationPolicies=nothing, vPCZoneIdentifier=nothing)
        new(autoScalingGroupName, availabilityZones, defaultCooldown, desiredCapacity, healthCheckGracePeriod, healthCheckType, instanceId, launchConfigurationName, loadBalancerNames, maxSize, minSize, newInstancesProtectedFromScaleIn, placementGroup, tags, targetGroupARNs, terminationPolicies, vPCZoneIdentifier)
    end
    CreateAutoScalingGroupRequest(pd) = parse_from_xml(CreateAutoScalingGroupRequest, AutoScalingTypeDict, pd)
end # CreateAutoScalingGroupRequest
export CreateAutoScalingGroupRequest

function CreateAutoScalingGroup(env::AWSEnv, msg::CreateAutoScalingGroupRequest)
    resp::AutoScalingResponse = autoscaling_execute(env, "CreateAutoScalingGroup", msg)
    resp
end
CreateAutoScalingGroup(env::AWSEnv; kwargs...) = CreateAutoScalingGroup(env, CreateAutoScalingGroupRequest(; kwargs...))
export CreateAutoScalingGroup

type DescribeScalingProcessTypesResult <: AbstractAWSType
    processes::Union{Void,Array{ProcessType,1}}
    function DescribeScalingProcessTypesResult(;processes=nothing)
        new(processes)
    end
    DescribeScalingProcessTypesResult(pd) = parse_from_xml(DescribeScalingProcessTypesResult, AutoScalingTypeDict, pd)
end # DescribeScalingProcessTypesResult
export DescribeScalingProcessTypesResult

function DescribeScalingProcessTypes(env::AWSEnv)
    resp::AutoScalingResponse = autoscaling_execute(env, "DescribeScalingProcessTypes")
    if (resp.pd !== nothing) && (resp.obj === nothing)
        resp.obj = DescribeScalingProcessTypesResult(resp.pd)
    end
    resp
end
export DescribeScalingProcessTypes

type DetachLoadBalancerTargetGroupsRequest <: AbstractAWSType
    autoScalingGroupName::Union{Void,String}
    targetGroupARNs::Union{Void,Array{String,1}}
    function DetachLoadBalancerTargetGroupsRequest(;autoScalingGroupName=nothing, targetGroupARNs=nothing)
        new(autoScalingGroupName, targetGroupARNs)
    end
    DetachLoadBalancerTargetGroupsRequest(pd) = parse_from_xml(DetachLoadBalancerTargetGroupsRequest, AutoScalingTypeDict, pd)
end # DetachLoadBalancerTargetGroupsRequest
export DetachLoadBalancerTargetGroupsRequest

function DetachLoadBalancerTargetGroups(env::AWSEnv, msg::DetachLoadBalancerTargetGroupsRequest)
    resp::AutoScalingResponse = autoscaling_execute(env, "DetachLoadBalancerTargetGroups", msg)
    resp
end
DetachLoadBalancerTargetGroups(env::AWSEnv; kwargs...) = DetachLoadBalancerTargetGroups(env, DetachLoadBalancerTargetGroupsRequest(; kwargs...))
export DetachLoadBalancerTargetGroups

type PutScalingPolicyResult <: AbstractAWSType
    alarms::Union{Void,Array{Alarm,1}}
    policyARN::Union{Void,String}
    function PutScalingPolicyResult(;alarms=nothing, policyARN=nothing)
        new(alarms, policyARN)
    end
    PutScalingPolicyResult(pd) = parse_from_xml(PutScalingPolicyResult, AutoScalingTypeDict, pd)
end # PutScalingPolicyResult
export PutScalingPolicyResult

type PutScalingPolicyRequest <: AbstractAWSType
    adjustmentType::Union{Void,String}
    autoScalingGroupName::Union{Void,String}
    cooldown::Union{Void,Int64}
    estimatedInstanceWarmup::Union{Void,Int64}
    metricAggregationType::Union{Void,String}
    minAdjustmentMagnitude::Union{Void,Int64}
    minAdjustmentStep::Union{Void,Int64}
    policyName::Union{Void,String}
    policyType::Union{Void,String}
    scalingAdjustment::Union{Void,Int64}
    stepAdjustments::Union{Void,Array{StepAdjustment,1}}
    targetTrackingConfiguration::Union{Void,TargetTrackingConfiguration}
    function PutScalingPolicyRequest(;adjustmentType=nothing, autoScalingGroupName=nothing, cooldown=nothing, estimatedInstanceWarmup=nothing, metricAggregationType=nothing, minAdjustmentMagnitude=nothing, minAdjustmentStep=nothing, policyName=nothing, policyType=nothing, scalingAdjustment=nothing, stepAdjustments=nothing, targetTrackingConfiguration=nothing)
        new(adjustmentType, autoScalingGroupName, cooldown, estimatedInstanceWarmup, metricAggregationType, minAdjustmentMagnitude, minAdjustmentStep, policyName, policyType, scalingAdjustment, stepAdjustments, targetTrackingConfiguration)
    end
    PutScalingPolicyRequest(pd) = parse_from_xml(PutScalingPolicyRequest, AutoScalingTypeDict, pd)
end # PutScalingPolicyRequest
export PutScalingPolicyRequest

function PutScalingPolicy(env::AWSEnv, msg::PutScalingPolicyRequest)
    resp::AutoScalingResponse = autoscaling_execute(env, "PutScalingPolicy", msg)
    if (resp.pd !== nothing) && (resp.obj === nothing)
        resp.obj = PutScalingPolicyResult(resp.pd)
    end
    resp
end
PutScalingPolicy(env::AWSEnv; kwargs...) = PutScalingPolicy(env, PutScalingPolicyRequest(; kwargs...))
export PutScalingPolicy

type DescribeScalingActivitiesResult <: AbstractAWSType
    activities::Union{Void,Array{Activity,1}}
    nextToken::Union{Void,String}
    function DescribeScalingActivitiesResult(;activities=nothing, nextToken=nothing)
        new(activities, nextToken)
    end
    DescribeScalingActivitiesResult(pd) = parse_from_xml(DescribeScalingActivitiesResult, AutoScalingTypeDict, pd)
end # DescribeScalingActivitiesResult
export DescribeScalingActivitiesResult

type DescribeScalingActivitiesRequest <: AbstractAWSType
    activityIds::Union{Void,Array{String,1}}
    autoScalingGroupName::Union{Void,String}
    maxRecords::Union{Void,Int64}
    nextToken::Union{Void,String}
    function DescribeScalingActivitiesRequest(;activityIds=nothing, autoScalingGroupName=nothing, maxRecords=nothing, nextToken=nothing)
        new(activityIds, autoScalingGroupName, maxRecords, nextToken)
    end
    DescribeScalingActivitiesRequest(pd) = parse_from_xml(DescribeScalingActivitiesRequest, AutoScalingTypeDict, pd)
end # DescribeScalingActivitiesRequest
export DescribeScalingActivitiesRequest

function DescribeScalingActivities(env::AWSEnv, msg::DescribeScalingActivitiesRequest)
    resp::AutoScalingResponse = autoscaling_execute(env, "DescribeScalingActivities", msg)
    if (resp.pd !== nothing) && (resp.obj === nothing)
        resp.obj = DescribeScalingActivitiesResult(resp.pd)
    end
    resp
end
DescribeScalingActivities(env::AWSEnv; kwargs...) = DescribeScalingActivities(env, DescribeScalingActivitiesRequest(; kwargs...))
export DescribeScalingActivities

type DeleteLifecycleHookRequest <: AbstractAWSType
    autoScalingGroupName::Union{Void,String}
    lifecycleHookName::Union{Void,String}
    function DeleteLifecycleHookRequest(;autoScalingGroupName=nothing, lifecycleHookName=nothing)
        new(autoScalingGroupName, lifecycleHookName)
    end
    DeleteLifecycleHookRequest(pd) = parse_from_xml(DeleteLifecycleHookRequest, AutoScalingTypeDict, pd)
end # DeleteLifecycleHookRequest
export DeleteLifecycleHookRequest

function DeleteLifecycleHook(env::AWSEnv, msg::DeleteLifecycleHookRequest)
    resp::AutoScalingResponse = autoscaling_execute(env, "DeleteLifecycleHook", msg)
    resp
end
DeleteLifecycleHook(env::AWSEnv; kwargs...) = DeleteLifecycleHook(env, DeleteLifecycleHookRequest(; kwargs...))
export DeleteLifecycleHook

type DeletePolicyRequest <: AbstractAWSType
    autoScalingGroupName::Union{Void,String}
    policyName::Union{Void,String}
    function DeletePolicyRequest(;autoScalingGroupName=nothing, policyName=nothing)
        new(autoScalingGroupName, policyName)
    end
    DeletePolicyRequest(pd) = parse_from_xml(DeletePolicyRequest, AutoScalingTypeDict, pd)
end # DeletePolicyRequest
export DeletePolicyRequest

function DeletePolicy(env::AWSEnv, msg::DeletePolicyRequest)
    resp::AutoScalingResponse = autoscaling_execute(env, "DeletePolicy", msg)
    resp
end
DeletePolicy(env::AWSEnv; kwargs...) = DeletePolicy(env, DeletePolicyRequest(; kwargs...))
export DeletePolicy

type DescribeAdjustmentTypesResult <: AbstractAWSType
    adjustmentTypes::Union{Void,Array{AdjustmentType,1}}
    function DescribeAdjustmentTypesResult(;adjustmentTypes=nothing)
        new(adjustmentTypes)
    end
    DescribeAdjustmentTypesResult(pd) = parse_from_xml(DescribeAdjustmentTypesResult, AutoScalingTypeDict, pd)
end # DescribeAdjustmentTypesResult
export DescribeAdjustmentTypesResult

function DescribeAdjustmentTypes(env::AWSEnv)
    resp::AutoScalingResponse = autoscaling_execute(env, "DescribeAdjustmentTypes")
    if (resp.pd !== nothing) && (resp.obj === nothing)
        resp.obj = DescribeAdjustmentTypesResult(resp.pd)
    end
    resp
end
export DescribeAdjustmentTypes

type TerminateInstanceInAutoScalingGroupResult <: AbstractAWSType
    activity::Union{Void,Activity}
    function TerminateInstanceInAutoScalingGroupResult(;activity=nothing)
        new(activity)
    end
    TerminateInstanceInAutoScalingGroupResult(pd) = parse_from_xml(TerminateInstanceInAutoScalingGroupResult, AutoScalingTypeDict, pd)
end # TerminateInstanceInAutoScalingGroupResult
export TerminateInstanceInAutoScalingGroupResult

type TerminateInstanceInAutoScalingGroupRequest <: AbstractAWSType
    instanceId::Union{Void,String}
    shouldDecrementDesiredCapacity::Union{Void,Bool}
    function TerminateInstanceInAutoScalingGroupRequest(;instanceId=nothing, shouldDecrementDesiredCapacity=nothing)
        new(instanceId, shouldDecrementDesiredCapacity)
    end
    TerminateInstanceInAutoScalingGroupRequest(pd) = parse_from_xml(TerminateInstanceInAutoScalingGroupRequest, AutoScalingTypeDict, pd)
end # TerminateInstanceInAutoScalingGroupRequest
export TerminateInstanceInAutoScalingGroupRequest

function TerminateInstanceInAutoScalingGroup(env::AWSEnv, msg::TerminateInstanceInAutoScalingGroupRequest)
    resp::AutoScalingResponse = autoscaling_execute(env, "TerminateInstanceInAutoScalingGroup", msg)
    if (resp.pd !== nothing) && (resp.obj === nothing)
        resp.obj = TerminateInstanceInAutoScalingGroupResult(resp.pd)
    end
    resp
end
TerminateInstanceInAutoScalingGroup(env::AWSEnv; kwargs...) = TerminateInstanceInAutoScalingGroup(env, TerminateInstanceInAutoScalingGroupRequest(; kwargs...))
export TerminateInstanceInAutoScalingGroup

type RecordLifecycleActionHeartbeatRequest <: AbstractAWSType
    autoScalingGroupName::Union{Void,String}
    instanceId::Union{Void,String}
    lifecycleActionToken::Union{Void,String}
    lifecycleHookName::Union{Void,String}
    function RecordLifecycleActionHeartbeatRequest(;autoScalingGroupName=nothing, instanceId=nothing, lifecycleActionToken=nothing, lifecycleHookName=nothing)
        new(autoScalingGroupName, instanceId, lifecycleActionToken, lifecycleHookName)
    end
    RecordLifecycleActionHeartbeatRequest(pd) = parse_from_xml(RecordLifecycleActionHeartbeatRequest, AutoScalingTypeDict, pd)
end # RecordLifecycleActionHeartbeatRequest
export RecordLifecycleActionHeartbeatRequest

function RecordLifecycleActionHeartbeat(env::AWSEnv, msg::RecordLifecycleActionHeartbeatRequest)
    resp::AutoScalingResponse = autoscaling_execute(env, "RecordLifecycleActionHeartbeat", msg)
    resp
end
RecordLifecycleActionHeartbeat(env::AWSEnv; kwargs...) = RecordLifecycleActionHeartbeat(env, RecordLifecycleActionHeartbeatRequest(; kwargs...))
export RecordLifecycleActionHeartbeat

type DeleteTagsRequest <: AbstractAWSType
    tags::Union{Void,Array{Tag,1}}
    function DeleteTagsRequest(;tags=nothing)
        new(tags)
    end
    DeleteTagsRequest(pd) = parse_from_xml(DeleteTagsRequest, AutoScalingTypeDict, pd)
end # DeleteTagsRequest
export DeleteTagsRequest

function DeleteTags(env::AWSEnv, msg::DeleteTagsRequest)
    resp::AutoScalingResponse = autoscaling_execute(env, "DeleteTags", msg)
    resp
end
DeleteTags(env::AWSEnv; kwargs...) = DeleteTags(env, DeleteTagsRequest(; kwargs...))
export DeleteTags

type AttachLoadBalancerTargetGroupsRequest <: AbstractAWSType
    autoScalingGroupName::Union{Void,String}
    targetGroupARNs::Union{Void,Array{String,1}}
    function AttachLoadBalancerTargetGroupsRequest(;autoScalingGroupName=nothing, targetGroupARNs=nothing)
        new(autoScalingGroupName, targetGroupARNs)
    end
    AttachLoadBalancerTargetGroupsRequest(pd) = parse_from_xml(AttachLoadBalancerTargetGroupsRequest, AutoScalingTypeDict, pd)
end # AttachLoadBalancerTargetGroupsRequest
export AttachLoadBalancerTargetGroupsRequest

function AttachLoadBalancerTargetGroups(env::AWSEnv, msg::AttachLoadBalancerTargetGroupsRequest)
    resp::AutoScalingResponse = autoscaling_execute(env, "AttachLoadBalancerTargetGroups", msg)
    resp
end
AttachLoadBalancerTargetGroups(env::AWSEnv; kwargs...) = AttachLoadBalancerTargetGroups(env, AttachLoadBalancerTargetGroupsRequest(; kwargs...))
export AttachLoadBalancerTargetGroups


text:
function plane_strain_voigt_hooke_matrix_2d(lambda,mu)
    l2mu = lambda+2.0*mu
    matrix = [l2mu    lambda  0.0
              lambda  l2mu    0.0
              0.0     0.0     mu]
    return matrix
end

function plane_strain_voigt_hooke_matrix(lambda,mu,dim)
    if dim == 2
        return plane_strain_voigt_hooke_matrix_2d(lambda,mu)
    elseif dim == 3
        throw(ArgumentError("dim == 3 has not been implemented yet"))
    else
        throw(ArgumentError("Expected dim ∈ {1,2} got dim = $dim"))
    end
end


text:
s = BenchmarkGroup()
suite["flow"] = s

edgs = [
  (1,2,10),(1,3,5),(1,4,15),(2,3,4),(2,5,9),
  (2,6,15),(3,4,4),(3,6,8),(4,7,16),(5,6,15),
  (5,8,10),(6,7,15),(6,8,10),(7,3,6),(7,8,10)
]

flow_graph = DiGraph(8)
capacity_matrix = zeros(Int,8,8)
for e in edgs
    u,v,f = e
    add_edge!(flow_graph,u,v)
    capacity_matrix[u,v] = f
end

s["push_relabel","$flow_graph"] = @benchmarkable maximum_flow($flow_graph, 1, 8
                    , $capacity_matrix, algorithm=PushRelabelAlgorithm())
s["dinic","$flow_graph"] = @benchmarkable maximum_flow($flow_graph, 1, 8
                    , $capacity_matrix, algorithm=DinicAlgorithm())

s["boykov","$flow_graph"] = @benchmarkable maximum_flow($flow_graph, 1, 8
                    , $capacity_matrix, algorithm=BoykovKolmogorovAlgorithm())

# from LittleScienceTools.RFIM
Random.seed!(17)
N = 200
g = random_regular_graph(N, 3, seed=1)
h = randn(N)
J = 1.

function net_capacity(g::AGraph, h::Vector{T}, J::AbstractFloat) where T
    N = nv(g)
    dg = digraph(g)
    add_vertices!(dg, 2)
    source = N+1
    target = N+2
    for i=1:N
        if h[i] > 0
            add_edge!(dg, source, i)
            add_edge!(dg, i, source)
        else
            add_edge!(dg, i, target)
            add_edge!(dg, target, i)
        end
    end

    c = spzeros(N+2, N+2)
    for i=1:N
        neigs = neighbors(dg, i)
        for j in neigs
            if j <= N
                c[i,j] = J
            elseif j == target
                c[i,j] = abs(h[i])
            end

        end
    end
    for j in neighbors(dg, source)
        c[source,j] = abs(h[j])
    end

    return dg, c
end

dg, c = net_capacity(g, h, J)

s["push_relabel","$dg"] = @benchmarkable maximum_flow($dg, $(N+1), $(N+2)
                    , $c, algorithm=PushRelabelAlgorithm())
s["dinic","$dg"] = @benchmarkable maximum_flow($dg, $(N+1), $(N+2)
                    , $c, algorithm=DinicAlgorithm())
s["boykov","$dg"] = @benchmarkable maximum_flow($dg, $(N+1),$(N+2)
                    , $c, algorithm=BoykovKolmogorovAlgorithm())


text:
include("1.1.2.x P(x) (a+b x^2)^p.jl")
include("1.1.2.y P(x) (c x)^m (a+b x^2)^p.jl")

max_stars_repo_path: src/rules/1 Algebraic functions/1.1 Binomial products/1.1.2 Quadratic/.jl


text:
"""
Baseclass for all observation dimensions.
"""
abstract type ObsDimension end

"""
    module ObsDim

Singleton types to define which dimension of some data structure
(e.g. some `Array`) denotes the observations.

- `ObsDim.First()`
- `ObsDim.Last()`
- `ObsDim.Constant(dim)`

Used for efficient dispatching
"""
module ObsDim
    using ..LearnBase: ObsDimension

    """
    Default value for most functions. Denotes that the concept of
    an observation dimension is not defined for the given data.
    """
    struct Undefined <: ObsDimension end

    """
        ObsDim.Last <: ObsDimension

    Defines that the last dimension denotes the observations
    """
    struct Last <: ObsDimension end

    """
        ObsDim.Constant{DIM} <: ObsDimension

    Defines that the dimension `DIM` denotes the observations
    """
    struct Constant{DIM} <: ObsDimension end
    Constant(dim::Int) = Constant{dim}()

    """
        ObsDim.First <: ObsDimension

    Defines that the first dimension denotes the observations
    """
    const First = Constant{1}
end

Base.convert(::Type{ObsDimension}, dim) = throw(ArgumentError("Unknown way to specify a obsdim: $dim"))
Base.convert(::Type{ObsDimension}, dim::ObsDimension) = dim
Base.convert(::Type{ObsDimension}, ::Nothing) = ObsDim.Undefined()
Base.convert(::Type{ObsDimension}, dim::Int) = ObsDim.Constant(dim)
Base.convert(::Type{ObsDimension}, dim::String) = convert(ObsDimension, Symbol(lowercase(dim)))
Base.convert(::Type{ObsDimension}, dims::Tuple) = map(d->convert(ObsDimension, d), dims)
function Base.convert(::Type{ObsDimension}, dim::Symbol)
    if dim == :first || dim == :begin
        ObsDim.First()
    elseif dim == Symbol("end") || dim == :last
        ObsDim.Last()
    elseif dim == Symbol("nothing") || dim == :none || dim == :null || dim == :na || dim == :undefined
        ObsDim.Undefined()
    else
        throw(ArgumentError("Unknown way to specify a obsdim: $dim"))
    end
end

"""
    default_obsdim(data)

The specify the default obsdim for a specific type of data.
Defaults to `ObsDim.Undefined()`
"""
default_obsdim(data) = ObsDim.Undefined()
default_obsdim(A::AbstractArray) = ObsDim.Last()
default_obsdim(tup::Tuple) = map(default_obsdim, tup)

"""
     datasubset(data, [idx], [obsdim])

Return a lazy subset of the observations in `data` that correspond
to the given `idx`. No data should be copied except of the
indices. Note that `idx` can be of type `Int` or `AbstractVector`.
Both options must be supported by a custom type.

If it makes sense for the type of `data`, `obsdim` can be used
to disptach on which dimension of `data` denotes the observations.
See `?ObsDim`.
"""
function datasubset end


text:
# Copyright (c) 2021, Joseph M. Rutherford
# All rights reserved.
#
# Code provided under the license contained in the LICENSE file.
# Copyright (c) 2021, Joseph M. Rutherford
# All rights reserved.
#
# Code provided under the license contained in the LICENSE file.
#
# This file imports all non-*_test sudoku_*.jl scripts

module Sudoku

export as_text_grid, random_solution, random_puzzle, SolvablePuzzle, solve_puzzle

include("sudoku_common.jl")
include("sudoku_display.jl")
include("sudoku_permute.jl")
include("sudoku_compose.jl")
include("sudoku_valid.jl")
include("sudoku_solve.jl")

end

max_stars_repo_name: joseph-m-rutherford/sudoku-julia

max_issues_repo_name: joseph-m-rutherford/sudoku-julia

max_forks_repo_name: joseph-m-rutherford/sudoku-julia


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

using Markdown
using InteractiveUtils

# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).
macro bind(def, element)
    quote
        local el = $(esc(element))
        global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : missing
        el
    end
end

# ╔═╡ 6e3ef066-d115-11eb-2338-013a707dfe8a
begin
	using PlutoUI
	using DataFrames
	using Statistics
	using RollingFunctions
	using HTTP
	using JSON
	using Chain
	using Tables
	using PerceptualColourMaps
	using Gadfly
	Gadfly.set_default_plot_size(16cm, 14cm)
end

# ╔═╡ 41bd06a2-e7bd-46c6-9249-6e69223b0e11
begin
	HASRUA_ENDPOINT_URL = "http://rldl12.eecs.umich.edu:1200/v1/graphql"
	HASURA_ADMIN_SECRET = "hNuxFSTJMk28GMiFDpZDbviKtelFQamcb20UJiYZSIZ4LYsyLCCwQFYA6Y8HRSUo"
end;

# ╔═╡ 94185c13-b6d2-4337-b5ce-336f5e128032
function gql_query(query:: String; variables:: Dict = nothing)
	r = HTTP.request(
		"POST",
		HASRUA_ENDPOINT_URL;
		verbose=3,
		body= JSON.json(Dict("query" => query, "variables" => variables)) ,
		headers=Dict("x-hasura-admin-secret" => HASURA_ADMIN_SECRET),
	)
	@chain r begin
		_.body
		String
		JSON.parse(_, null=missing)
		_["data"]
	end
end

# ╔═╡ 8f417ce0-fa72-4b12-8d3b-8f88b2e5a2bf
function latest_runs(n::Integer)::Vector{AbstractDict}
	query = """
	  query latestRuns(\$limit: Int!){
		run(order_by: {id: desc}, limit: \$limit) {
		  id
		  metadata
		  sweep{
	        id
		  }
		}
	  }
	  """
	gql_query(query; variables=Dict("limit" => n))["run"]
end

# ╔═╡ 48be0808-f22a-4b72-a078-b2f2552db327
function format_logs(run::AbstractDict)
	sweep_id = ismissing(run["sweep"]) ? nothing : run["sweep"]["id"]
	@chain run["run_logs"] begin
		map(x -> Dict((Symbol(replace(k, " " => "_")) => v for (k,v) in x["log"])), _)
		DataFrame
		insertcols!(:run_id => run["id"], :sweep_id => sweep_id)
	end
end

# ╔═╡ f4d4785e-0df1-4882-8eb9-005ff2a50614
function format_run(run::AbstractDict)
	sweep_id = something(get(run, "sweep", nothing), Dict("id" => nothing))["id"]
	data = run["metadata"]
	push!(data, pop!(data, "parameters")...)
	items = [Symbol(replace(k, " " => "_")) => v for (k, v) in data]
	push!(items, :run_id => run["id"], :sweep_id => sweep_id)
	Dict(items)
end

# ╔═╡ 0ca92cdc-102c-45e7-a5b0-17087b9ba634
function format_runs(runs::Vector)::DataFrame
	rows = map(format_run, runs)
	cols = map(keys, rows) |> Iterators.flatten |> Set
	for r in rows
		for c in setdiff(cols, keys(r))
			r[c] = nothing
		end
	end
	df = DataFrame(rows)
	leading = [:run_id, :sweep_id]
	cols = filter(x -> !(x in leading), propertynames(df))
	df[!, vcat(leading, cols)]
end

# ╔═╡ 68e80154-126b-403c-a593-d896cdf96ef2
function run_data(ids::AbstractVector{Int}, runs::AbstractDataFrame)
	query = """
		query getRuns(\$ids: [Int!]) {
		  run(where: {id: {_in: \$ids}}) {
			id
			run_logs{
			  log
			}
			metadata
			charts{
			  spec
			}
			sweep {
				id
			}
		  }
		}
  	"""
	@chain gql_query(query; variables=Dict("ids" => ids)) begin
			_["run"]
			format_logs.(_)
			DataFrame.(_)
			vcat(_...;cols=:union)
			leftjoin(runs[!, Not(:sweep_id)]; on=:run_id)
	end
end

# ╔═╡ 0f54629c-e045-47bf-90a5-36e44c05b8f0
function sweep_runs(sweep_ids::AbstractVector{Int})
	query = """
		query getSweepRuns(\$ids: [Int!]) {
		  sweep(where: {id: {_in: \$ids}}) {
			runs {
           		id
			    metadata
			    sweep{
				 id
			    }
        	}
		  }
		}
  	"""
	rows = @chain gql_query(query; variables=Dict("ids" => sweep_ids)) begin
		_["sweep"]
		map(values, _)
		Iterators.flatten
		Iterators.flatten
		collect
	end
	format_runs(rows)
end

# ╔═╡ 18147da2-1945-42e4-b140-c1375f46962b
function sweep_data(sweep_runs::AbstractDataFrame; ids = nothing)::DataFrame
	s_run_ids = sweep_runs.run_id |> unique |> collect
	if !isnothing(ids)
		s_run_ids = filter(in(ids), s_run_ids)
	end
	s_df = [run_data(collect(i), sweep_runs) for i in Iterators.partition(s_run_ids, 10)]
	s_df = vcat(s_df...; cols=:union)
	dropmissing!(s_df, :step)
end

# ╔═╡ 0135af1a-d8c8-4027-af38-7f57bbfef282
gpt_runs = sweep_runs([26, 23, 22, 19, 17])

# ╔═╡ 3ba73b7c-f5dc-4639-ab9c-c43cc992634f
gpt_df = sweep_data(gpt_runs);

# ╔═╡ 8798b46c-1b0b-4d34-93ef-1d5062f8a632
md"##### Smoothing"

# ╔═╡ bbed8889-d401-4167-9370-9927aabbc83b
@bind window_size Slider(1:200, default=100)

# ╔═╡ 5cba55d9-c7fe-4918-88b3-abbabe08c56b
function smooth_curves(df::AbstractDataFrame, y::Symbol, group_col::Symbol, window_size::Int)::DataFrame
	@chain df begin
		dropmissing!([y, group_col])
		groupby(group_col)
		pairs
		[@chain g begin
				DataFrame
				sort!(:step)
				DataFrame(
					group_col => first(k),
					:step => round.(Int, rollmedian(_.step, min(window_size, nrow(_)))),
					:mean => rollmean(_[:, y], min(window_size, nrow(_))),
					:std => rollstd(_[:, y], min(window_size, nrow(_))),
				)
				transform(
					[:mean, :std] => ((x, y) -> x - y) => [:lower],
					[:mean, :std] => ((x, y) -> x + y) => [:upper]
				)
			end for (k, g) in _]
		vcat(_...)
	end
end

# ╔═╡ 70e759a8-2f8d-46c8-aa02-c581dd17c1c4

# ╔═╡ 23d3bad8-099c-4794-806a-aaacc86b9e1a
gpt_df

# ╔═╡ 92de44db-86be-4fe5-9eb1-1ac657676b95

# ╔═╡ c252df75-fb25-470d-956d-0aa532701565
md"### Runs"

# ╔═╡ 8b4a7da4-562e-4ad7-aa8b-8a458f302508
runs = format_runs(latest_runs(10))

# ╔═╡ 163fc23c-952e-4002-be1c-0baafbccd8aa
md"#### Select runs to visualize"

# ╔═╡ fe1f61d3-2b34-4a54-9fdc-9e4504248994
begin
	checkbox_values = [
		string(r.run_id) => "$(r.run_id)"
		for r in eachrow(runs)
	]
	@bind selected_run_id_strs MultiCheckBox(
		checkbox_values;
		orientation=:column,
		select_all=true
	)
end

# ╔═╡ 26b7f618-1576-4299-b8d5-5bfef31401f1
begin
	selected_run_ids = parse.(Int, something(selected_run_id_strs, []))
	selected_runs = filter(:run_id => in(selected_run_ids), runs, view=true)
end;

# ╔═╡ 352700d7-8f94-4aa6-9aff-4de783ae1b4d
md"#### Group by"

# ╔═╡ 83e33b0e-68ac-4039-a41c-3273b0317657
@bind group_col Radio(
	names(
		selected_runs[!, [!any(isnothing, c) for c in eachcol(selected_runs)]]
		),
	default="run_id")

# ╔═╡ d4729079-765c-4c54-b8c1-252e7b3fa4a9
df = isempty(selected_run_ids) ? DataFrame() : run_data(selected_run_ids, runs);

# ╔═╡ 20995b98-9a5b-41a4-be86-72be1a35e698
function metric_stats(df::AbstractDataFrame, metric_col::Symbol, group_col::Symbol)::DataFrame
	result = []
	df = dropmissing(df, [metric_col, group_col], view=true)
	for (g_key, g) in pairs(groupby(df, group_col))
		group_data = @chain groupby(g, :step) begin
				combine(
					metric_col => mean => metric_col,
					metric_col => std => :std
				)
				_ .= ifelse.(isnan.(_), 0, _)  # Replace NAN with 0
				transform(
					[metric_col, :std] => ((x, y) -> x - y) => :lower,
					[metric_col, :std] => ((x, y) -> x + y) => :upper;
				)
				select(:step, metric_col, :lower, :upper)
		end
		insertcols!(group_data, group_col => first(g_key))
		push!(result, group_data)
	end
	vcat(result...)
end

# ╔═╡ 19186224-91a0-421b-bdca-0689567c701f
md"### Plots"

# ╔═╡ 7acd7dfb-7edb-4904-8877-ac66a498eb9c
begin
	struct HTMLDocument
		embedded
	end
	function Base.show(io::IO, mime::MIME"text/html", doc::HTMLDocument)
		println(io, "<html>")
		show(io, mime, doc.embedded)
		println(io, "</html>")
	end
end

# ╔═╡ fe6f09ca-dc39-4d77-aae1-757c87ccd3e7
begin
	action_colors(n) = cmap("L08"; N=n)
	plot(
		smooth_curves(gpt_df, :episode_return, :action_hidden_size, window_size),
		x=:step, y=:mean,
		ymin=:lower, ymax=:upper,
		color=:action_hidden_size,
		Guide.xlabel("Step"),
		Guide.ylabel("Episode Return"),
		Geom.line,
		Geom.ribbon,
		Scale.color_discrete(action_colors),
		Guide.colorkey(title="Action Hidden Size"),
		Guide.title("Performance Across Action Sizes"),
		alpha=[0.5]
	) |> HTMLDocument
end

# ╔═╡ 1f0c13a6-ae73-4aec-bee3-745610c23175
plot(
		smooth_curves(
			sweep_data(sweep_runs([26, 9])),
			:episode_return,
			:sweep_id,
			window_size
		),
		x=:step, y=:mean,
		ymin=:lower, ymax=:upper,
		color=:sweep_id,
		Guide.xlabel("Step"),
		Guide.ylabel("Episode Return"),
		Geom.line,
		Geom.ribbon,
		Scale.color_discrete(),
		Guide.colorkey(labels=["No", "Yes"], title="GPT?"),
		Guide.title("GPT vs. No GPT Performance"),
		alpha=[0.5]
	) |> HTMLDocument

# ╔═╡ 24091393-3afb-4a1c-9a9a-8ab2627285a3
function multiline_chart(df::AbstractDataFrame, y::Symbol, group_col::Symbol)
	if !isempty(df)
		plt = (
			data(metric_stats(df, y, group_col)) *
			mapping(
				:step,
				y;
				color=group_col => nonnumeric,
				lower=:lower,
				upper=:upper
			) *
			visual(LinesFill))
		set_title!(draw(plt), replace(string(y), "_" => " ") |> titlecase)
	end
end

# ╔═╡ 9c6b8bc6-94ad-4fdf-a9b6-6df962227ead
multiline_chart(df, :loss, Symbol(group_col))

# ╔═╡ a346a9f5-490a-477c-8979-160be8198073
multiline_chart(df, :episode_return, Symbol(group_col))

# ╔═╡ 5811c404-e244-4fae-a442-db5e4946039b
md"### Data"

# ╔═╡ 233b2be1-ec9b-4b3e-b0cb-fe90ddaf4a1e
df

# ╔═╡ Cell order:
# ╟─6e3ef066-d115-11eb-2338-013a707dfe8a
# ╟─41bd06a2-e7bd-46c6-9249-6e69223b0e11
# ╟─94185c13-b6d2-4337-b5ce-336f5e128032
# ╟─8f417ce0-fa72-4b12-8d3b-8f88b2e5a2bf
# ╟─48be0808-f22a-4b72-a078-b2f2552db327
# ╟─f4d4785e-0df1-4882-8eb9-005ff2a50614
# ╟─0ca92cdc-102c-45e7-a5b0-17087b9ba634
# ╟─68e80154-126b-403c-a593-d896cdf96ef2
# ╟─0f54629c-e045-47bf-90a5-36e44c05b8f0
# ╟─18147da2-1945-42e4-b140-c1375f46962b
# ╟─0135af1a-d8c8-4027-af38-7f57bbfef282
# ╟─3ba73b7c-f5dc-4639-ab9c-c43cc992634f
# ╟─8798b46c-1b0b-4d34-93ef-1d5062f8a632
# ╟─bbed8889-d401-4167-9370-9927aabbc83b
# ╟─5cba55d9-c7fe-4918-88b3-abbabe08c56b
# ╠═fe6f09ca-dc39-4d77-aae1-757c87ccd3e7
# ╟─70e759a8-2f8d-46c8-aa02-c581dd17c1c4
# ╟─1f0c13a6-ae73-4aec-bee3-745610c23175
# ╠═23d3bad8-099c-4794-806a-aaacc86b9e1a
# ╠═92de44db-86be-4fe5-9eb1-1ac657676b95
# ╟─c252df75-fb25-470d-956d-0aa532701565
# ╟─8b4a7da4-562e-4ad7-aa8b-8a458f302508
# ╟─163fc23c-952e-4002-be1c-0baafbccd8aa
# ╟─fe1f61d3-2b34-4a54-9fdc-9e4504248994
# ╟─26b7f618-1576-4299-b8d5-5bfef31401f1
# ╟─352700d7-8f94-4aa6-9aff-4de783ae1b4d
# ╟─83e33b0e-68ac-4039-a41c-3273b0317657
# ╟─d4729079-765c-4c54-b8c1-252e7b3fa4a9
# ╟─20995b98-9a5b-41a4-be86-72be1a35e698
# ╟─19186224-91a0-421b-bdca-0689567c701f
# ╟─7acd7dfb-7edb-4904-8877-ac66a498eb9c
# ╟─24091393-3afb-4a1c-9a9a-8ab2627285a3
# ╟─9c6b8bc6-94ad-4fdf-a9b6-6df962227ead
# ╟─a346a9f5-490a-477c-8979-160be8198073
# ╟─5811c404-e244-4fae-a442-db5e4946039b
# ╠═233b2be1-ec9b-4b3e-b0cb-fe90ddaf4a1e

max_stars_repo_name: GPT-RL/generalization

max_issues_repo_name: GPT-RL/generalization

max_forks_repo_name: GPT-RL/generalization


text:
using JLAssistant
using Test

@testset "JLAssistant.jl" begin
    # Write your tests here.
end


text:
"""
This deals with the data of a Semagram as passed back from typescript.

Basically, we recreate the data structures in typescript so that we get
automatic json conversion into a Julia-friendly format (SemagramData)
and then we provide a function to convert that into an honest-to-goodness
acset.
"""
module Data

export Box, Port, Wire, SemagramData, LocatedSemagramData, to_acset

using ..Muesli
import ..Muesli: from_json, to_json
using ..Schema
using Catlab.CSetDataStructures
using Catlab.Theories
using MLStyle

struct Port
  ty::Symbol
  weights::Dict{Symbol, String}
end

from_json(d::Dict{String,<:Any},::Type{Port}) = generic_from_json(d,Port)
to_json(p::Port) = generic_to_json(p)

struct Box
  ty::Symbol
  weights::Dict{Symbol, String}
  ports::Dict{Int,Port}
end

from_json(d::Dict{String,<:Any},::Type{Box}) = generic_from_json(d,Box)
to_json(b::Box) = generic_to_json(b)

@data Attachment begin
  AttachBox(box_idx::Int)
  AttachPort(box_idx::Int, port_idx::Int)
end

function from_json(d::Dict{String,<:Any},::Type{Attachment})
  if d["ty"] == "Box"
    AttachBox(d["box_idx"])
  else
    AttachPort(d["box_idx"],d["port_idx"])
  end
end

function to_json(a::Attachment)
  @match a begin
    AttachBox(box_idx) => Dict(:ty => "Box", :box_idx => box_idx)
    AttachPort(box_idx, port_idx) => Dict(:ty => "Port", :box_idx => box_idx, :port_idx => port_idx)
  end
end

struct Wire
  ty::Symbol
  weights::Dict{Symbol, String}
  src::Attachment
  tgt::Attachment
end

from_json(d::Dict{String,<:Any},::Type{Wire}) = generic_from_json(d,Wire)
to_json(w::Wire) = generic_to_json(w)

struct IDGen
  i::Int
end

from_json(d::Dict{String,<:Any},::Type{IDGen}) = generic_from_json(d,IDGen)
to_json(gen::IDGen) = generic_to_json(gen)

struct SemagramData
  boxes::Dict{Int, Box}
  wires::Dict{Int, Wire}
  gen::IDGen
  schema::SemagramSchema
  function SemagramData(schema::SemagramSchema)
    new(Dict{Int,Box}(), Dict{Int,Wire}(), IDGen(0), schema)
  end
  function SemagramData(boxes, wires, gen, schema)
    new(boxes, wires, gen, schema)
  end
end

from_json(d::Dict{String,<:Any},::Type{SemagramData}) = generic_from_json(d,SemagramData)
to_json(sd::SemagramData) = generic_to_json(sd)

struct LocatedSemagramData
  sg::SemagramData
  boxlocs::Dict{Int, Tuple{Float64, Float64}}
  function LocatedSemagramData(schema::SemagramSchema)
    new(SemagramData(schema), Dict{Int, Tuple{Float64, Float64}}())
  end
  function LocatedSemagramData(sg, boxlocs)
    new(sg, boxlocs)
  end
end

from_json(d::Dict{String,<:Any},::Type{LocatedSemagramData}) = generic_from_json(d,LocatedSemagramData)
to_json(ls::LocatedSemagramData) = generic_to_json(ls)

function lookup_attachment(box_map::Dict{Int,Int},
                           port_map::Dict{Tuple{Int,Int},Int},
                           a::Attachment)
  @match a begin
    AttachBox(box_idx) => box_map[box_idx]
    AttachPort(box_idx,port_idx) => port_map[(box_idx,port_idx)]
  end
end

function attribute_type(::Type{T}, attr::Symbol) where {CD, AD, Ts, T <: AbstractACSet{CD, AD, Ts}}
  Ts.parameters[Theories.codom_num(AD, attr)]
end

function attributes_from_strings(weights::Dict{Symbol, String}, ::Type{T}) where {T <: AbstractACSet}
  types = Dict([attr => attribute_type(T, attr) for attr in keys(weights)]...)
  NamedTuple{(keys(types)...,),Tuple{values(types)...}}(
    [from_json(weights[attr],types[attr]) for attr in keys(weights)]
  )
end

function to_acset(ls::LocatedSemagramData, ::Type{T}) where {T <: AbstractACSet}
  sd = ls.sg
  schema = sd.schema
  acs = T()
  box_map = Dict{Int,Int}()
  port_map = Dict{Tuple{Int,Int},Int}()
  for (i,box) in sd.boxes
    acs_i = add_part!(acs, box.ty; attributes_from_strings(box.weights, T)...)
    box_map[i] = acs_i
    for (j,port) in box.ports
      port_props = schema.port_types[port.ty]
      acs_j = add_part!(acs,port.ty;Dict(port_props.box_map => acs_i)...,
                        attributes_from_strings(port.weights, T)...)
      port_map[(i,j)] = acs_j
    end
  end
  for (i,wire) in sd.wires
    acs_src = lookup_attachment(box_map, port_map, wire.src)
    acs_tgt = lookup_attachment(box_map, port_map, wire.tgt)
    wire_props = schema.wire_types[wire.ty]
    attrs = Dict(wire_props.src_map => acs_src, wire_props.tgt_map => acs_tgt)
    add_part!(acs,wire.ty; attrs..., attributes_from_strings(wire.weights, T)...)
  end
  acs
end

end


text:
################################################################################
#                                ____ ____ ____                                #
#                                |__| | __ |                                   #
#                                |  | |__] |___                                #
################################################################################

type AGC
    gain
    bandwidth
    alpha
    y2_prime
    initialized
end

function AGC( gain = 1.0, bandwidth = 0.01, alpha = bandwidth  )
    AGC( gain, bandwidth, alpha, 1.0, false )
end

function exec( agc::AGC, x::Number )
    y            = x * agc.gain
    y2           = abs2( y )
    agc.y2_prime = (1 - agc.alpha) * agc.y2_prime + agc.alpha*y2
    agc.gain *= exp( -0.5 * agc.alpha * log(agc.y2_prime))

    return y
end

function exec{T}( agc::AGC, x::Vector{T} )
    if ! agc.initialized
        for i in 1:min(1000, length(x))
           exec( agc, x[i])
        end
    end
    T[ exec( agc, xx) for xx in x ]
end

#=
include( "Modem/QAM.jl" )

agc        = AGC(1e-1)
M          = 16
modem      = QAMModem( M )
data       = rand( 0:M-1, 1000 )
symbols    = modulate( modem, data )
agcSymbols = exec( agc, symbols )
demodData  = demodulate( modem, agcSymbols )

Test.@test_approx_eq data demodData

using PyPlot
clf()
subplot( 2, 1, 1 )
plot( real(symbols), "b" )
plot( imag(symbols), "g" )

subplot( 2, 1, 2 )
plot( real(agcSymbols), "b" )
plot( imag(agcSymbols), "g" )
=#


text:
export Message

"""
A [`Message`](@ref)'s type.
More details [here](https://discordapp.com/developers/docs/resources/channel#message-object-message-types).
"""
@enum MessageType begin
    MT_DEFAULT
    MT_RECIPIENT_ADD
    MT_RECIPIENT_REMOVE
    MT_CALL
    MT_CHANNEL_NAME_CHANGE
    MT_CHANNEL_ICON_CHANGE
    MT_CHANNEL_PINNED_MESSAGE
    MT_GUILD_MEMBER_JOIN
end
@boilerplate MessageType :lower

"""
A [`Message`](@ref)'s activity type.
More details [here](https://discordapp.com/developers/docs/resources/channel#message-object-message-activity-types).
"""
@enum MessageActivityType MAT_JOIN MAT_SPECTATE MAT_LISTEN MAT_JOIN_REQUEST
@boilerplate MessageActivityType :lower

"""
A [`Message`](@ref) activity.
More details [here](https://discordapp.com/developers/docs/resources/channel#message-object-message-activity-structure).
"""
struct MessageActivity
    type::MessageActivityType
    party_id::Union{String, Missing}
end
@boilerplate MessageActivity :dict :docs :lower :merge

"""
A Rich Presence [`Message`](@ref)'s application information.
More details [here](https://discordapp.com/developers/docs/resources/channel#message-object-message-application-structure).
"""
struct MessageApplication
    id::Snowflake
    cover_image::String
    description::String
    icon::String
    name::String
end
@boilerplate MessageApplication :dict :docs :lower :merge

"""
A message sent to a [`DiscordChannel`](@ref).
More details [here](https://discordapp.com/developers/docs/resources/channel#message-object).
"""
struct Message
    id::Snowflake
    channel_id::Snowflake
    # MessageUpdate only requires the ID and channel ID.
    guild_id::Union{Snowflake, Missing}
    author::Union{User, Missing}
    member::Union{Member, Missing}
    content::Union{String, Missing}
    timestamp::Union{DateTime, Missing}
    edited_timestamp::Union{DateTime, Nothing, Missing}
    tts::Union{Bool, Missing}
    mention_everyone::Union{Bool, Missing}
    mentions::Union{Vector{User}, Missing}
    mention_roles::Union{Vector{Snowflake}, Missing}
    attachments::Union{Vector{Attachment}, Missing}
    embeds::Union{Vector{Embed}, Missing}
    reactions::Union{Vector{Reaction}, Missing}
    nonce::Union{Snowflake, Nothing, Missing}
    pinned::Union{Bool, Missing}
    webhook_id::Union{Snowflake, Missing}
    type::Union{MessageType, Missing}
    activity::Union{MessageActivity, Missing}
    application::Union{MessageApplication, Missing}
end
@boilerplate Message :dict :docs :lower :merge