text:
__precompile__()
"""
This is the main module and provides interfaces for specifying and solving reachability problems.
"""
module Reachability

using Reexport, RecipesBase, Memento, MathematicalSystems
@reexport using LazySets

include("logging.jl")
include("Utils/Utils.jl")
include("ReachSets/ReachSets.jl")
include("Properties/Properties.jl")
include("Transformations/Transformations.jl")

@reexport using Reachability.Utils

using Reachability.ReachSets,
      Reachability.Properties,
      Reachability.Transformations

export Properties, LinearConstraintProperty, Clause,
       IntersectionProperty,
       SubsetProperty,
       Transformations

include("options.jl")
include("solve.jl")
include("plot_recipes.jl")

end # module


text:
# This file is used to generate the "src/core.jl" file from the schema files in the BIDS
# specification. This should be run periodically to ensure that all entities are present and
# the rules for composing file names for each data type are BIDS compliant.
using YAML
using DataStructures

struct EntitySchema
    name::String
    entity::String
    description::String
end

struct ModalitySchema
    suffixes::Vector{String}
    extensions::Vector{String}
    entities::OrderedDict{Any,Any}
end

function generate_schemas(m::Vector{String})
    modalities = Dict{String,Vector{ModalitySchema}}()
    for m_i in m
        p = download("https://raw.githubusercontent.com/bids-standard/bids-specification/master/src/schema/datatypes/$(m_i).yaml")
        modalities[m_i] = [ModalitySchema(s["suffixes"], s["extensions"], s["entities"]) for s in YAML.load_file(p; dicttype=OrderedDict{Any,Any})]
    end
    entities = Dict{String,EntitySchema}()
    for (k,v) in YAML.load_file(download("https://raw.githubusercontent.com/bids-standard/bids-specification/master/src/schema/entities.yaml"); dicttype=OrderedDict{Any,Any})
        entities[k] = EntitySchema(k, v["entity"], v["description"])
    end
    return modalities, entities
end

function generate_entity_file(e)
    io = open("neuro_entities.jl", "w")
    write(io, "\n")

    # Create enum for each entity
    write(io, "@enum Entity::UInt8 begin\n")
    for (k,v) in e
        write(io, "    $(k)\n")
    end
    write(io, "end\n\n")

    # Entity -> String
    write(io, "function Base.String(x::Entity)\n")
    for (i, (k, v)) in enumerate(e)
        if i === 1
            write(io, "    if ")
        else
            write(io, "    elseif ")
        end
        write(io, "x === $(k)\n")
        write(io, "        return \"$(v.entity)\"\n")
    end
    write(io, "    end\n")
    write(io, "end\n\n")

    # String -> Entity
    write(io, "function Entity(x::AbstractString)\n")
    for (i, (k, v)) in enumerate(e)
        if i === 1
            write(io, "    if ")
        else
            write(io, "    elseif ")
        end
        write(io, "x == \"$(v.entity)\"\n")
        write(io, "        return $(k)\n")
    end
    write(io, "    else\n")
    write(io, "        error(x * \" cannot be converted to an Entity type.\")")
    write(io, "    end\n")
    write(io, "end\n\n")

    # Symbol -> Entity
    write(io, "function Entity(x::Symbol)\n")
    for (i, (k, v)) in enumerate(e)
        if i === 1
            write(io, "    if ")
        else
            write(io, "    elseif ")
        end
        write(io, "x == :$(k)\n")
        write(io, "        return $(k)\n")
    end
    write(io, "    else\n")
    write(io, "        error(\"\$(x) cannot be converted to an Entity type.\")\n")
    write(io, "    end\n")
    write(io, "end\n\n")
    close(io)
end

function generate_data_type_files(modalities, e)
    io = open("data_type_entities.jl", "w")
    # modalities
    for (m, v) in modalities
        write(io, "function _$(m)_entities(suffix, src::Entities)\n")
        for i in axes(v, 1)
            ms = v[i]
            if i === 1
                write(io, "    if ")
            else
                write(io, "    elseif ")
            end
            suffixes = ms.suffixes
            for j in axes(suffixes, 1)
                if j !== 1
                    write(io, " || ")
                end
                write(io, "suffix == \"$(suffixes[j])\"")
            end
            write(io, "\n")
            str = "()"
            for (k,v) in ms.entities
                if v == "required"
                    str = "_get_req($(str), src, $(k))"
                else
                    str = "_get_opt($(str), src, $(k))"
                end
            end
            write(io, "        return Entities($(str))\n")
        end
        write(io, "    else\n")
        write(io, "        error(suffix * \" is not a supported suffix.\")\n")
        write(io, "    end\n")
        write(io, "end\n\n")
    end
    close(io)
end

m, e = generate_schemas(["anat", "beh", "dwi", "eeg", "fmap", "func", "ieeg", "meg", "perf", "pet"]);

generate_entity_file(e)
generate_data_type_files(m, e)

ext: jl


text:
module Retriever

using PyCall

export commit, commit_log
export get_dataset_names_upstream
export get_script_citation
export get_script_upstream
export check_for_updates, dataset_names, download
export install_csv, install_mysql, install_postgres
export install_sqlite, install_msaccess, install_json
export install_xml, reset_retriever
export reload_scripts
export data_retriever_version

# Create retriever as rt while properly handling precompilation
# See: https://github.com/JuliaPy/PyCall.jl#using-pycall-from-julia-modules
const rt = PyNULL()
function __init__()
    copy!(rt, pyimport_conda("retriever", "retriever", "conda-forge"))
end

"""
```julia
    commit(dataset, commit_message::String="", path::String="", quiet::Bool=false)
```

Commit Retriever dataset.
"""
function commit(dataset, commit_message::String="", path::String="", quiet::Bool=false)
    rt.commit(dataset, commit_message, path, quiet)
    println("Successfully committed.")
end

"""
```julia
    commit_log(dataset)
```

Get the commit log for a dataset.
"""
function commit_log(dataset)
    rt.commit_log(dataset)
end

"""
```julia
    check_for_updates()
```

Check Retriever scripts for updates.
"""
function check_for_updates()
    rt.check_for_updates()
end

"""
```julia
    get_script_citation(repo::String="")
```

Get citation for the data retriever or scripts.
"""
function get_script_citation(dataset::String="")
    rt.get_script_citation(dataset)
end

"""
```julia
    reload_scripts()
```

Reload scripts Retriever scripts.
"""
function reload_scripts()
    rt.reload_scripts()
end

"""
```julia
    data_retriever_version()
```

Get Data Retriever version.
"""
function data_retriever_version()
    rt.__version__
end

"""
```julia
    get_dataset_names_upstream(keywords::Array{String,1}=String[], licenses::Array{String,1}=String[], repo::String="")
```

Get dataset names upstream scripts.
"""
function get_dataset_names_upstream(keywords::Array{String,1}=String[], licenses::Array{String,1}=String[], repo::String="")
    rt.get_dataset_names_upstream(keywords, licenses, repo)
end

"""
```julia
    get_script_upstream(dataset, repo::String="")
```

Get upstream retriever-recipe's scripts.
"""
function get_script_upstream(dataset, repo::String="")
    rt.get_script_upstream(dataset, repo)
end

"""
```julia
    reload_scripts()
```

Retriever reload scripts.
"""
function reload_scripts()
    rt.reload_scripts()
end

"""
```julia
    reset_retriever(scope::String="all", ask_permission::Bool=true)
```

Retriever reset scripts or data or all.
"""
function reset_retriever(scope::String="all", ask_permission::Bool=true)
    rt.reset_retriever(scope, ask_permission)
end

"""
```julia
    dataset_names()
```

Return list of all available dataset names.
"""
function dataset_names()
    rt.dataset_names()
end

"""
```julia
    download(dataset; path::String="./", quiet::Bool=false,
                subdir::String="", debug::Bool=false, use_cache::Bool=false)
```

Download scripts for retriever.
"""
function download(dataset; path::String="./", quiet::Bool=false,
                subdir::String="", debug::Bool=false, use_cache::Bool=false)
    rt.download(dataset, path, quiet, subdir, debug, use_cache)
end

"""
```julia

    install_csv(dataset; table_name::String="", compile::Bool=false,
        data_dir=pwd(), debug::Bool=false, use_cache::Bool=true)
```

Install Retriever scripts in csv format.
"""
function install_csv(dataset; table_name::String="{db}_{table}",
        data_dir=pwd(), debug::Bool=false, use_cache::Bool=true)
    rt.install_csv(dataset, table_name, data_dir, debug, use_cache)
end

"""
```julia
    install_mysql(dataset; user::String="root",
                password::String="", host::String="localhost",
                port::Int=3306, database_name::String="", table_name::String="",
                compile::Bool=false, debug::Bool=false, quiet::Bool=false,
                use_cache::Bool=true)
```

Install Retriever scripts in mysql database.
"""
function install_mysql(dataset; user::String="root",
                password::String="", host::String="localhost",
                port::Int=3306, database_name::String="{db}", table_name::String="{db}.{table}",
                debug::Bool=false, use_cache::Bool=true)
    rt.install_mysql(dataset, user, password, host, port, database_name,
                     table_name, debug, use_cache)
end

"""
```julia
    install_postgres(dataset; user::String="postgres",
                password::String="", host::String="localhost",
                port::Int=5432, database::String="postgres",
                database_name::String="", table_name::String="", bbox::Any=[],
                debug::Bool=false, use_cache::Bool=true)
```

Install Retriever scripts in database.
"""
function install_postgres(dataset; user::String="postgres",
                password::String="", host::String="localhost",
                port::Int=5432, database::String="postgres",
                database_name::String="{db}", table_name::String="{db}.{table}", bbox::Any=[],
                debug::Bool=false, use_cache::Bool=true)

    rt.install_postgres(dataset, user, password, host, port, database,
                        database_name, table_name, bbox, debug, use_cache)
end

"""
```julia
    install_sqlite(dataset; file::String="", table_name::String="",
                data_dir=pwd(), debug::Bool=false,
                use_cache::Bool=true)
```

Install Retriever scripts in database.
"""
function install_sqlite(dataset; file::String="", table_name::String="{db}.{table}",
                data_dir=pwd(), debug::Bool=false, use_cache::Bool=true)
    return rt.install_sqlite(dataset, file, table_name, data_dir, debug, use_cache)
end

"""
```julia
    install_msaccess(dataset; file::String="", table_name::String="",
                data_dir=pwd(), debug::Bool=false, use_cache::Bool=true)
```

Install Retriever scripts in msacces.
"""
function install_msaccess(dataset; file::String="", table_name::String="",
                data_dir=pwd(), debug::Bool=false, use_cache::Bool=true)
    rt.install_msaccess(dataset, file, table_name, data_dir, debug, quiet,
                        use_cache)
end

"""
```julia
    install_json(dataset; table_name::String="", data_dir=pwd(),
    debug::Bool=false, use_cache::Bool=true)
```

Install Retriever scripts in json format.
"""
function install_json(dataset; table_name::String="{db}_{table}.json",
                data_dir=pwd(), debug::Bool=false, use_cache::Bool=true)
    rt.install_json(dataset, table_name, data_dir, debug, use_cache)

end

"""
```julia
    install_xml(dataset; table_name::String="", compile::Bool=false, data_dir=pwd(),
            debug::Bool=false, use_cache::Bool=true)
```

Install Retriever scripts in xml format.
"""
function install_xml(dataset; table_name::String="{db}_{table}.xml",
                data_dir=pwd(), debug::Bool=false, use_cache::Bool=true)
    rt.install_xml(dataset, table_name, data_dir, debug, use_cache)

end

end # module


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

"""
    associate_custom_domain(domain_name, service_arn)
    associate_custom_domain(domain_name, service_arn, params::Dict{String,<:Any})

Associate your own domain name with the AWS App Runner subdomain URL of your App Runner
service. After you call AssociateCustomDomain and receive a successful response, use the
information in the CustomDomain record that's returned to add CNAME records to your Domain
Name System (DNS). For each mapped domain name, add a mapping to the target App Runner
subdomain and one or more certificate validation records. App Runner then performs DNS
validation to verify that you own or control the domain name that you associated. App
Runner tracks domain validity in a certificate stored in AWS Certificate Manager (ACM).

# Arguments
- `domain_name`: A custom domain endpoint to associate. Specify a root domain (for example,
  example.com), a subdomain (for example, login.example.com or admin.login.example.com), or a
  wildcard (for example, *.example.com).
- `service_arn`: The Amazon Resource Name (ARN) of the App Runner service that you want to
  associate a custom domain name with.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"EnableWWWSubdomain"`: Set to true to associate the subdomain www.DomainName  with the
  App Runner service in addition to the base domain. Default: true
"""
associate_custom_domain(DomainName, ServiceArn; aws_config::AbstractAWSConfig=global_aws_config()) = apprunner("AssociateCustomDomain", Dict{String, Any}("DomainName"=>DomainName, "ServiceArn"=>ServiceArn); aws_config=aws_config)
associate_custom_domain(DomainName, ServiceArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = apprunner("AssociateCustomDomain", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("DomainName"=>DomainName, "ServiceArn"=>ServiceArn), params)); aws_config=aws_config)

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

Create an AWS App Runner automatic scaling configuration resource. App Runner requires this
resource when you create App Runner services that require non-default auto scaling
settings. You can share an auto scaling configuration across multiple services. Create
multiple revisions of a configuration by using the same AutoScalingConfigurationName and
different AutoScalingConfigurationRevision values. When you create a service, you can set
it to use the latest active revision of an auto scaling configuration or a specific
revision. Configure a higher MinSize to increase the spread of your App Runner service over
more Availability Zones in the AWS Region. The tradeoff is a higher minimal cost. Configure
a lower MaxSize to control your cost. The tradeoff is lower responsiveness during peak
demand.

# Arguments
- `auto_scaling_configuration_name`: A name for the auto scaling configuration. When you
  use it for the first time in an AWS Region, App Runner creates revision number 1 of this
  name. When you use the same name in subsequent calls, App Runner creates incremental
  revisions of the configuration.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"MaxConcurrency"`: The maximum number of concurrent requests that you want an instance
  to process. If the number of concurrent requests exceeds this limit, App Runner scales up
  your service. Default: 100
- `"MaxSize"`: The maximum number of instances that your service scales up to. At most
  MaxSize instances actively serve traffic for your service. Default: 25
- `"MinSize"`: The minimum number of instances that App Runner provisions for your service.
  The service always has at least MinSize provisioned instances. Some of them actively serve
  traffic. The rest of them (provisioned and inactive instances) are a cost-effective compute
  capacity reserve and are ready to be quickly activated. You pay for memory usage of all the
  provisioned instances. You pay for CPU usage of only the active subset. App Runner
  temporarily doubles the number of provisioned instances during deployments, to maintain the
  same capacity for both old and new code. Default: 1
- `"Tags"`: A list of metadata items that you can associate with your auto scaling
  configuration resource. A tag is a key-value pair.
"""
create_auto_scaling_configuration(AutoScalingConfigurationName; aws_config::AbstractAWSConfig=global_aws_config()) = apprunner("CreateAutoScalingConfiguration", Dict{String, Any}("AutoScalingConfigurationName"=>AutoScalingConfigurationName); aws_config=aws_config)
create_auto_scaling_configuration(AutoScalingConfigurationName, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = apprunner("CreateAutoScalingConfiguration", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("AutoScalingConfigurationName"=>AutoScalingConfigurationName), params)); aws_config=aws_config)

"""
    create_connection(connection_name, provider_type)
    create_connection(connection_name, provider_type, params::Dict{String,<:Any})

Create an AWS App Runner connection resource. App Runner requires a connection resource
when you create App Runner services that access private repositories from certain
third-party providers. You can share a connection across multiple services. A connection
resource is needed to access GitHub repositories. GitHub requires a user interface approval
process through the App Runner console before you can use the connection.

# Arguments
- `connection_name`: A name for the new connection. It must be unique across all App Runner
  connections for the AWS account in the AWS Region.
- `provider_type`: The source repository provider.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Tags"`: A list of metadata items that you can associate with your connection resource.
  A tag is a key-value pair.
"""
create_connection(ConnectionName, ProviderType; aws_config::AbstractAWSConfig=global_aws_config()) = apprunner("CreateConnection", Dict{String, Any}("ConnectionName"=>ConnectionName, "ProviderType"=>ProviderType); aws_config=aws_config)
create_connection(ConnectionName, ProviderType, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = apprunner("CreateConnection", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ConnectionName"=>ConnectionName, "ProviderType"=>ProviderType), params)); aws_config=aws_config)

"""
    create_service(service_name, source_configuration)
    create_service(service_name, source_configuration, params::Dict{String,<:Any})

Create an AWS App Runner service. After the service is created, the action also
automatically starts a deployment. This is an asynchronous operation. On a successful call,
you can use the returned OperationId and the ListOperations call to track the operation's
progress.

# Arguments
- `service_name`: A name for the new service. It must be unique across all the running App
  Runner services in your AWS account in the AWS Region.
- `source_configuration`: The source to deploy to the App Runner service. It can be a code
  or an image repository.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"AutoScalingConfigurationArn"`: The Amazon Resource Name (ARN) of an App Runner
  automatic scaling configuration resource that you want to associate with your service. If
  not provided, App Runner associates the latest revision of a default auto scaling
  configuration.
- `"EncryptionConfiguration"`: An optional custom encryption key that App Runner uses to
  encrypt the copy of your source repository that it maintains and your service logs. By
  default, App Runner uses an AWS managed CMK.
- `"HealthCheckConfiguration"`: The settings for the health check that AWS App Runner
  performs to monitor the health of your service.
- `"InstanceConfiguration"`: The runtime configuration of instances (scaling units) of the
  App Runner service.
- `"Tags"`: An optional list of metadata items that you can associate with your service
  resource. A tag is a key-value pair.
"""
create_service(ServiceName, SourceConfiguration; aws_config::AbstractAWSConfig=global_aws_config()) = apprunner("CreateService", Dict{String, Any}("ServiceName"=>ServiceName, "SourceConfiguration"=>SourceConfiguration); aws_config=aws_config)
create_service(ServiceName, SourceConfiguration, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = apprunner("CreateService", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ServiceName"=>ServiceName, "SourceConfiguration"=>SourceConfiguration), params)); aws_config=aws_config)

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

Delete an AWS App Runner automatic scaling configuration resource. You can delete a
specific revision or the latest active revision. You can't delete a configuration that's
used by one or more App Runner services.

# Arguments
- `auto_scaling_configuration_arn`: The Amazon Resource Name (ARN) of the App Runner auto
  scaling configuration that you want to delete. The ARN can be a full auto scaling
  configuration ARN, or a partial ARN ending with either .../name  or .../name/revision . If
  a revision isn't specified, the latest active revision is deleted.

"""
delete_auto_scaling_configuration(AutoScalingConfigurationArn; aws_config::AbstractAWSConfig=global_aws_config()) = apprunner("DeleteAutoScalingConfiguration", Dict{String, Any}("AutoScalingConfigurationArn"=>AutoScalingConfigurationArn); aws_config=aws_config)
delete_auto_scaling_configuration(AutoScalingConfigurationArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = apprunner("DeleteAutoScalingConfiguration", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("AutoScalingConfigurationArn"=>AutoScalingConfigurationArn), params)); aws_config=aws_config)

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

Delete an AWS App Runner connection. You must first ensure that there are no running App
Runner services that use this connection. If there are any, the DeleteConnection action
fails.

# Arguments
- `connection_arn`: The Amazon Resource Name (ARN) of the App Runner connection that you
  want to delete.

"""
delete_connection(ConnectionArn; aws_config::AbstractAWSConfig=global_aws_config()) = apprunner("DeleteConnection", Dict{String, Any}("ConnectionArn"=>ConnectionArn); aws_config=aws_config)
delete_connection(ConnectionArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = apprunner("DeleteConnection", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ConnectionArn"=>ConnectionArn), params)); aws_config=aws_config)

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

Delete an AWS App Runner service. This is an asynchronous operation. On a successful call,
you can use the returned OperationId and the ListOperations call to track the operation's
progress.

# Arguments
- `service_arn`: The Amazon Resource Name (ARN) of the App Runner service that you want to
  delete.

"""
delete_service(ServiceArn; aws_config::AbstractAWSConfig=global_aws_config()) = apprunner("DeleteService", Dict{String, Any}("ServiceArn"=>ServiceArn); aws_config=aws_config)
delete_service(ServiceArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = apprunner("DeleteService", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ServiceArn"=>ServiceArn), params)); aws_config=aws_config)

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

Return a full description of an AWS App Runner automatic scaling configuration resource.

# Arguments
- `auto_scaling_configuration_arn`: The Amazon Resource Name (ARN) of the App Runner auto
  scaling configuration that you want a description for. The ARN can be a full auto scaling
  configuration ARN, or a partial ARN ending with either .../name  or .../name/revision . If
  a revision isn't specified, the latest active revision is described.

"""
describe_auto_scaling_configuration(AutoScalingConfigurationArn; aws_config::AbstractAWSConfig=global_aws_config()) = apprunner("DescribeAutoScalingConfiguration", Dict{String, Any}("AutoScalingConfigurationArn"=>AutoScalingConfigurationArn); aws_config=aws_config)
describe_auto_scaling_configuration(AutoScalingConfigurationArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = apprunner("DescribeAutoScalingConfiguration", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("AutoScalingConfigurationArn"=>AutoScalingConfigurationArn), params)); aws_config=aws_config)

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

Return a description of custom domain names that are associated with an AWS App Runner
service.

# Arguments
- `service_arn`: The Amazon Resource Name (ARN) of the App Runner service that you want
  associated custom domain names to be described for.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"MaxResults"`: The maximum number of results that each response (result page) can
  include. It's used for a paginated request. If you don't specify MaxResults, the request
  retrieves all available results in a single response.
- `"NextToken"`: A token from a previous result page. It's used for a paginated request.
  The request retrieves the next result page. All other parameter values must be identical to
  the ones that are specified in the initial request. If you don't specify NextToken, the
  request retrieves the first result page.
"""
describe_custom_domains(ServiceArn; aws_config::AbstractAWSConfig=global_aws_config()) = apprunner("DescribeCustomDomains", Dict{String, Any}("ServiceArn"=>ServiceArn); aws_config=aws_config)
describe_custom_domains(ServiceArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = apprunner("DescribeCustomDomains", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ServiceArn"=>ServiceArn), params)); aws_config=aws_config)

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

Return a full description of an AWS App Runner service.

# Arguments
- `service_arn`: The Amazon Resource Name (ARN) of the App Runner service that you want a
  description for.

"""
describe_service(ServiceArn; aws_config::AbstractAWSConfig=global_aws_config()) = apprunner("DescribeService", Dict{String, Any}("ServiceArn"=>ServiceArn); aws_config=aws_config)
describe_service(ServiceArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = apprunner("DescribeService", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ServiceArn"=>ServiceArn), params)); aws_config=aws_config)

"""
    disassociate_custom_domain(domain_name, service_arn)
    disassociate_custom_domain(domain_name, service_arn, params::Dict{String,<:Any})

Disassociate a custom domain name from an AWS App Runner service. Certificates tracking
domain validity are associated with a custom domain and are stored in AWS Certificate
Manager (ACM). These certificates aren't deleted as part of this action. App Runner delays
certificate deletion for 30 days after a domain is disassociated from your service.

# Arguments
- `domain_name`: The domain name that you want to disassociate from the App Runner service.
- `service_arn`: The Amazon Resource Name (ARN) of the App Runner service that you want to
  disassociate a custom domain name from.

"""
disassociate_custom_domain(DomainName, ServiceArn; aws_config::AbstractAWSConfig=global_aws_config()) = apprunner("DisassociateCustomDomain", Dict{String, Any}("DomainName"=>DomainName, "ServiceArn"=>ServiceArn); aws_config=aws_config)
disassociate_custom_domain(DomainName, ServiceArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = apprunner("DisassociateCustomDomain", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("DomainName"=>DomainName, "ServiceArn"=>ServiceArn), params)); aws_config=aws_config)

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

Returns a list of AWS App Runner automatic scaling configurations in your AWS account. You
can query the revisions for a specific configuration name or the revisions for all
configurations in your account. You can optionally query only the latest revision of each
requested name.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"AutoScalingConfigurationName"`: The name of the App Runner auto scaling configuration
  that you want to list. If specified, App Runner lists revisions that share this name. If
  not specified, App Runner returns revisions of all configurations.
- `"LatestOnly"`: Set to true to list only the latest revision for each requested
  configuration name. Keep as false to list all revisions for each requested configuration
  name. Default: false
- `"MaxResults"`: The maximum number of results to include in each response (result page).
  It's used for a paginated request. If you don't specify MaxResults, the request retrieves
  all available results in a single response.
- `"NextToken"`: A token from a previous result page. It's used for a paginated request.
  The request retrieves the next result page. All other parameter values must be identical to
  the ones that are specified in the initial request. If you don't specify NextToken, the
  request retrieves the first result page.
"""
list_auto_scaling_configurations(; aws_config::AbstractAWSConfig=global_aws_config()) = apprunner("ListAutoScalingConfigurations"; aws_config=aws_config)
list_auto_scaling_configurations(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = apprunner("ListAutoScalingConfigurations", params; aws_config=aws_config)

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

Returns a list of AWS App Runner connections that are associated with your AWS account.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"ConnectionName"`: If specified, only this connection is returned. If not specified, the
  result isn't filtered by name.
- `"MaxResults"`: The maximum number of results to include in each response (result page).
  Used for a paginated request. If you don't specify MaxResults, the request retrieves all
  available results in a single response.
- `"NextToken"`: A token from a previous result page. Used for a paginated request. The
  request retrieves the next result page. All other parameter values must be identical to the
  ones specified in the initial request. If you don't specify NextToken, the request
  retrieves the first result page.
"""
list_connections(; aws_config::AbstractAWSConfig=global_aws_config()) = apprunner("ListConnections"; aws_config=aws_config)
list_connections(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = apprunner("ListConnections", params; aws_config=aws_config)

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

Return a list of operations that occurred on an AWS App Runner service. The resulting list
of OperationSummary objects is sorted in reverse chronological order. The first object on
the list represents the last started operation.

# Arguments
- `service_arn`: The Amazon Resource Name (ARN) of the App Runner service that you want a
  list of operations for.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"MaxResults"`: The maximum number of results to include in each response (result page).
  It's used for a paginated request. If you don't specify MaxResults, the request retrieves
  all available results in a single response.
- `"NextToken"`: A token from a previous result page. It's used for a paginated request.
  The request retrieves the next result page. All other parameter values must be identical to
  the ones specified in the initial request. If you don't specify NextToken, the request
  retrieves the first result page.
"""
list_operations(ServiceArn; aws_config::AbstractAWSConfig=global_aws_config()) = apprunner("ListOperations", Dict{String, Any}("ServiceArn"=>ServiceArn); aws_config=aws_config)
list_operations(ServiceArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = apprunner("ListOperations", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ServiceArn"=>ServiceArn), params)); aws_config=aws_config)

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

Returns a list of running AWS App Runner services in your AWS account.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"MaxResults"`: The maximum number of results to include in each response (result page).
  It's used for a paginated request. If you don't specify MaxResults, the request retrieves
  all available results in a single response.
- `"NextToken"`: A token from a previous result page. Used for a paginated request. The
  request retrieves the next result page. All other parameter values must be identical to the
  ones specified in the initial request. If you don't specify NextToken, the request
  retrieves the first result page.
"""
list_services(; aws_config::AbstractAWSConfig=global_aws_config()) = apprunner("ListServices"; aws_config=aws_config)
list_services(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = apprunner("ListServices", params; aws_config=aws_config)

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

List tags that are associated with for an AWS App Runner resource. The response contains a
list of tag key-value pairs.

# Arguments
- `resource_arn`: The Amazon Resource Name (ARN) of the resource that a tag list is
  requested for. It must be the ARN of an App Runner resource.

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

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

Pause an active AWS App Runner service. App Runner reduces compute capacity for the service
to zero and loses state (for example, ephemeral storage is removed). This is an
asynchronous operation. On a successful call, you can use the returned OperationId and the
ListOperations call to track the operation's progress.

# Arguments
- `service_arn`: The Amazon Resource Name (ARN) of the App Runner service that you want to
  pause.

"""
pause_service(ServiceArn; aws_config::AbstractAWSConfig=global_aws_config()) = apprunner("PauseService", Dict{String, Any}("ServiceArn"=>ServiceArn); aws_config=aws_config)
pause_service(ServiceArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = apprunner("PauseService", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ServiceArn"=>ServiceArn), params)); aws_config=aws_config)

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

Resume an active AWS App Runner service. App Runner provisions compute capacity for the
service. This is an asynchronous operation. On a successful call, you can use the returned
OperationId and the ListOperations call to track the operation's progress.

# Arguments
- `service_arn`: The Amazon Resource Name (ARN) of the App Runner service that you want to
  resume.

"""
resume_service(ServiceArn; aws_config::AbstractAWSConfig=global_aws_config()) = apprunner("ResumeService", Dict{String, Any}("ServiceArn"=>ServiceArn); aws_config=aws_config)
resume_service(ServiceArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = apprunner("ResumeService", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ServiceArn"=>ServiceArn), params)); aws_config=aws_config)

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

Initiate a manual deployment of the latest commit in a source code repository or the latest
image in a source image repository to an AWS App Runner service. For a source code
repository, App Runner retrieves the commit and builds a Docker image. For a source image
repository, App Runner retrieves the latest Docker image. In both cases, App Runner then
deploys the new image to your service and starts a new container instance. This is an
asynchronous operation. On a successful call, you can use the returned OperationId and the
ListOperations call to track the operation's progress.

# Arguments
- `service_arn`: The Amazon Resource Name (ARN) of the App Runner service that you want to
  manually deploy to.

"""
start_deployment(ServiceArn; aws_config::AbstractAWSConfig=global_aws_config()) = apprunner("StartDeployment", Dict{String, Any}("ServiceArn"=>ServiceArn); aws_config=aws_config)
start_deployment(ServiceArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = apprunner("StartDeployment", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ServiceArn"=>ServiceArn), params)); aws_config=aws_config)

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

Add tags to, or update the tag values of, an App Runner resource. A tag is a key-value pair.

# Arguments
- `resource_arn`: The Amazon Resource Name (ARN) of the resource that you want to update
  tags for. It must be the ARN of an App Runner resource.
- `tags`: A list of tag key-value pairs to add or update. If a key is new to the resource,
  the tag is added with the provided value. If a key is already associated with the resource,
  the value of the tag is updated.

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

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

Remove tags from an App Runner resource.

# Arguments
- `resource_arn`: The Amazon Resource Name (ARN) of the resource that you want to remove
  tags from. It must be the ARN of an App Runner resource.
- `tag_keys`: A list of tag keys that you want to remove.

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

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

Update an AWS App Runner service. You can update the source configuration and instance
configuration of the service. You can also update the ARN of the auto scaling configuration
resource that's associated with the service. However, you can't change the name or the
encryption configuration of the service. These can be set only when you create the service.
To update the tags applied to your service, use the separate actions TagResource and
UntagResource. This is an asynchronous operation. On a successful call, you can use the
returned OperationId and the ListOperations call to track the operation's progress.

# Arguments
- `service_arn`: The Amazon Resource Name (ARN) of the App Runner service that you want to
  update.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"AutoScalingConfigurationArn"`: The Amazon Resource Name (ARN) of an App Runner
  automatic scaling configuration resource that you want to associate with your service.
- `"HealthCheckConfiguration"`: The settings for the health check that AWS App Runner
  performs to monitor the health of your service.
- `"InstanceConfiguration"`: The runtime configuration to apply to instances (scaling
  units) of the App Runner service.
- `"SourceConfiguration"`: The source configuration to apply to the App Runner service. You
  can change the configuration of the code or image repository that the service uses.
  However, you can't switch from code to image or the other way around. This means that you
  must provide the same structure member of SourceConfiguration that you originally included
  when you created the service. Specifically, you can include either CodeRepository or
  ImageRepository. To update the source configuration, set the values to members of the
  structure that you include.
"""
update_service(ServiceArn; aws_config::AbstractAWSConfig=global_aws_config()) = apprunner("UpdateService", Dict{String, Any}("ServiceArn"=>ServiceArn); aws_config=aws_config)
update_service(ServiceArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = apprunner("UpdateService", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ServiceArn"=>ServiceArn), params)); aws_config=aws_config)


text:
"""
    extrapolatetoboundary(v, x̄, bc::Tuple{BoundaryCondition, BoundaryCondition})

Returns a `length(x̄)`-vector whose `2:(length(x̄)-1)` elements are `v`,
the first and last element are extrapolated `v` on the boundaries of `x̄` according to
boundary conditions `bc` given.

The first element of `bc` is applied to the lower bound, and second element of `bc` to the upper.
# Examples
```jldoctest; setup = :(using SimpleDifferentialOperators)
julia> x̄ = -2:2
0:5

julia> x = interiornodes(x̄)
  1
  2
  3

julia> v = (x -> x^2).(x)
3-element Array{Int64,1}:
  1
  0
  1

julia> extrapolatetoboundary(v, x̄, (Absorbing(), Absorbing()))
5-element Array{Int64,1}:
  0
  1
  0
  1
  0

julia> extrapolatetoboundary(v, x̄, (Absorbing(), Reflecting()))
 5-element Array{Int64,1}:
  0
  1
  0
  1
  1

julia> extrapolatetoboundary(v, x̄, (Mixed(ξ = 3.0), Reflecting()))
5-element Array{Float64,1}:
 -0.5
  1.0
  0.0
  1.0
  1.0

```
"""
function extrapolatetoboundary(v, x̄, bc::Tuple{BoundaryCondition, BoundaryCondition})
    # setup for extension
    T = eltype(v)

    # default extrapolated boundaries (absorbing for both sides)
    lb_extended = zero(T)
    ub_extended = zero(T)

    # extrapolate on the lower bound
    if (typeof(bc[1]) <: Reflecting)
        lb_extended = v[1]
    elseif (typeof(bc[1]) <: Mixed)
        ξ_lb = bc[1].ξ
        Δ_1_minus = x̄[2] - x̄[1]

        # apply extrapolation based on the directions
        if (bc[1].direction != :backward)
          lb_extended = v[1]/(1-ξ_lb*Δ_1_minus)
        else
          lb_extended = (1+ξ_lb*Δ_1_minus)*v[1]
        end
    end

    # extrapolate on the upper bound
    if (typeof(bc[2]) <: Reflecting)
        ub_extended = v[end]
    elseif (typeof(bc[2]) <: Mixed)
        ξ_ub = bc[2].ξ
        Δ_M_plus = x̄[end] - x̄[end-1]

        # apply extrapolation based on the directions
        if (bc[2].direction != :forward)
          ub_extended = v[end]/(1+ξ_ub*Δ_M_plus)
        else
          ub_extended = (1-ξ_ub*Δ_M_plus)*v[end]
        end
    end

    return [lb_extended; v; ub_extended]
end


text:
using ContinuumWorld
using POMDPs
using POMDPModelTools
using POMDPModels
using POMDPSimulators
using Test
using Plots
using Random

w = CWorld()

@inferred @gen(:sp, :r)(w, [3,2], [4,2], MersenneTwister(19))

sol = CWorldSolver(rng=MersenneTwister(7))
pol = solve(sol, w)

sim = HistoryRecorder(rng=MersenneTwister(5), max_steps=30)
@show state_hist(simulate(sim, w, pol))

#=
write_file(CWorldVis(w, f=norm), joinpath(tempdir(), "test.png"))
@time write_file(CWorldVis(w, f=norm, g=sol.grid), joinpath(tempdir(), "test_timed.png"))
@time write_file(CWorldVis(w, f=norm), joinpath(tempdir(), "test_timed.tif"))
@time write_file(CWorldVis(w, f=norm, g=sol.grid), joinpath(tempdir(), "test_timed.tif"))
@time write_file(CWorldVis(w, f=s->action_ind(pol, s), g=sol.grid, title="Policy"), joinpath(tempdir(), "policy.png"))
@time write_file(CWorldVis(w, f=s->value(pol, s), g=sol.grid, title="Value"), joinpath(tempdir(), "value.png"))
=#
plot(CWorldVis(w, f=s->value(pol, s), g=sol.grid, title="Value"))


text:
function underscore(cur_string::AbstractString)
  cur_string = _decamelize(cur_string)

  snakecase(cur_string)
end


text:
"""
```
B, flags = psf(A; ωₘ, slope, dhₘ, dh₀, cellsize)
```
Applies a progressive slope filter to `A`.

# Output
- `B::Array{T,2}` Maximum allowable values based A + slope, dhₘ, dh₀
- `flags::Array{Float64,2}` A sized array with window sizes if filtered, zero if not filtered.

Afterwards, one can retrieve the resulting mask for `A` by `A .<= B` or `flags .== 0.`.

# Arguments
- `A::Array{T,2}` Input Array
- `ωₘ::Float64=20.` Maximum window size [m]
- `slope::Float64=0.01` Terrain slope [m/m]
- `dhₘ::Float64=2.5` Maximum elevation threshold [m]
- `dh₀::Float64=0.2` Initial elevation threshold [m]
- `cellsize::Float64=1.` Cellsize in [m]
"""
function psf(A::AbstractMatrix{T};
    ωₘ::Float64 = 20.0,
    slope::Float64 = 0.01,
    dhₘ::Float64 = 2.5,
    dh₀::Float64 = 0.2,
    cellsize::Float64 = 1.0,
    circular = false) where {T<:Real}

    # Compute windowsizes and thresholds
    ωₘ = round(Int, ωₘ / cellsize)
    κ_max = floor(Int, log2(ωₘ - 1))  # determine # iterations based on exp growth
    windowsizes = Int.(exp2.(1:κ_max)) .+ 1

    # Compute tresholds
    dwindows = vcat(windowsizes[1], windowsizes)  # prepend first element so we get 0 as diff
    window_diffs = [dwindows[i] - dwindows[i-1] for i = 2:length(dwindows)]
    height_tresholds = [min(dhₘ, slope * window_diff * cellsize + dh₀) for window_diff in window_diffs]
    @info "Using the following thresholds: $height_tresholds for the following windows: $windowsizes"

    # Set up arrays
    Af = copy(A)  # array to be morphed
    nan_mask = isnan.(Af)
    Af[nan_mask] .= Inf  # Replace NaN with Inf, as to always filter these

    B = copy(A)  # max_elevation raster

    flags = zeros(size(A))  # 0 = ground, other values indicate window size
    flags[nan_mask] .= NaN

    mask = falses(size(A))

    # Iterate over window sizes and height tresholds
    p = Progress(sum(windowsizes .^ 2))
    progress = 0
    for (ωₖ, dhₜ) in zip(windowsizes, height_tresholds)
        if circular
            mapwindowcirc!(minimum_mask, A, ωₖ, Af, Inf)
        else
            mapwindow!(minimum, A, ωₖ, Af)
        end
        mask .= (A .- Af) .> dhₜ
        for I in eachindex(flags)
            if mask[I] && flags[I] == 0
                flags[I] = ωₖ
            end
        end
        B .= min.(B, Af .+ dhₜ)
        progress += ωₖ^2
        ProgressMeter.update!(p, progress)
    end

    B, flags
end


text:
function ShaoRSolver(A,b,C,d,XLB,XUB,VariableDef;CUTs = [],AddedUB = Inf,TimeLim = 2e+10,rEPS = 1e-10,aEPS = 1e-10)

    t0 = time_ns();
    # Initialization
    nObj = size(C)[1];
    nVar = size(A)[2];
    nCons = length(b);

    UB = Inf;
    const EPS = 0.00000001;

    # I1
    YI = zeros(nObj);
    Var = zeros(nVar);
    OptX = [];
    OptX2 = [];
    PayoffTable = zeros(nObj,nObj);
    for i = 1:nObj
        SingleObjModel = MakeModel(A,b,C,XLB,XUB,i,Cuts = CUTs);
        # Time commands
        # ----------------------------------------------------------------------
        if TimeLim - (time_ns() - t0)/1e9 < 0.001
            return [],[], AddedUB,OptX2
        end
        # ----------------------------------------------------------------------
        setsolver(SingleObjModel,CplexSolver(CPXPARAM_Threads = 1,CPXPARAM_ScreenOutput = 0, CPXPARAM_TimeLimit = TimeLim - (time_ns() - t0)/1e9));
        status = solve(SingleObjModel);
        # Time commands
        # ----------------------------------------------------------------------
        if TimeLim - (time_ns() - t0)/1e9 < 0.001
            return [],[], AddedUB,OptX2
        end
        # ----------------------------------------------------------------------

        if status != :Optimal
            return [],[], AddedUB,OptX2
        end
        YI[i] = getobjectivevalue(SingleObjModel) + d[i];
        PayoffTable[i,i]= YI[i] ;
        Var = getvalue(getvariable(SingleObjModel,:X))

        for j =1:nObj
            if j==i; continue; end
            PayoffTable[i,j] = sum(Var.*C[j,:]) + d[j];
        end
        if prod(PayoffTable[i,:]) < UB
            UB = prod(PayoffTable[i,:])
            OptX = Var;
        end
        # The idea of finding a good integer solution in relaxed iterations
        # if all(isinteger.(Var[VariableDef[1]+1:end])) & (prod(PayoffTable[i,:]) < AddedUB)
        #     AddedUB = prod(PayoffTable[i,:])
        #     OptX2 = Var;
        # end
    end
    LB = prod(YI);

    # if (LB > AddedUB)
    #     return [],[], AddedUB,OptX2
    # end

    MaxVals = maximum(PayoffTable,1);
    S = [VerticeType(YI,[i for i=2:nObj+1],[i for i=1:nObj],prod(YI))]
    temp = [i for i in 1:nObj+1];
    for i = 1:nObj
        point = copy(YI);
        point[i] = MaxVals[i];
        neighbors = copy(temp);
        neighbors = filter!(j -> j!=i+1 ,neighbors)
        Cuts = copy(temp);
        Cuts = filter!(j -> j!=i ,Cuts);
        T = prod(point);
        push!(S,VerticeType(point,neighbors,Cuts,T ))
    end

    Y = zeros(nObj);
    Var = zeros(nVar);
    CutNum = nObj + 1;
    while true
        # K1
        s = MinimalT2(S)[1];
        P_bar,U_cons,LAMBDA_cons = MakeP_bar(A,b,C,d,XLB,XUB,S[s].Point;Cuts = CUTs)

        # ----------------------------------------------------------------------
        if TimeLim - (time_ns() - t0)/1e9 < 0.001
            return [],[], AddedUB,OptX2
        end
        # ----------------------------------------------------------------------

        setsolver(P_bar,CplexSolver(CPXPARAM_Threads = 1,CPXPARAM_ScreenOutput = 0,CPXPARAM_TimeLimit = TimeLim - (time_ns() - t0)/1e9));

        status = solve(P_bar);
        # ----------------------------------------------------------------------
        if TimeLim - (time_ns() - t0)/1e9 < 0.001
            return [],[], AddedUB,OptX2
        end
        # ----------------------------------------------------------------------
        if status != :Optimal
            return [],[], AddedUB,OptX2
        end
        # U = getdual(U_cons);
        LAMBDA = getdual(LAMBDA_cons);
        # K2
        Var = getvalue(getVar(P_bar,:X))
        for j = 1:nObj
            Y[j] = sum(Var.*C[j,:]) + d[j];
        end

        # # The idea of finding a good integer solution in relaxed iterations
        # if all(isinteger.(Var[VariableDef[1]+1:end])) & (prod(Y) < AddedUB)
        #     AddedUB = prod(Y)
        #     OptX2 = Var
        # end

        if prod(Y) < UB
            UB = prod(Y)
            OptX = Var;
        end
        # K3
        if (abs(UB-LB) <= aEPS) || ((UB-LB)/UB <= rEPS); break; end
        # K4 & K5
        Cut = copy(LAMBDA);
        CutNum = CutNum + 1;
        push!(Cut,-1*sum(Y.*LAMBDA))

        if ~all(abs(Y-S[s].Point) .< EPS)
            S = Vert(deepcopy(S), Cut,CutNum)
        end
        if isempty(S)
            return -2,-2, AddedUB,OptX2
        end
        LB = MinimalT2(S)[2];

        # if (LB > AddedUB)
        #     return [],[], AddedUB,OptX2
        # end

        # println("LB = ",LB," | UB = ",UB)
        if (abs(UB-LB) <= aEPS) || ((UB-LB)/UB <= rEPS); break; end

    end
    return UB,OptX, AddedUB,OptX2
end


text:
# This file is a part of BayesianBlocks.jl, licensed under the MIT License (MIT).

using BayesianBlocks
using StatsBase
using DelimitedFiles
using Test

data = readdlm("data/test.dat")[:,1]

@test_throws MethodError BayesianBlocks.partition(fit(Histogram{Float64}, data), progress=true)

edges = BayesianBlocks.partition(data, progress=true)
@test edges ≈ [-3.48528, -1.87114, -1.36282, -0.677218,
              0.659105, 1.39771, 4.06582, 5.60912,
              6.17286, 7.76634, 9.91696 ] atol = 1E-04

edges = BayesianBlocks.partition(data, logfitness=:cash, logprior=:p0, p0=0.01)
@test edges ≈ [-3.48528, -1.87114, -1.36282, -0.677218,
              0.659105, 1.39771, 4.06582, 5.60912,
              6.17286, 7.76634, 9.91696 ] atol = 1E-04

edges = BayesianBlocks.partition(data, logfitness=:cash, logprior=:gamma, gamma=0.01)
@test edges ≈ [-3.48528, -2.9689, -1.74481, -1.12669,
               -0.24271, 0.492523, 1.27286, 1.59163,
               3.22158, 4.27094, 5.56663, 6.17286,
               7.76634, 9.91696] atol = 1E-04

edges = BayesianBlocks.partition(fit(Histogram, data, nbins=100, closed = :left),
                        logfitness=:cash, logprior=:p0, p0=0.01)
@test edges ≈ [-3.5, -3.1, -1.8, -1.2, -0.4, 0.4, 1.4, 3.6, 4.2, 5.6, 6.2, 7.8, 9.9]

edges = BayesianBlocks.partition(fit(Histogram, data, nbins=100, closed = :left),
                        logfitness=:cash, logprior=:gamma, gamma=0.01)
@test edges ≈ [-3.5, -3.1, -1.8, -1.2, -0.4, 0.4, 1.4, 3.6, 4.2, 5.6, 6.2, 7.8, 9.9]


text:
@valueequals struct Circle
    x::Number
    y::Number

    r::Number

    Circle(x::Number, y::Number, r::Number) = new(x, y, r)
    Circle(x1::Number, y1::Number, x2::Number, y2::Number) = new(x1, y1, sqrt((x1 - x2)^2 + (y1 - y2)^2))
end

function circumference(circle::Circle)
    return 2 * pi * circle.r
end

# Efficient enough, checks might be too small for huge circles
function pointsOnCircle(circle::Circle; filled::Bool=false, checks::Int=max(1, ceil(Int, circumference(circle))))
    res = Set{Tuple{Number, Number}}()
    step = 2 * pi / checks

    if checks > 0
        for theta in 0:step:2 * pi
            ox = cos(theta) * circle.r
            oy = sin(theta) * circle.r

            push!(res, (round(Int, circle.x + ox), round(Int, circle.y + oy)))
            push!(res, (round(Int, circle.x - ox), round(Int, circle.y + oy)))

            if filled
                for i in floor(Int, -ox + 1):ceil(Int, ox - 1)
                    push!(res, (round(Int, circle.x + i), round(Int, circle.y + oy)))
                end
            end
        end
    end

    return collect(res)
end

max_stars_repo_name: CelestialCartographers/Ahorn

max_issues_repo_name: CelestialCartographers/Ahorn

max_forks_repo_name: CelestialCartographers/Ahorn


text:
"""
    freecf(Z; mat="her", obj="kurt", opt="orth")

Apply free component analysis to Z, return estimated
mixing matrix and free components

# Arguments
-   `Z`: an array of matrices of mat and of the same dimensions
-   `mat`: the type of Z[i], valid options are "her" and "rec"
-   `obj`: the type of loss function, valid options are "kurt" and "ent"
-   `opt`: string, type of optimization, valid option: "orth", "sphe"

# Outputs
-   `Aest`: a matrix of size `s`-by-`s`, where `s` = size(Z, 1)
-   `Xest`: an array of "free" matrices, such that `Z = Aest*Xest`
"""
function freecf(Z; mat="her", obj="kurt", opt="orth")

    # freecf is not designed for obj = "ent" and opt = "sphe"
    if (obj == "ent") & (opt == "sphe")
        error("Spherical optimization is not designed for entropy based fcf!")
    end

    # get the dimension of each matrix
    N, M = size(Z[1])
    s = size(Z, 1)

    # check whether the dimension with the mat
    if (mat == "her") && (N != M)
        error("The input components are not a Hermitian matrix")
    end

    # whiten the data
    Y, U, Σ = free_whiten(Z; mat = mat);

    # assign the objective function and derivative according to
    # obj and mat
    if obj == "kurt"
        # if we use kurtosis based cost function
        # obj function
        F = (W, Y) -> neg_abs_sum_free_kurt(W[:,:]'*Y);

        # derivative of obj function
        grad_F = (W, Y) -> grad_neg_abs_sum_free_kurt(W, Y);

    elseif obj == "ent"
        # if we use entropy based cost function
        # obj function
        F = (W, Y) -> sum_free_ent(W[:,:]'*Y; mat = mat);

        # derivative of obj function
        grad_F = (W, Y) -> grad_sum_free_ent(W, Y; mat = mat);
    end

    # optimization over the orthogonal matrix
    if opt == "orth"
        What = OptOrtho(W -> F(W, Y), W -> grad_F(W, Y), s);
    elseif opt == "sphe"
        # recover the columns of W one-by-one
        # first column
        What = reshape(OptSphere(W -> F(W, Y), W -> grad_F(W, Y), s), :, 1)

        # find 2nd to s-1th column one at a time
        for i = 2: (s - 1)
            pY = (I - What*What')*Y

            # updated loss function

            # find i th column, attach it to W
            Wi = OptSphere(W -> F(W, pY), W -> grad_F(W, pY), s)
            What = (qr(hcat(What, Wi)).Q)[:, 1:i]
        end

        # find the s-th column by take qr decomposition
        What = Matrix(qr(hcat(What, randn(s))).Q)
    end

    # compute and return the estimated mixing matrix
    # and free components
    Aest = U*Σ*U'*What;
    Xest = pinv(Aest) * Z;

    # order Xest by the descending order of absolute free kurtosis if obj = "kurt"
    if obj == "kurt"
        order = sortperm(Xest, by = X -> -abs(κ₄(X)))
        Xest = Xest[order]
        Aest = Aest[:,order]
    # order Xest by the aescending order of the free entropy
    elseif obj == "ent"
        order = sortperm(Xest, by = X -> free_ent(X; mat=mat))
        Xest = Xest[order]
        Aest = Aest[:,order]
    end

    return Aest, Xest
end


text:
module TestKMeans
using ParallelKMeans
using Test
using Random

@testset "linear separation" begin
    Random.seed!(2020)

    X = rand(100, 3)
    labels, centroids, sum_squares = kmeans(X, 3; tol = 1e-10, verbose = false)

    # for future reference: Clustering shows here 14.964882850452984
    # guess they use better initialisation. For now we will use own
    # value
    @test sum_squares ≈ 15.314823028363763
end

end # module


text:
using Pkg
Pkg.add("Unitful")
using Unitful

one_meter = 1u"m"

b = uconvert(u"km", one_meter)
b
one_meter

c = ustrip(u"m", one_meter)
c
typeof(c)
one_meter

ustrip(u"km", one_meter)
ustrip(one_meter)
#%%
function compute_speed(Δx, Δt)
    return Δx/Δt
end

compute_speed(1u"km", 2u"s")

function compute_speed(Δx::Unitful.Length, Δt::Unitful.Time)
    return uconvert(u"m/s", Δx/Δt)
end

compute_speed(1u"km", 2u"s")
#%%
struct Person
    height::typeof(1.0u"m")
    mass::typeof(1.0u"kg")
end
#%%
using QuadGK
velocity(t::Unitful.Time) = 2u"m/s^2"*t + 1u"m/s"

quadgk(velocity, 0u"s", 3u"s")[1]

max_stars_repo_name: JeffreySarnoff/techytok-examples

max_issues_repo_name: JeffreySarnoff/techytok-examples

max_forks_repo_name: JeffreySarnoff/techytok-examples


text:
module LinearAlgebraInterface

export _measure

using LinearAlgebra
using ..Common

import ..AbstractEigenproblem
import ..AbstractLinearEigenproblem
import ..AbstractCFEigenproblem
import ..AbstractNonlinearEigenproblem
import ..DEFAULT_LINEAR_EIGENSOLVER
import ..HelmholtzLEP
import ..MaxwellLEP

IrisSymmetric = Common.Symmetric

"""
    normalize!(simulation, ψ, B, [index])

normalize electric field `ψ` with respect to inner product `B`. If `index` is provided,[]
fixes `ψ[index,:]` to be real.
"""
function LinearAlgebra.normalize!(sim::Simulation,ψ,B)
    @inbounds for j ∈ 1:size(ψ,2)
        𝒩² = zero(eltype(ψ))
        # @fastmath @inbounds @simd
        for i ∈ 1:size(ψ,1)
            𝒩² += (ψ[i,j]^2)*B[i,i]*_measure(sim)
        end
        ψ[:,j] /= sqrt(𝒩²)
    end
    return nothing
end

function LinearAlgebra.normalize!(sim::Simulation,ψ,B,ind::Int)
    normalize!(sim,ψ,B)
    @fastmath @inbounds @simd for i ∈ 1:size(ψ,2) ψ[:,i] /= cis(angle(ψ[ind,i])) end
    return nothing
end

"""
    eigen(::AbstractEigenproblem, args...; kwargs...)

See [`helmholtzeigen`](@ref), [`maxwelleigen`](@ref)
"""
function LinearAlgebra.eigen(prob::AbstractEigenproblem, args...; kwargs...)
    if problemtype(prob) <: HelmholtzProblem
        return helmholtzeigen(prob, args...; kwargs...)
    elseif problemtype(prob) <: MaxwellProblem
        return maxwelleigen(prob, args...; kwargs...)
    end
end

function _measure(sim::Simulation{1})
    if typeof(sim.lattice)<:Lattice{1,Cartesian}
        D = sim.dx
    end
    return D
end

function _measure(sim::Simulation{2,IrisSymmetric})
    if typeof(sim.lattice)<:Lattice{2,Cartesian}
        D = sim.dx*sim.dy
    end
    return D
end

end # module

using .LinearAlgebraInterface


text:
"""
Abstract type for a subsystem that contains multiple instances of StaticInjection

Subtypes must implement:
- get_subcomponents(subsystem::StaticInjectionSubsystem)

The subcomponents in subtypes must be attached to the System as masked components.
"""
abstract type StaticInjectionSubsystem <: StaticInjection end

"""
Efficiently add all time series data in the subcomponent to the subsystem by copying the
underlying references.
"""
function copy_subcomponent_time_series!(
    subsystem::StaticInjectionSubsystem,
    subcomponent::Component,
)
    # the existing_ts can remove entries from the set if the Subsystem has two device of
    # the same type with the same time series type and label. Currently in the HybridSystem
    # use case there can only be one devoe of each type.
    existing_ts = Set(
        (typeof(ts), get_name(ts_m)) for
        (ts, ts_m) in IS.get_time_series_with_metadata_multiple(subsystem)
    )
    name_mapping = Dict{Tuple{String, String}, String}()
    device_name = get_name(subcomponent)
    for ts in get_time_series_multiple(subcomponent)
        name = get_name(ts)
        key = (typeof(ts), name)
        if !(key in existing_ts)
            new_name = make_subsystem_time_series_name(subcomponent, ts)
            if name in keys(name_mapping)
                IS.@assert_op new_name == name_mapping[(device_name, name)]
                continue
            end
            name_mapping[(device_name, name)] = new_name
        end
    end

    copy_time_series!(subsystem, subcomponent, name_mapping = name_mapping)
    @info "Copied time series from $(summary(subcomponent)) to $(summary(subsystem))"
end

function make_subsystem_time_series_name(subcomponent::Component, ts::TimeSeriesData)
    return make_subsystem_time_series_name(typeof(subcomponent), get_name(ts))
end

function make_subsystem_time_series_name(subcomponent::Component, label::String)
    return make_subsystem_time_series_name(typeof(subcomponent), label)
end

function make_subsystem_time_series_name(subcomponent::Type{<:Component}, label::String)
    return IS.strip_module_name(subcomponent) * "__" * label
end


text:
# String assignment. Creation and garbage collection are automatic.
a = "123\x00 abc "  # strings can contain bytes that are not printable in the local font
b = "456" * '\x09'
c = "789"
println(a)
println(b)
println(c)

# string comparison
println("(a == b) is $(a == b)")

# String copying.
A = a
B = b
C = c
println(A)
println(B)
println(C)

# check if string is empty
if length(a) == 0
println("string a is empty")
else
println("string a is not empty")
end

# append a byte (actually this is a Char in Julia, and may also be up to 32 bit Unicode) to a string
a= a * '\x64'
println(a)

# extract a substring from string
e = a[1:6]
println(e)

# repeat strings with ^
b4 = b ^ 4
println(b4)

# Replace every occurrence of a string in another string with third string
r = replace(b4, "456" => "xyz")
println(r)

# join strings with *
d = a * b * c
println(d)

max_stars_repo_name: ethansaxenian/RosettaDecode

max_issues_repo_name: ethansaxenian/RosettaDecode

max_forks_repo_name: ethansaxenian/RosettaDecode


text:
# SPDX-License-Identifier: MIT

using EnumX, Test

const T16 = Int16
getInt64() = Int64
const Elppa = -1
const Ananab = -1

@testset "EnumX" begin

# Basic
@enumx Fruit Apple Banana

@test Fruit isa Module
@test Set(names(Fruit)) == Set([:Fruit])
@test_broken Set(names(Fruit; all=true)) == Set([:Fruit, :Apple, :Banana, :T])
@test issubset(Set([:Fruit, :Apple, :Banana, :T]), Set(names(Fruit; all=true)))
@test Fruit.T <: EnumX.Enum{Int32} <: Base.Enum{Int32}
@test !@isdefined(Apple)
@test !@isdefined(Banana)

@test Fruit.Apple isa EnumX.Enum
@test Fruit.Apple isa Base.Enum
@test Fruit.Banana isa EnumX.Enum
@test Fruit.Banana isa Base.Enum

@test instances(Fruit.T) === (Fruit.Apple, Fruit.Banana)
@test Base.Enums.namemap(Fruit.T) == Dict{Int32,Symbol}(0 => :Apple, 1 => :Banana)
@test Base.Enums.basetype(Fruit.T) == Int32

@test Symbol(Fruit.Apple) === :Apple
@test Symbol(Fruit.Banana) === :Banana

@test Integer(Fruit.Apple) === Int32(0)
@test Int(Fruit.Apple) === Int(0)
@test Integer(Fruit.Banana) === Int32(1)
@test Int(Fruit.Banana) === Int(1)

@test Fruit.Apple === Fruit.Apple
@test Fruit.Banana === Fruit.Banana

@test Fruit.T(Int32(0)) === Fruit.T(0) === Fruit.Apple
@test Fruit.T(Int32(1)) === Fruit.T(1) === Fruit.Banana
@test_throws ArgumentError("invalid value for Enum Fruit: 123.") Fruit.T(Int32(123))
@test_throws ArgumentError("invalid value for Enum Fruit: 123.") Fruit.T(123)

@test Fruit.Apple < Fruit.Banana

let io = IOBuffer()
    write(io, Fruit.Apple)
    seekstart(io)
    @test read(io, Fruit.T) === Fruit.Apple
    seekstart(io)
    write(io, Fruit.Banana)
    seekstart(io)
    @test read(io, Fruit.T) === Fruit.Banana
    seekstart(io)
    write(io, Int32(123))
    seekstart(io)
    @test_throws ArgumentError("invalid value for Enum Fruit: 123.") read(io, Fruit.T)
end

let io = IOBuffer()
    show(io, "text/plain", Fruit.T)
    str = String(take!(io))
    @test str == "Enum type Fruit.T <: Enum{Int32} with 2 instances:\n Fruit.Apple  = 0\n Fruit.Banana = 1"
    show(io, "text/plain", Fruit.Apple)
    str = String(take!(io))
    @test str == "Fruit.Apple = 0"
    show(io, "text/plain", Fruit.Banana)
    str = String(take!(io))
    @test str == "Fruit.Banana = 1"
    show(io, "text/plain", EnumX.Enum)
    str = String(take!(io))
    @test str == "EnumX.Enum"
    show(io, "text/plain", EnumX.Enum{Int32})
    str = String(take!(io))
    @test str == "EnumX.Enum{Int32}"
end

# Base type specification
@enumx Fruit8::Int8 Apple
@test Fruit8.T <: EnumX.Enum{Int8} <: Base.Enum{Int8}
@test Base.Enums.basetype(Fruit8.T) === Int8
@test Integer(Fruit8.Apple) === Int8(0)

@enumx FruitU8::UInt8 Apple Banana # no overflow even if first is typemin(T)
@test Base.Enums.basetype(FruitU8.T) === UInt8
@test FruitU8.Apple === FruitU8.T(0)

let io = IOBuffer()
    show(io, "text/plain", FruitU8.T)
    str = String(take!(io))
    @test str == "Enum type FruitU8.T <: Enum{UInt8} with 2 instances:\n FruitU8.Apple  = 0x00\n FruitU8.Banana = 0x01"
    show(io, "text/plain", FruitU8.Apple)
    str = String(take!(io))
    @test str == "FruitU8.Apple = 0x00"
    show(io, "text/plain", FruitU8.Banana)
    str = String(take!(io))
    @test str == "FruitU8.Banana = 0x01"
end

@enumx Fruit16::T16 Apple
@test Fruit16.T <: EnumX.Enum{Int16} <: Base.Enum{Int16}
@test Base.Enums.basetype(Fruit16.T) === Int16
@test Integer(Fruit16.Apple) === Int16(0)

@enumx Fruit64::getInt64() Apple
@test Fruit64.T <: EnumX.Enum{Int64} <: Base.Enum{Int64}
@test Base.Enums.basetype(Fruit64.T) === Int64
@test Integer(Fruit64.Apple) == Int64(0)

try
    @macroexpand @enumx (Fr + uit) Apple
    error()
catch err
    err isa LoadError && (err = err.error)
    @test err isa ArgumentError
    @test err.msg == "invalid EnumX.@enumx type specification: Fr + uit."
end

# Block syntax
@enumx FruitBlock begin
    Apple
    Banana
end
@test FruitBlock.T <: EnumX.Enum{Int32} <: Base.Enum{Int32}
@test FruitBlock.Apple === FruitBlock.T(0)
@test FruitBlock.Banana === FruitBlock.T(1)

@enumx FruitBlock8::Int8 begin
    Apple
    Banana
end
@test FruitBlock8.T <: EnumX.Enum{Int8} <: Base.Enum{Int8}
@test FruitBlock8.Apple === FruitBlock8.T(0)
@test FruitBlock8.Banana === FruitBlock8.T(1)

# Custom values
@enumx FruitValues Apple = 1 Banana = (1 + 2) Orange
@test FruitValues.Apple === FruitValues.T(1)
@test FruitValues.Banana === FruitValues.T(3)
@test FruitValues.Orange === FruitValues.T(4)

@enumx FruitValues8::Int8 Apple = -1 Banana = (1 + 2) Orange
@test FruitValues8.Apple === FruitValues8.T(-1)
@test FruitValues8.Banana === FruitValues8.T(3)
@test FruitValues8.Orange === FruitValues8.T(4)

@enumx FruitValuesBlock begin
    Apple = sum((1, 2, 3))
    Banana
end
@test FruitValuesBlock.Apple === FruitValuesBlock.T(6)
@test FruitValuesBlock.Banana === FruitValuesBlock.T(7)

try
    @macroexpand @enumx Fruit::Int8 Apple=typemax(Int8) Banana
    error()
catch err
    err isa LoadError && (err = err.error)
    @test err isa ArgumentError
    @test err.msg == "value overflow for Enum Fruit: Fruit.Banana = -128."
end
try
    @macroexpand @enumx Fruit::Int8 Apple="apple"
    error()
catch err
    err isa LoadError && (err = err.error)
    @test err isa ArgumentError
    @test err.msg == "invalid value for Enum Fruit{Int8}: Fruit.Apple = \"apple\"."
end
try
    @macroexpand @enumx Fruit::Int8 Apple=128
    error()
catch err
    err isa LoadError && (err = err.error)
    @test err isa ArgumentError
    @test err.msg == "invalid value for Enum Fruit{Int8}: Fruit.Apple = 128."
end
try
    @macroexpand @enumx Fruit::Int8 Apple()
    error()
catch err
    err isa LoadError && (err = err.error)
    @test err isa ArgumentError
    @test err.msg == "invalid EnumX.@enumx entry: Apple()"
end
try
    @macroexpand @enumx Fruit Apple Apple
    error()
catch err
    err isa LoadError && (err = err.error)
    @test err isa ArgumentError
    @test err.msg == "duplicate name for Enum Fruit: Fruit.Apple = 1, name already used for Fruit.Apple = 0."
end

# Duplicate values
@enumx FruitDup Apple=0 Banana=0
@test FruitDup.Apple === FruitDup.Banana === FruitDup.T(0)

let io = IOBuffer()
    show(io, "text/plain", FruitDup.T)
    str = String(take!(io))
    @test str == "Enum type FruitDup.T <: Enum{Int32} with 2 instances:\n FruitDup.Apple  = 0\n FruitDup.Banana = 0"
    show(io, "text/plain", FruitDup.Apple)
    str = String(take!(io))
    @test str == "FruitDup.Apple = FruitDup.Banana = 0"
    show(io, "text/plain", FruitDup.Banana)
    str = String(take!(io))
    @test str == "FruitDup.Apple = FruitDup.Banana = 0"
end

# Initialize with previous instance name
@enumx FruitPrev Elppa Banana=Elppa Orange=Ananab
@test FruitPrev.Elppa === FruitPrev.Banana === FruitPrev.T(0)
@test FruitPrev.Orange === FruitPrev.T(-1)

# Custom typename
@enumx T=Typ FruitT Apple Banana
@test isdefined(FruitT, :Typ)
@test !isdefined(FruitT, :T)
@test FruitT.Typ <: EnumX.Enum
@test FruitT.Apple === FruitT.Typ(0)

let io = IOBuffer()
    show(io, "text/plain", FruitT.Typ)
    str = String(take!(io))
    @test str == "Enum type FruitT.Typ <: Enum{Int32} with 2 instances:\n FruitT.Apple  = 0\n FruitT.Banana = 1"
end

# Custom typename with quoted symbol
@enumx T=:Typ FruitST Apple Banana
@test isdefined(FruitST, :Typ)
@test !isdefined(FruitST, :T)
@test FruitST.Typ <: EnumX.Enum
@test FruitST.Apple === FruitST.Typ(0)

try
    @macroexpand @enumx T=Apple Fruit Apple
    error()
catch err
    err isa LoadError && (err = err.error)
    @test err isa ArgumentError
    @test err.msg == "instance name Fruit.Apple reserved for the Enum typename."
end

# Empty enum
@enumx FruitEmpty
@test instances(FruitEmpty.T) == ()
let io = IOBuffer()
    show(io, "text/plain", FruitEmpty.T)
    str = String(take!(io))
    @test str == "Enum type FruitEmpty.T <: Enum{Int32} with 0 instances"
end

@enumx T=Typ FruitEmptyT
@test instances(FruitEmptyT.Typ) == ()

# Documented type (module) and instances
begin
    """
    Documentation for FruitDoc
    """
    @enumx FruitDoc begin
        "Apple documentation."
        Apple
        """
        Banana documentation
        on multiple lines.
        """
        Banana = 2
        Orange = Apple
    end
    @eval const LINENUMBER = $(@__LINE__)
    @eval const FILENAME = $(@__FILE__)
    @eval const MODULE = $(@__MODULE__)
end

function get_doc_metadata(mod, s)
    Base.Docs.meta(mod)[Base.Docs.Binding(mod, s)].docs[Union{}].data
end

@test FruitDoc.Apple === FruitDoc.T(0)
@test FruitDoc.Banana === FruitDoc.T(2)
@test FruitDoc.Orange === FruitDoc.T(0)

mod_doc = @doc(FruitDoc)
@test sprint(show, mod_doc) == "Documentation for FruitDoc\n"
mod_doc_data = get_doc_metadata(FruitDoc, :FruitDoc)
@test mod_doc_data[:linenumber] == LINENUMBER - 13
@test mod_doc_data[:path] == FILENAME
@test mod_doc_data[:module] == MODULE

apple_doc = @doc(FruitDoc.Apple)
@test sprint(show, apple_doc) == "Apple documentation.\n"
apple_doc_data = get_doc_metadata(FruitDoc, :Apple)
@test apple_doc_data[:linenumber] == LINENUMBER - 9
@test apple_doc_data[:path] == FILENAME
@test apple_doc_data[:module] == FruitDoc

banana_doc = @doc(FruitDoc.Banana)
@test sprint(show, banana_doc) == "Banana documentation on multiple lines.\n"
banana_doc_data = get_doc_metadata(FruitDoc, :Banana)
@test banana_doc_data[:linenumber] == LINENUMBER - 7
@test banana_doc_data[:path] == FILENAME
@test banana_doc_data[:module] == FruitDoc

orange_doc = @doc(FruitDoc.Orange)
@test startswith(sprint(show, orange_doc), "No documentation found")

end # testset


text:
# SECTION 4.2.1

using NetworkDesignModels, Gurobi, JuMP
using DataFrames, JLD2, CSV
using ProgressMeter
NDM = NetworkDesignModels;

# parameters
fulltime = 20
nzs = 4
if length(ARGS) == 0
    delta = 1.0 # 1 - (delta in paper) -- 1.0 in the code corresponds to 0.0 in the paper
    distparam = 1.5
else
    delta = [1.0, 0.9, 0.8][parse(Int, ARGS[1])]
    distparam = [1.4, 1.5][parse(Int, ARGS[2])]
end
@show delta
@show distparam

# load data
env = Gurobi.Env()
options = NDM.MasterOptions(
    nlegs = 1, distparam = distparam,
    nfreqs = 1, costwts = [1.0], freqwts = [1.0], xfrwts = [1.0])
JLD2.@load "data/transit-network-boston.jld2" stns np
@show sum(np.odmatrix .> 0)

# create master problem
rmp = NDM.MasterProblem(
    np,
    linelist = copy(np.lines),
    options = options,
    solver = GurobiSolver(env, OutputFlag = 0)
);
budget = ceil(0.75*sum(NDM.linecost(np,line) for line in np.lines))
NDM.optimize(rmp, budget)
@show length(NDM.commutes(rmp))
@time badcoms = NDM.badcommutecombos(np, options, k=2, rmp=rmp)
@show length(badcoms)

# generate warm start from processed subproblems
directions = [round.([cos(f*pi),sin(f*pi)], digits=3) for f in (1/nzs):(1/nzs):1]
objs = Vector{Float64}()
paths = Vector{Vector{Int}}()
lastpath = nothing
# warm up functions to get accurate running times
sp_d = NDM.SubProblem(rmp,
        maxdist = 1.0,
        solver = GurobiSolver(env, OutputFlag = 0, TimeLimit = 5),
        maxlength = 19,
        direction = directions[1], delta = delta,
        traveltimes = true)
JuMP.@constraint(sp_d.model,
    [bc in badcoms],
    sum(sp_d.srv[uv] for uv in bc) <= length(bc)-1)
temp = NDM.generatecolumn(sp_d, rmp)
if lastpath != nothing
    NDM.trywarmstart(sp_d, temp)
end
# solve
time_warm = time()
for d in 1:length(directions)
    global sp_d = NDM.SubProblem(rmp,
        maxdist = 1.0,
        solver = GurobiSolver(env, OutputFlag = 0, TimeLimit = 1*60),
        maxlength = 19,
        direction = directions[d], delta = delta,
        traveltimes = true);
    # cuts
    JuMP.@constraint(sp_d.model,
        [bc in badcoms],
        sum(sp_d.srv[uv] for uv in bc) <= length(bc)-1)
    if lastpath != nothing
        NDM.trywarmstart(sp_d, lastpath)
    end
    path = NDM.generatecolumn(sp_d, rmp)
    if length(path) > 0 && !NDM.linein(path, rmp.linelist)
        push!(paths, path)
        push!(objs, getobjectivevalue(sp_d.model))
        global lastpath = path
    end
end
time_warm = time() - time_warm
obj_warm = maximum(objs)
println(obj_warm)
path_warm = paths[findmax(objs)[2]]

if delta == 1.0

# solve full subproblem
sp = NDM.SubProblemCP(rmp,
    maxdist = 1.0,
    solver = GurobiSolver(env, OutputFlag = 1, TimeLimit = fulltime*60),
    maxlength = 19,
    traveltimes = true);
NDM.trywarmstart(sp, path_warm)
# cut off reverse solution because this graph is symmetric
for k in 2:length(path_warm)
    JuMP.@constraint(sp.model, sp.edg[path_warm[k],path_warm[k-1]] == 0)
end
# cuts
JuMP.@constraint(sp.model,
    [bc in badcoms],
    sum(sp.srv[uv] for uv in bc) <= length(bc)-1)
path_full = NDM.generatecolumn(sp, rmp, trackingstatuses = [:Intermediate])
time_full = sp.auxinfo[:endtime]
obj_full = getobjectivevalue(sp.model)
time_progress_full = sp.auxinfo[:time]
obj_progress_full = sp.auxinfo[:obj]
bound_progress_full = sp.auxinfo[:bestbound]
gap_full = sp.auxinfo[:bestbound][end]/obj_full-1

# save data
# JLD2.@save "data/results-scale-$(delta)-$(nzs)-$(distparam).jld2" paths objs time_warm obj_warm path_warm time_full obj_full path_full gap_full time_progress_full obj_progress_full bound_progress_full

else

# save data
# JLD2.@save "data/results-scale-$(delta)-$(nzs)-$(distparam).jld2" paths objs time_warm obj_warm path_warm

end


text:
using VoxelPlots.MagicaVoxel
using .MagicaVoxel: VoxData, ChunkStream, ChunkTree, chunk_to_data
using AbstractTrees
using Test

# const vox_dir = "/Applications/MagicaVoxel-0.99.4-alpha-macos/vox/"
const vox_dir = normpath(@__DIR__, "vox")

function resource(filename)::Tuple{ChunkTree, VoxData}
    path = normpath(vox_dir, filename)
    f = open(path)
    tree = ChunkTree([], UInt8[])
    stream = ChunkStream(f, tree)
    vox = MagicaVoxel.parse_vox_file(stream)
    close(stream)
    return (tree, vox)
end

(tree, vox) = resource("empty.vox")
using Colors: RGBA, @colorant_str

(tree2, vox2) = resource("empty2.vox")
# @info :voxels vox2.models[1].voxels
# @info :palette vox2.palette[0xb4+1] == RGBA(colorant"cyan")

@test chunk_to_data(tree, vox2) == chunk_to_data(tree2, vox2)
@test vox.materials == vox2.materials
@test vox.palette == vox2.palette
append!(vox.models[1].voxels, vox2.models[1].voxels)
@test vox == vox2


text:
# passed from a worker to the global report channel
struct WorkReport{N} # each vector has one entry for each action
    id::Int
    error::Bool
    n_obs::SVector{N, Int}
    n_sims::SVector{N, Int}
    qs::SVector{N, Float64}
end

# passed to a single worker channel
struct GlobalUpdate{N}
    global_ns::SVector{N, Int}
    global_qs::SVector{N, Float64}
    new_branch::Nullable{Int}
    terminate::Bool
end


text:
original_directory = pwd()
project_root = joinpath(splitpath(@__DIR__)...)
cd(project_root)

@info("removing depot directory...")
rm(
    joinpath(project_root, "depot");
    force = true,
    recursive = true,
    )
@info("successfully removed depot directory")

@info("removing environments directory...")
rm(
    joinpath(project_root, "environments");
    force = true,
    recursive = true,
    )
@info("successfully removed environments directory")

@info("removing repos directory...")
rm(
    joinpath(project_root, "repos");
    force = true,
    recursive = true,
    )
@info("successfully removed repos directory")

@info("removing packages directory...")
rm(
    joinpath(project_root, "packages");
    force = true,
    recursive = true,
    )
@info("successfully removed packages directory")

@info("removing Registry.toml...")
rm(
    joinpath(project_root, "Registry.toml",);
    force = true,
    recursive = true,
    )
@info("successfully removed Registry.toml")

@info("removing build/")
rm(
    joinpath(project_root, "build",);
    force = true,
    recursive = true,
    )
@info("successfully removed build/")

cd(original_directory)

max_forks_repo_name: DilumAluthge/PredictMDRegistryOffline


text:
using GeometryTypes, Reactive, GLVisualize
using GLPlot

"""
Lorenz function
"""
function lorenz(t0, a, b, c, h)
    Point3f0(
        t0[1] + h * a * (t0[2] - t0[1]),
        t0[2] + h * (t0[1] * (b - t0[3]) - t0[2]),
        t0[3] + h * (t0[1] * t0[2] - c * t0[3]),
    )
end
# step through the `time`
function lorenz(array::Vector, a=5.0,b=2.0,c=6.0,d=0.01)
    t0 = Point3f0(0.1, 0, 0)
    for i=eachindex(array)
        t0 = lorenz(t0, a,b,c,d)
        array[i] = t0
    end
    array
end

# create sliders to interact with the parameters of the lorenz function
slidera = GLPlot.play_widget(linspace(0.1f0, 40f0, 30))
sliderb = GLPlot.play_widget(linspace(0.1f0, 40f0, 30))
sliderc = GLPlot.play_widget(linspace(0.1f0, 40f0, 30))
sliderd = GLPlot.play_widget(linspace(0.001f0, 0.5f0, 30))

# N time steps
n = 10_000
# foldp registers a callback (in this case lorenz), which updates the points
# whenever the slider changes.
points = foldp(lorenz, Array(Point3f0, n), slidera, sliderb, sliderc, sliderd)
# we set the boundingbox to nothing, since we don't need it and don't want to
# calculate it for every update (which is the default)
glplot(points, :lines, preferred_camera = :perspective)
# you can also visualize the points
glplot(
    (Circle(Point2f0(0), 0.01f0), points),
    preferred_camera = :perspective
)
# the above renders an antia aliased nice looking circle which could have outlines and glows.
# this makes it relatively slow. For optimal performance, one might need the command below
# which draws one (or n) pixel per point
#glplot(points, :speed, boundingbox=nothing, preferred_camera=:perspective)


text:
function preprocessing(model::Model)

    ## Fixing all groups of 1st week

    q = model.p ÷ model.g

    for i in 1:model.g
        sol = Vector{Int}(undef, q)
        for j in 1:q
            sol[j] = (i-1)*q + j
        end
        model.X[i,1].upperBound = sol
        model.X[i,1].lowerBound = sol
        fix!(model.X[i, 1], Change(model.X[i, 1]))
    end

    ## Fixing 1st element of first q groups (or g if g < q, but the problem is infeasible when w > 1)

    for i in 2:model.w
        for j in 1:min(q,model.g)
            push!(model.X[j,i].lowerBound, j)
        end
    end
end

function quoi()
    model = ModelTest()
    preprocessing(model)
end


text:
number1arg = [
(:abs, :(sign(x))),
(:abs2, :(2x)),
]

for (f,g) in number1arg
    @eval @primitive $f(x),dy,y  (dy.*($g))
    addtest1(f,(-Inf,Inf))
end

number1zero = [
:isinteger,
:sign,
:signbit,
]
for f in number1zero; @eval @zerograd $f(x); end

# TODO:
# size: interfaces.jl
# eltype: interfaces.jl
# ndims: interfaces.jl
# length: interfaces.jl
# endof: interfaces.jl
# getindex: interfaces.jl
# unsafe_getindex: Not exported
# first: compound using start/next
# last: compound using getindex/endof
# divrem
# fldmod
# copysign
# conj
# transpose
# ctranspose
# inv
# angle
# widemul
# start: interfaces.jl
# next: interfaces.jl
# done: interfaces.jl
# isempty: interfaces.jl
# in
# map
# zero: interfaces.jl
# one: interfaces.jl
# factorial


text:
using Images, Colors
using FileIO
using ImageView
using LinearAlgebra
using LightXML
using Glob

function getCoords(fileName)
    xml = parse_file(fileName)
    xroot = root(xml)
    ces = xroot["table"]
    out = []
    for i in 1:length(ces)
        t=find_element(ces[i], "Coords")
        p = attribute(t,"points")
        a = [split(i," ") for i in split(p,",")]
        c = collect(Iterators.flatten(a))
        toInt = [parse(Int,num) for num in c]
        xs=[toInt[2+(n-1)*2] for n in 1:4]
        ys=[toInt[1+(n-1)*2] for n in 1:4]
        xmin = minimum(xs)
        xmax = maximum(xs)
        ymin = minimum(ys)
        ymax = maximum(ys)
        coords = [xmin,xmax,ymin,ymax]
        append!(out,coords)
    end
    return reshape(out,(4,length(ces)))
end

function createMask(filename)
    coords = getCoords(filename)
    img = load(replace(filename,".xml"=>".jpg"))
    mask = zeros(size(img))
    for i in 1:size(coords)[2]
        mask[coords[1,i]:coords[2,i],coords[3,i]:coords[4,i]] .= 1;
    end
    return img .* mask
end

# Get all xml files in directory
fnames = glob("*.xml","./ICDAR2019_cTDaR/training/TRACKA/ground_truth/")

# Create mask for each file in directory
for f in fnames
    filename = replace(f,".xml"=>"_mask.png")
    try
        m = createMask(f)
        save(filename,m)
    catch
        println(filename)
    end
end


text:
#################### Raftery and Lewis Diagnostic ####################

"""
    rafterydiag(x::AbstractVector{<:Real}; q, r, s, eps, range)

Compute the Raftery and Lewis diagnostic.
"""
function rafterydiag(
    x::AbstractVector{<:Real}; q=0.025, r=0.005, s=0.95, eps=0.001, range=1:length(x)
)
    nx = length(x)
    phi = sqrt(2.0) * SpecialFunctions.erfinv(s)
    nmin = ceil(Int, q * (1.0 - q) * (phi / r)^2)
    if nmin > nx
        @warn "At least $nmin samples are needed for specified q, r, and s"
        kthin = -1
        burnin = total = NaN
    else
        dichot = Int[(x .<= StatsBase.quantile(x, q))...]
        kthin = 0
        bic = 1.0
        local test , ntest
        while bic >= 0.0
            kthin += 1
            test = dichot[1:kthin:nx]
            ntest = length(test)
            temp = test[1:(ntest - 2)] + 2 * test[2:(ntest - 1)] + 4 * test[3:ntest]
            trantest = reshape(StatsBase.counts(temp, 0:7), 2, 2, 2)
            g2 = 0.0
            for i1 in 1:2, i2 in 1:2, i3 in 1:2
                tt = trantest[i1, i2, i3]
                if tt > 0
                    fitted =
                        sum(trantest[:, i2, i3]) * sum(trantest[i1, i2, :]) /
                        sum(trantest[:, i2, :])
                    g2 += 2.0 * tt * log(tt / fitted)
                end
            end
            bic = g2 - 2.0 * log(ntest - 2.0)
        end

        tranfinal = StatsBase.counts(test[1:(ntest - 1)] + 2 * test[2:ntest], 0:3)
        alpha = tranfinal[3] / (tranfinal[1] + tranfinal[3])
        beta = tranfinal[2] / (tranfinal[2] + tranfinal[4])
        kthin *= step(range)
        m = log(eps * (alpha + beta) / max(alpha, beta)) / log(abs(1.0 - alpha - beta))
        burnin = kthin * ceil(m) + first(range) - 1
        n = ((2.0 - alpha - beta) * alpha * beta * phi^2) / (r^2 * (alpha + beta)^3)
        keep = kthin * ceil(n)
        total = burnin + keep
    end
    return (
        thinning=kthin, burnin=burnin, total=total, nmin=nmin, dependencefactor=total / nmin
    )
end


text:
#Create and initialize shaders
module ShadersAndVerticies
using ModernGL, GeometryTypes, GLFW, ..ForDisplayStructs,  ..CustomFragShad,  ..ModernGlUtil

export createFragmentShader
export positions
export elements
export getMainVerticies
export createVertexShader

"""
creating VertexShader  so controlling structures like verticies, quads
gslString so version of GSLS we are using currently
  """
function createVertexShader(gslString::String)
vsh = """
$(gslString)
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec3 aColor;
layout (location = 2) in vec2 aTexCoord;
out vec3 ourColor;
smooth out vec2 TexCoord0;
void main()
{
    gl_Position = vec4(aPos, 1.0);
    ourColor = aColor;
 //  TexCoord0 = vec2(-aTexCoord.y, aTexCoord.x);
   TexCoord0 = aTexCoord;

}
"""
return createShader(vsh, GL_VERTEX_SHADER)
end

"""
loading the shader from file- so we have better experience writing shader in separate file (can be used if we do not use Custom frag shader)
"""
function getShaderFileText(path::String)
f = open(path)
return  join(readlines(f), "\n")
end #getShaderFileText

"""
creating fragment Shader  so controlling colors and textures
gslString so version of GSLS we are using currently
  """
function createFragmentShader(gslString::String
                          ,listOfTexturesToCreate::Vector{TextureSpec}
                          ,maskToSubtractFrom::TextureSpec
                          ,maskWeAreSubtracting ::TextureSpec)
    fsh = """
    $(gslString)
    $( createCustomFramgentShader(listOfTexturesToCreate,maskToSubtractFrom,maskWeAreSubtracting))
    """
    return createShader(fsh, GL_FRAGMENT_SHADER)
    end

################### data to display verticies

# Specify how vertices are arranged into faces
# Face{N,T} type specifies a face with N vertices, with index type
# T (you should choose UInt32), and index-offset O. If you're
# specifying faces in terms of julia's 1-based indexing, you should set
# O=0. (If you instead number the vertices starting with 0, set
# O=-1.)
elements = Face{3,UInt32}[(0,1,2),          # the first triangle
(2,3,0)]          # the second triangle

  end #..ShadersAndVerticies


text:
# This file was generated by the Julia Swagger Code Generator
# Do not modify this file directly. Modify the swagger specification instead.

mutable struct RollingUpgradePolicy <: SwaggerModel
    maxBatchInstancePercent::Any # spec type: Union{ Nothing, Int32 } # spec name: maxBatchInstancePercent
    maxUnhealthyInstancePercent::Any # spec type: Union{ Nothing, Int32 } # spec name: maxUnhealthyInstancePercent
    maxUnhealthyUpgradedInstancePercent::Any # spec type: Union{ Nothing, Int32 } # spec name: maxUnhealthyUpgradedInstancePercent
    pauseTimeBetweenBatches::Any # spec type: Union{ Nothing, String } # spec name: pauseTimeBetweenBatches

    function RollingUpgradePolicy(;maxBatchInstancePercent=nothing, maxUnhealthyInstancePercent=nothing, maxUnhealthyUpgradedInstancePercent=nothing, pauseTimeBetweenBatches=nothing)
        o = new()
        validate_property(RollingUpgradePolicy, Symbol("maxBatchInstancePercent"), maxBatchInstancePercent)
        setfield!(o, Symbol("maxBatchInstancePercent"), maxBatchInstancePercent)
        validate_property(RollingUpgradePolicy, Symbol("maxUnhealthyInstancePercent"), maxUnhealthyInstancePercent)
        setfield!(o, Symbol("maxUnhealthyInstancePercent"), maxUnhealthyInstancePercent)
        validate_property(RollingUpgradePolicy, Symbol("maxUnhealthyUpgradedInstancePercent"), maxUnhealthyUpgradedInstancePercent)
        setfield!(o, Symbol("maxUnhealthyUpgradedInstancePercent"), maxUnhealthyUpgradedInstancePercent)
        validate_property(RollingUpgradePolicy, Symbol("pauseTimeBetweenBatches"), pauseTimeBetweenBatches)
        setfield!(o, Symbol("pauseTimeBetweenBatches"), pauseTimeBetweenBatches)
        o
    end
end # type RollingUpgradePolicy

const _property_map_RollingUpgradePolicy = Dict{Symbol,Symbol}(Symbol("maxBatchInstancePercent")=>Symbol("maxBatchInstancePercent"), Symbol("maxUnhealthyInstancePercent")=>Symbol("maxUnhealthyInstancePercent"), Symbol("maxUnhealthyUpgradedInstancePercent")=>Symbol("maxUnhealthyUpgradedInstancePercent"), Symbol("pauseTimeBetweenBatches")=>Symbol("pauseTimeBetweenBatches"))
const _property_types_RollingUpgradePolicy = Dict{Symbol,String}(Symbol("maxBatchInstancePercent")=>"Int32", Symbol("maxUnhealthyInstancePercent")=>"Int32", Symbol("maxUnhealthyUpgradedInstancePercent")=>"Int32", Symbol("pauseTimeBetweenBatches")=>"String")
Base.propertynames(::Type{ RollingUpgradePolicy }) = collect(keys(_property_map_RollingUpgradePolicy))
Swagger.property_type(::Type{ RollingUpgradePolicy }, name::Symbol) = Union{Nothing,eval(Meta.parse(_property_types_RollingUpgradePolicy[name]))}
Swagger.field_name(::Type{ RollingUpgradePolicy }, property_name::Symbol) =  _property_map_RollingUpgradePolicy[property_name]

function check_required(o::RollingUpgradePolicy)
    true
end

function validate_property(::Type{ RollingUpgradePolicy }, name::Symbol, val)
    if name === Symbol("maxBatchInstancePercent")
        Swagger.validate_param(name, "RollingUpgradePolicy", :maximum, val, 100, false)
        Swagger.validate_param(name, "RollingUpgradePolicy", :minimum, val, 5, false)
    end
    if name === Symbol("maxUnhealthyInstancePercent")
        Swagger.validate_param(name, "RollingUpgradePolicy", :maximum, val, 100, false)
        Swagger.validate_param(name, "RollingUpgradePolicy", :minimum, val, 5, false)
    end
    if name === Symbol("maxUnhealthyUpgradedInstancePercent")
        Swagger.validate_param(name, "RollingUpgradePolicy", :maximum, val, 100, false)
        Swagger.validate_param(name, "RollingUpgradePolicy", :minimum, val, 0, false)
    end
end


text:
# Analyze convergence of Monte Carlo tree search while varying the exploration
# constant

using SubmodularMaximization
using PyPlot
using Statistics
using Base.Threads
using Base.Iterators
using JLD2

close()

data_folder = "./data"
experiment_name = "mcts_exploration_constant_data"
reprocess = false

num_trials = 1:100
num_mcts_samples = map(x->round(Int64, x), 1.3 .^ (15:26))

horizon = SubmodularMaximization.default_horizon

exploration_constants =  1.03 .* [0.1, 0.5, 0.7, 1.0, 1.3, 1.5, 10.0]

grid_size = 12
const sensor = RangingSensor()

# place the target in the center of the grid
const grid = Grid(grid_size, grid_size)
const target_state = (8,8)
const robot_state = (3,3)

# Create some uncertainty. Two steps is probably a reasonable approximation of
# the kind of target uncertainty that we will encounter
const histogram_filter = Filter(grid, target_state)
process_update!(histogram_filter, transition_matrix(grid))

const problem = SingleRobotTargetTrackingProblem(grid, sensor, horizon,
                                                 [histogram_filter])

all_tests = product(exploration_constants, num_mcts_samples, num_trials)
all_configurations = product(exploration_constants, num_mcts_samples)

function trial_fun(x)
  (exploration_constant, num_mcts_samples, trial) = x

  trajectory = solve_single_robot(problem, robot_state,
                                  n_iterations=num_mcts_samples,
                                  exploration_constant=exploration_constant
                                 ).trajectory

  # evaluate mutual information using the default number of samples (which
  # should be quite accurate)
  finite_horizon_information(grid, histogram_filter, sensor,
                             trajectory).reward
end
function print_summary(x)
  (exploration_constant, num_mcts_samples, trial) = x

  println("Exploration constant: ", exploration_constant,
          " Num. samples: ", num_mcts_samples,
          " Trial: ", trial,
         )
end

@time data = run_experiments(all_tests,
                             trial_fun=trial_fun,
                             print_summary=print_summary,
                             experiment_name=experiment_name,
                             data_folder=data_folder,
                             reprocess=reprocess,
                            )

mean_rewards = map(all_configurations) do configuration
  mean(x->data[configuration..., x], num_trials)
end

maximum_reward = maximum(mean_rewards)

for (ii, exploration_constant) in enumerate(exploration_constants)
  data = mean_rewards[ii,:]
  fraction_rewards =  data ./ maximum_reward

  label = string("Exp. const.: ", exploration_constant)
  loglog(num_mcts_samples, fraction_rewards, label=label)
end

title("MCTS convergence")
xlabel("Num rollouts")
ylabel("Frac. of max. reward")
legend(loc="upper left")

save_fig("fig", "mcts_exploration_constants")

max_stars_repo_name: mcorah/MultiAgentSensing

max_issues_repo_name: mcorah/MultiAgentSensing

max_forks_repo_name: mcorah/MultiAgentSensing


text:
#=
The following iterative sequence is defined for the set of positive integers:

n → n/2 (n is even)
n → 3n + 1 (n is odd)

Using the rule above and starting with 13, we generate the following sequence:

13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.

Which starting number, under one million, produces the longest chain?

NOTE: Once the chain starts the terms are allowed to go above one million.
=#

function find_collatz(x::Int64)
  count = 0
  while x > 1
    x = iseven(x) ? div(x,2) : 3x+1
    count +=1
  end
  count
end

function calc()
  startnumber = 1
  longest = 1
  for i in 1:1_000_000
    c = find_collatz(i)
    if c > longest
      longest = c
      startnumber = i
    end
  end
  startnumber
end
@time println(calc())

max_stars_repo_name: daniel-beard/JuliaProjectEuler

max_issues_repo_name: daniel-beard/JuliaProjectEuler

max_forks_repo_name: daniel-beard/JuliaProjectEuler