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

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

Creates a backup plan using a backup plan name and backup rules. A backup plan is a
document that contains information that AWS Backup uses to schedule tasks that create
recovery points for resources. If you call CreateBackupPlan with a plan that already
exists, an AlreadyExistsException is returned.

# Arguments
- `backup_plan`: Specifies the body of a backup plan. Includes a BackupPlanName and one or
  more sets of Rules.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"BackupPlanTags"`: To help organize your resources, you can assign your own metadata to
  the resources that you create. Each tag is a key-value pair. The specified tags are
  assigned to all backups created with this plan.
- `"CreatorRequestId"`: Identifies the request and allows failed requests to be retried
  without the risk of running the operation twice. If the request includes a CreatorRequestId
  that matches an existing backup plan, that plan is returned. This parameter is optional.
"""
create_backup_plan(BackupPlan; aws_config::AbstractAWSConfig=global_aws_config()) = backup("PUT", "/backup/plans/", Dict{String, Any}("BackupPlan"=>BackupPlan); aws_config=aws_config)
create_backup_plan(BackupPlan, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = backup("PUT", "/backup/plans/", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("BackupPlan"=>BackupPlan), params)); aws_config=aws_config)

"""
    create_backup_selection(backup_selection, backup_plan_id)
    create_backup_selection(backup_selection, backup_plan_id, params::Dict{String,<:Any})

Creates a JSON document that specifies a set of resources to assign to a backup plan.
Resources can be included by specifying patterns for a ListOfTags and selected Resources.
For example, consider the following patterns:    Resources:
\"arn:aws:ec2:region:account-id:volume/volume-id\"     ConditionKey:\"department\"
ConditionValue:\"finance\"   ConditionType:\"StringEquals\"     ConditionKey:\"importance\"
  ConditionValue:\"critical\"   ConditionType:\"StringEquals\"    Using these patterns
would back up all Amazon Elastic Block Store (Amazon EBS) volumes that are tagged as
\"department=finance\", \"importance=critical\", in addition to an EBS volume with the
specified volume ID. Resources and conditions are additive in that all resources that match
the pattern are selected. This shouldn't be confused with a logical AND, where all
conditions must match. The matching patterns are logically put together using the OR
operator. In other words, all patterns that match are selected for backup.

# Arguments
- `backup_selection`: Specifies the body of a request to assign a set of resources to a
  backup plan.
- `backup_plan_id`: Uniquely identifies the backup plan to be associated with the selection
  of resources.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"CreatorRequestId"`: A unique string that identifies the request and allows failed
  requests to be retried without the risk of running the operation twice.
"""
create_backup_selection(BackupSelection, backupPlanId; aws_config::AbstractAWSConfig=global_aws_config()) = backup("PUT", "/backup/plans/$(backupPlanId)/selections/", Dict{String, Any}("BackupSelection"=>BackupSelection); aws_config=aws_config)
create_backup_selection(BackupSelection, backupPlanId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = backup("PUT", "/backup/plans/$(backupPlanId)/selections/", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("BackupSelection"=>BackupSelection), params)); aws_config=aws_config)

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

Creates a logical container where backups are stored. A CreateBackupVault request includes
a name, optionally one or more resource tags, an encryption key, and a request ID.
Sensitive data, such as passport numbers, should not be included the name of a backup
vault.

# Arguments
- `backup_vault_name`: The name of a logical container where backups are stored. Backup
  vaults are identified by names that are unique to the account used to create them and the
  AWS Region where they are created. They consist of letters, numbers, and hyphens.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"BackupVaultTags"`: Metadata that you can assign to help organize the resources that you
  create. Each tag is a key-value pair.
- `"CreatorRequestId"`: A unique string that identifies the request and allows failed
  requests to be retried without the risk of running the operation twice.
- `"EncryptionKeyArn"`: The server-side encryption key that is used to protect your
  backups; for example,
  arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab.
"""
create_backup_vault(backupVaultName; aws_config::AbstractAWSConfig=global_aws_config()) = backup("PUT", "/backup-vaults/$(backupVaultName)"; aws_config=aws_config)
create_backup_vault(backupVaultName, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = backup("PUT", "/backup-vaults/$(backupVaultName)", params; aws_config=aws_config)

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

Deletes a backup plan. A backup plan can only be deleted after all associated selections of
resources have been deleted. Deleting a backup plan deletes the current version of a backup
plan. Previous versions, if any, will still exist.

# Arguments
- `backup_plan_id`: Uniquely identifies a backup plan.

"""
delete_backup_plan(backupPlanId; aws_config::AbstractAWSConfig=global_aws_config()) = backup("DELETE", "/backup/plans/$(backupPlanId)"; aws_config=aws_config)
delete_backup_plan(backupPlanId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = backup("DELETE", "/backup/plans/$(backupPlanId)", params; aws_config=aws_config)

"""
    delete_backup_selection(backup_plan_id, selection_id)
    delete_backup_selection(backup_plan_id, selection_id, params::Dict{String,<:Any})

Deletes the resource selection associated with a backup plan that is specified by the
SelectionId.

# Arguments
- `backup_plan_id`: Uniquely identifies a backup plan.
- `selection_id`: Uniquely identifies the body of a request to assign a set of resources to
  a backup plan.

"""
delete_backup_selection(backupPlanId, selectionId; aws_config::AbstractAWSConfig=global_aws_config()) = backup("DELETE", "/backup/plans/$(backupPlanId)/selections/$(selectionId)"; aws_config=aws_config)
delete_backup_selection(backupPlanId, selectionId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = backup("DELETE", "/backup/plans/$(backupPlanId)/selections/$(selectionId)", params; aws_config=aws_config)

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

Deletes the backup vault identified by its name. A vault can be deleted only if it is empty.

# Arguments
- `backup_vault_name`: The name of a logical container where backups are stored. Backup
  vaults are identified by names that are unique to the account used to create them and the
  AWS Region where they are created. They consist of lowercase letters, numbers, and hyphens.

"""
delete_backup_vault(backupVaultName; aws_config::AbstractAWSConfig=global_aws_config()) = backup("DELETE", "/backup-vaults/$(backupVaultName)"; aws_config=aws_config)
delete_backup_vault(backupVaultName, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = backup("DELETE", "/backup-vaults/$(backupVaultName)", params; aws_config=aws_config)

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

Deletes the policy document that manages permissions on a backup vault.

# Arguments
- `backup_vault_name`: The name of a logical container where backups are stored. Backup
  vaults are identified by names that are unique to the account used to create them and the
  AWS Region where they are created. They consist of lowercase letters, numbers, and hyphens.

"""
delete_backup_vault_access_policy(backupVaultName; aws_config::AbstractAWSConfig=global_aws_config()) = backup("DELETE", "/backup-vaults/$(backupVaultName)/access-policy"; aws_config=aws_config)
delete_backup_vault_access_policy(backupVaultName, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = backup("DELETE", "/backup-vaults/$(backupVaultName)/access-policy", params; aws_config=aws_config)

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

Deletes event notifications for the specified backup vault.

# Arguments
- `backup_vault_name`: The name of a logical container where backups are stored. Backup
  vaults are identified by names that are unique to the account used to create them and the
  Region where they are created. They consist of lowercase letters, numbers, and hyphens.

"""
delete_backup_vault_notifications(backupVaultName; aws_config::AbstractAWSConfig=global_aws_config()) = backup("DELETE", "/backup-vaults/$(backupVaultName)/notification-configuration"; aws_config=aws_config)
delete_backup_vault_notifications(backupVaultName, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = backup("DELETE", "/backup-vaults/$(backupVaultName)/notification-configuration", params; aws_config=aws_config)

"""
    delete_recovery_point(backup_vault_name, recovery_point_arn)
    delete_recovery_point(backup_vault_name, recovery_point_arn, params::Dict{String,<:Any})

Deletes the recovery point specified by a recovery point ID. If the recovery point ID
belongs to a continuous backup, calling this endpoint deletes the existing continuous
backup and stops future continuous backup.

# Arguments
- `backup_vault_name`: The name of a logical container where backups are stored. Backup
  vaults are identified by names that are unique to the account used to create them and the
  AWS Region where they are created. They consist of lowercase letters, numbers, and hyphens.
- `recovery_point_arn`: An Amazon Resource Name (ARN) that uniquely identifies a recovery
  point; for example,
  arn:aws:backup:us-east-1:123456789012:recovery-point:1EB3B5E7-9EB0-435A-A80B-108B488B0D45.

"""
delete_recovery_point(backupVaultName, recoveryPointArn; aws_config::AbstractAWSConfig=global_aws_config()) = backup("DELETE", "/backup-vaults/$(backupVaultName)/recovery-points/$(recoveryPointArn)"; aws_config=aws_config)
delete_recovery_point(backupVaultName, recoveryPointArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = backup("DELETE", "/backup-vaults/$(backupVaultName)/recovery-points/$(recoveryPointArn)", params; aws_config=aws_config)

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

Returns backup job details for the specified BackupJobId.

# Arguments
- `backup_job_id`: Uniquely identifies a request to AWS Backup to back up a resource.

"""
describe_backup_job(backupJobId; aws_config::AbstractAWSConfig=global_aws_config()) = backup("GET", "/backup-jobs/$(backupJobId)"; aws_config=aws_config)
describe_backup_job(backupJobId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = backup("GET", "/backup-jobs/$(backupJobId)", params; aws_config=aws_config)

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

Returns metadata about a backup vault specified by its name.

# Arguments
- `backup_vault_name`: The name of a logical container where backups are stored. Backup
  vaults are identified by names that are unique to the account used to create them and the
  AWS Region where they are created. They consist of lowercase letters, numbers, and hyphens.

"""
describe_backup_vault(backupVaultName; aws_config::AbstractAWSConfig=global_aws_config()) = backup("GET", "/backup-vaults/$(backupVaultName)"; aws_config=aws_config)
describe_backup_vault(backupVaultName, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = backup("GET", "/backup-vaults/$(backupVaultName)", params; aws_config=aws_config)

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

Returns metadata associated with creating a copy of a resource.

# Arguments
- `copy_job_id`: Uniquely identifies a copy job.

"""
describe_copy_job(copyJobId; aws_config::AbstractAWSConfig=global_aws_config()) = backup("GET", "/copy-jobs/$(copyJobId)"; aws_config=aws_config)
describe_copy_job(copyJobId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = backup("GET", "/copy-jobs/$(copyJobId)", params; aws_config=aws_config)

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

Describes the global settings of the AWS account, including whether it is opted in to
cross-account backup.

"""
describe_global_settings(; aws_config::AbstractAWSConfig=global_aws_config()) = backup("GET", "/global-settings"; aws_config=aws_config)
describe_global_settings(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = backup("GET", "/global-settings", params; aws_config=aws_config)

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

Returns information about a saved resource, including the last time it was backed up, its
Amazon Resource Name (ARN), and the AWS service type of the saved resource.

# Arguments
- `resource_arn`: An Amazon Resource Name (ARN) that uniquely identifies a resource. The
  format of the ARN depends on the resource type.

"""
describe_protected_resource(resourceArn; aws_config::AbstractAWSConfig=global_aws_config()) = backup("GET", "/resources/$(resourceArn)"; aws_config=aws_config)
describe_protected_resource(resourceArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = backup("GET", "/resources/$(resourceArn)", params; aws_config=aws_config)

"""
    describe_recovery_point(backup_vault_name, recovery_point_arn)
    describe_recovery_point(backup_vault_name, recovery_point_arn, params::Dict{String,<:Any})

Returns metadata associated with a recovery point, including ID, status, encryption, and
lifecycle.

# Arguments
- `backup_vault_name`: The name of a logical container where backups are stored. Backup
  vaults are identified by names that are unique to the account used to create them and the
  AWS Region where they are created. They consist of lowercase letters, numbers, and hyphens.
- `recovery_point_arn`: An Amazon Resource Name (ARN) that uniquely identifies a recovery
  point; for example,
  arn:aws:backup:us-east-1:123456789012:recovery-point:1EB3B5E7-9EB0-435A-A80B-108B488B0D45.

"""
describe_recovery_point(backupVaultName, recoveryPointArn; aws_config::AbstractAWSConfig=global_aws_config()) = backup("GET", "/backup-vaults/$(backupVaultName)/recovery-points/$(recoveryPointArn)"; aws_config=aws_config)
describe_recovery_point(backupVaultName, recoveryPointArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = backup("GET", "/backup-vaults/$(backupVaultName)/recovery-points/$(recoveryPointArn)", params; aws_config=aws_config)

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

Returns the current service opt-in settings for the Region. If service-opt-in is enabled
for a service, AWS Backup tries to protect that service's resources in this Region, when
the resource is included in an on-demand backup or scheduled backup plan. Otherwise, AWS
Backup does not try to protect that service's resources in this Region, AWS Backup does not
try to protect that service's resources in this Region.

"""
describe_region_settings(; aws_config::AbstractAWSConfig=global_aws_config()) = backup("GET", "/account-settings"; aws_config=aws_config)
describe_region_settings(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = backup("GET", "/account-settings", params; aws_config=aws_config)

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

Returns metadata associated with a restore job that is specified by a job ID.

# Arguments
- `restore_job_id`: Uniquely identifies the job that restores a recovery point.

"""
describe_restore_job(restoreJobId; aws_config::AbstractAWSConfig=global_aws_config()) = backup("GET", "/restore-jobs/$(restoreJobId)"; aws_config=aws_config)
describe_restore_job(restoreJobId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = backup("GET", "/restore-jobs/$(restoreJobId)", params; aws_config=aws_config)

"""
    disassociate_recovery_point(backup_vault_name, recovery_point_arn)
    disassociate_recovery_point(backup_vault_name, recovery_point_arn, params::Dict{String,<:Any})

Deletes the specified continuous backup recovery point from AWS Backup and releases control
of that continuous backup to the source service, such as Amazon RDS. The source service
will continue to create and retain continuous backups using the lifecycle that you
specified in your original backup plan. Does not support snapshot backup recovery points.

# Arguments
- `backup_vault_name`: The unique name of an AWS Backup vault. Required.
- `recovery_point_arn`: An Amazon Resource Name (ARN) that uniquely identifies an AWS
  Backup recovery point. Required.

"""
disassociate_recovery_point(backupVaultName, recoveryPointArn; aws_config::AbstractAWSConfig=global_aws_config()) = backup("POST", "/backup-vaults/$(backupVaultName)/recovery-points/$(recoveryPointArn)/disassociate"; aws_config=aws_config)
disassociate_recovery_point(backupVaultName, recoveryPointArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = backup("POST", "/backup-vaults/$(backupVaultName)/recovery-points/$(recoveryPointArn)/disassociate", params; aws_config=aws_config)

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

Returns the backup plan that is specified by the plan ID as a backup template.

# Arguments
- `backup_plan_id`: Uniquely identifies a backup plan.

"""
export_backup_plan_template(backupPlanId; aws_config::AbstractAWSConfig=global_aws_config()) = backup("GET", "/backup/plans/$(backupPlanId)/toTemplate/"; aws_config=aws_config)
export_backup_plan_template(backupPlanId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = backup("GET", "/backup/plans/$(backupPlanId)/toTemplate/", params; aws_config=aws_config)

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

Returns BackupPlan details for the specified BackupPlanId. The details are the body of a
backup plan in JSON format, in addition to plan metadata.

# Arguments
- `backup_plan_id`: Uniquely identifies a backup plan.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"versionId"`: Unique, randomly generated, Unicode, UTF-8 encoded strings that are at
  most 1,024 bytes long. Version IDs cannot be edited.
"""
get_backup_plan(backupPlanId; aws_config::AbstractAWSConfig=global_aws_config()) = backup("GET", "/backup/plans/$(backupPlanId)/"; aws_config=aws_config)
get_backup_plan(backupPlanId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = backup("GET", "/backup/plans/$(backupPlanId)/", params; aws_config=aws_config)

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

Returns a valid JSON document specifying a backup plan or an error.

# Arguments
- `backup_plan_template_json`: A customer-supplied backup plan document in JSON format.

"""
get_backup_plan_from_json(BackupPlanTemplateJson; aws_config::AbstractAWSConfig=global_aws_config()) = backup("POST", "/backup/template/json/toPlan", Dict{String, Any}("BackupPlanTemplateJson"=>BackupPlanTemplateJson); aws_config=aws_config)
get_backup_plan_from_json(BackupPlanTemplateJson, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = backup("POST", "/backup/template/json/toPlan", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("BackupPlanTemplateJson"=>BackupPlanTemplateJson), params)); aws_config=aws_config)

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

Returns the template specified by its templateId as a backup plan.

# Arguments
- `template_id`: Uniquely identifies a stored backup plan template.

"""
get_backup_plan_from_template(templateId; aws_config::AbstractAWSConfig=global_aws_config()) = backup("GET", "/backup/template/plans/$(templateId)/toPlan"; aws_config=aws_config)
get_backup_plan_from_template(templateId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = backup("GET", "/backup/template/plans/$(templateId)/toPlan", params; aws_config=aws_config)

"""
    get_backup_selection(backup_plan_id, selection_id)
    get_backup_selection(backup_plan_id, selection_id, params::Dict{String,<:Any})

Returns selection metadata and a document in JSON format that specifies a list of resources
that are associated with a backup plan.

# Arguments
- `backup_plan_id`: Uniquely identifies a backup plan.
- `selection_id`: Uniquely identifies the body of a request to assign a set of resources to
  a backup plan.

"""
get_backup_selection(backupPlanId, selectionId; aws_config::AbstractAWSConfig=global_aws_config()) = backup("GET", "/backup/plans/$(backupPlanId)/selections/$(selectionId)"; aws_config=aws_config)
get_backup_selection(backupPlanId, selectionId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = backup("GET", "/backup/plans/$(backupPlanId)/selections/$(selectionId)", params; aws_config=aws_config)

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

Returns the access policy document that is associated with the named backup vault.

# Arguments
- `backup_vault_name`: The name of a logical container where backups are stored. Backup
  vaults are identified by names that are unique to the account used to create them and the
  AWS Region where they are created. They consist of lowercase letters, numbers, and hyphens.

"""
get_backup_vault_access_policy(backupVaultName; aws_config::AbstractAWSConfig=global_aws_config()) = backup("GET", "/backup-vaults/$(backupVaultName)/access-policy"; aws_config=aws_config)
get_backup_vault_access_policy(backupVaultName, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = backup("GET", "/backup-vaults/$(backupVaultName)/access-policy", params; aws_config=aws_config)

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

Returns event notifications for the specified backup vault.

# Arguments
- `backup_vault_name`: The name of a logical container where backups are stored. Backup
  vaults are identified by names that are unique to the account used to create them and the
  AWS Region where they are created. They consist of lowercase letters, numbers, and hyphens.

"""
get_backup_vault_notifications(backupVaultName; aws_config::AbstractAWSConfig=global_aws_config()) = backup("GET", "/backup-vaults/$(backupVaultName)/notification-configuration"; aws_config=aws_config)
get_backup_vault_notifications(backupVaultName, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = backup("GET", "/backup-vaults/$(backupVaultName)/notification-configuration", params; aws_config=aws_config)

"""
    get_recovery_point_restore_metadata(backup_vault_name, recovery_point_arn)
    get_recovery_point_restore_metadata(backup_vault_name, recovery_point_arn, params::Dict{String,<:Any})

Returns a set of metadata key-value pairs that were used to create the backup.

# Arguments
- `backup_vault_name`: The name of a logical container where backups are stored. Backup
  vaults are identified by names that are unique to the account used to create them and the
  AWS Region where they are created. They consist of lowercase letters, numbers, and hyphens.
- `recovery_point_arn`: An Amazon Resource Name (ARN) that uniquely identifies a recovery
  point; for example,
  arn:aws:backup:us-east-1:123456789012:recovery-point:1EB3B5E7-9EB0-435A-A80B-108B488B0D45.

"""
get_recovery_point_restore_metadata(backupVaultName, recoveryPointArn; aws_config::AbstractAWSConfig=global_aws_config()) = backup("GET", "/backup-vaults/$(backupVaultName)/recovery-points/$(recoveryPointArn)/restore-metadata"; aws_config=aws_config)
get_recovery_point_restore_metadata(backupVaultName, recoveryPointArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = backup("GET", "/backup-vaults/$(backupVaultName)/recovery-points/$(recoveryPointArn)/restore-metadata", params; aws_config=aws_config)

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

Returns the AWS resource types supported by AWS Backup.

"""
get_supported_resource_types(; aws_config::AbstractAWSConfig=global_aws_config()) = backup("GET", "/supported-resource-types"; aws_config=aws_config)
get_supported_resource_types(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = backup("GET", "/supported-resource-types", params; aws_config=aws_config)

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

Returns a list of existing backup jobs for an authenticated account for the last 30 days.
For a longer period of time, consider using these monitoring tools.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"accountId"`: The account ID to list the jobs from. Returns only backup jobs associated
  with the specified account ID. If used from an AWS Organizations management account,
  passing * returns all jobs across the organization.
- `"backupVaultName"`: Returns only backup jobs that will be stored in the specified backup
  vault. Backup vaults are identified by names that are unique to the account used to create
  them and the AWS Region where they are created. They consist of lowercase letters, numbers,
  and hyphens.
- `"createdAfter"`: Returns only backup jobs that were created after the specified date.
- `"createdBefore"`: Returns only backup jobs that were created before the specified date.
- `"maxResults"`: The maximum number of items to be returned.
- `"nextToken"`: The next item following a partial list of returned items. For example, if
  a request is made to return maxResults number of items, NextToken allows you to return more
  items in your list starting at the location pointed to by the next token.
- `"resourceArn"`: Returns only backup jobs that match the specified resource Amazon
  Resource Name (ARN).
- `"resourceType"`: Returns only backup jobs for the specified resources:    DynamoDB for
  Amazon DynamoDB    EBS for Amazon Elastic Block Store    EC2 for Amazon Elastic Compute
  Cloud    EFS for Amazon Elastic File System    RDS for Amazon Relational Database Service
   Aurora for Amazon Aurora    Storage Gateway for AWS Storage Gateway
- `"state"`: Returns only backup jobs that are in the specified state.
"""
list_backup_jobs(; aws_config::AbstractAWSConfig=global_aws_config()) = backup("GET", "/backup-jobs/"; aws_config=aws_config)
list_backup_jobs(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = backup("GET", "/backup-jobs/", params; aws_config=aws_config)

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

Returns metadata of your saved backup plan templates, including the template ID, name, and
the creation and deletion dates.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"maxResults"`: The maximum number of items to be returned.
- `"nextToken"`: The next item following a partial list of returned items. For example, if
  a request is made to return maxResults number of items, NextToken allows you to return more
  items in your list starting at the location pointed to by the next token.
"""
list_backup_plan_templates(; aws_config::AbstractAWSConfig=global_aws_config()) = backup("GET", "/backup/template/plans"; aws_config=aws_config)
list_backup_plan_templates(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = backup("GET", "/backup/template/plans", params; aws_config=aws_config)

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

Returns version metadata of your backup plans, including Amazon Resource Names (ARNs),
backup plan IDs, creation and deletion dates, plan names, and version IDs.

# Arguments
- `backup_plan_id`: Uniquely identifies a backup plan.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"maxResults"`: The maximum number of items to be returned.
- `"nextToken"`: The next item following a partial list of returned items. For example, if
  a request is made to return maxResults number of items, NextToken allows you to return more
  items in your list starting at the location pointed to by the next token.
"""
list_backup_plan_versions(backupPlanId; aws_config::AbstractAWSConfig=global_aws_config()) = backup("GET", "/backup/plans/$(backupPlanId)/versions/"; aws_config=aws_config)
list_backup_plan_versions(backupPlanId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = backup("GET", "/backup/plans/$(backupPlanId)/versions/", params; aws_config=aws_config)

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

Returns a list of existing backup plans for an authenticated account. The list is populated
only if the advanced option is set for the backup plan. The list contains information such
as Amazon Resource Names (ARNs), plan IDs, creation and deletion dates, version IDs, plan
names, and creator request IDs.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"includeDeleted"`: A Boolean value with a default value of FALSE that returns deleted
  backup plans when set to TRUE.
- `"maxResults"`: The maximum number of items to be returned.
- `"nextToken"`: The next item following a partial list of returned items. For example, if
  a request is made to return maxResults number of items, NextToken allows you to return more
  items in your list starting at the location pointed to by the next token.
"""
list_backup_plans(; aws_config::AbstractAWSConfig=global_aws_config()) = backup("GET", "/backup/plans/"; aws_config=aws_config)
list_backup_plans(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = backup("GET", "/backup/plans/", params; aws_config=aws_config)

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

Returns an array containing metadata of the resources associated with the target backup
plan.

# Arguments
- `backup_plan_id`: Uniquely identifies a backup plan.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"maxResults"`: The maximum number of items to be returned.
- `"nextToken"`: The next item following a partial list of returned items. For example, if
  a request is made to return maxResults number of items, NextToken allows you to return more
  items in your list starting at the location pointed to by the next token.
"""
list_backup_selections(backupPlanId; aws_config::AbstractAWSConfig=global_aws_config()) = backup("GET", "/backup/plans/$(backupPlanId)/selections/"; aws_config=aws_config)
list_backup_selections(backupPlanId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = backup("GET", "/backup/plans/$(backupPlanId)/selections/", params; aws_config=aws_config)

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

Returns a list of recovery point storage containers along with information about them.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"maxResults"`: The maximum number of items to be returned.
- `"nextToken"`: The next item following a partial list of returned items. For example, if
  a request is made to return maxResults number of items, NextToken allows you to return more
  items in your list starting at the location pointed to by the next token.
"""
list_backup_vaults(; aws_config::AbstractAWSConfig=global_aws_config()) = backup("GET", "/backup-vaults/"; aws_config=aws_config)
list_backup_vaults(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = backup("GET", "/backup-vaults/", params; aws_config=aws_config)

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

Returns metadata about your copy jobs.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"accountId"`: The account ID to list the jobs from. Returns only copy jobs associated
  with the specified account ID.
- `"createdAfter"`: Returns only copy jobs that were created after the specified date.
- `"createdBefore"`: Returns only copy jobs that were created before the specified date.
- `"destinationVaultArn"`: An Amazon Resource Name (ARN) that uniquely identifies a source
  backup vault to copy from; for example,
  arn:aws:backup:us-east-1:123456789012:vault:aBackupVault.
- `"maxResults"`: The maximum number of items to be returned.
- `"nextToken"`: The next item following a partial list of returned items. For example, if
  a request is made to return maxResults number of items, NextToken allows you to return more
  items in your list starting at the location pointed to by the next token.
- `"resourceArn"`: Returns only copy jobs that match the specified resource Amazon Resource
  Name (ARN).
- `"resourceType"`: Returns only backup jobs for the specified resources:    DynamoDB for
  Amazon DynamoDB    EBS for Amazon Elastic Block Store    EC2 for Amazon Elastic Compute
  Cloud    EFS for Amazon Elastic File System    RDS for Amazon Relational Database Service
   Aurora for Amazon Aurora    Storage Gateway for AWS Storage Gateway
- `"state"`: Returns only copy jobs that are in the specified state.
"""
list_copy_jobs(; aws_config::AbstractAWSConfig=global_aws_config()) = backup("GET", "/copy-jobs/"; aws_config=aws_config)
list_copy_jobs(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = backup("GET", "/copy-jobs/", params; aws_config=aws_config)

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

Returns an array of resources successfully backed up by AWS Backup, including the time the
resource was saved, an Amazon Resource Name (ARN) of the resource, and a resource type.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"maxResults"`: The maximum number of items to be returned.
- `"nextToken"`: The next item following a partial list of returned items. For example, if
  a request is made to return maxResults number of items, NextToken allows you to return more
  items in your list starting at the location pointed to by the next token.
"""
list_protected_resources(; aws_config::AbstractAWSConfig=global_aws_config()) = backup("GET", "/resources/"; aws_config=aws_config)
list_protected_resources(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = backup("GET", "/resources/", params; aws_config=aws_config)

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

Returns detailed information about the recovery points stored in a backup vault.

# Arguments
- `backup_vault_name`: The name of a logical container where backups are stored. Backup
  vaults are identified by names that are unique to the account used to create them and the
  AWS Region where they are created. They consist of lowercase letters, numbers, and hyphens.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"backupPlanId"`: Returns only recovery points that match the specified backup plan ID.
- `"createdAfter"`: Returns only recovery points that were created after the specified
  timestamp.
- `"createdBefore"`: Returns only recovery points that were created before the specified
  timestamp.
- `"maxResults"`: The maximum number of items to be returned.
- `"nextToken"`: The next item following a partial list of returned items. For example, if
  a request is made to return maxResults number of items, NextToken allows you to return more
  items in your list starting at the location pointed to by the next token.
- `"resourceArn"`: Returns only recovery points that match the specified resource Amazon
  Resource Name (ARN).
- `"resourceType"`: Returns only recovery points that match the specified resource type.
"""
list_recovery_points_by_backup_vault(backupVaultName; aws_config::AbstractAWSConfig=global_aws_config()) = backup("GET", "/backup-vaults/$(backupVaultName)/recovery-points/"; aws_config=aws_config)
list_recovery_points_by_backup_vault(backupVaultName, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = backup("GET", "/backup-vaults/$(backupVaultName)/recovery-points/", params; aws_config=aws_config)

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

Returns detailed information about recovery points of the type specified by a resource
Amazon Resource Name (ARN).

# Arguments
- `resource_arn`: An ARN that uniquely identifies a resource. The format of the ARN depends
  on the resource type.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"maxResults"`: The maximum number of items to be returned.
- `"nextToken"`: The next item following a partial list of returned items. For example, if
  a request is made to return maxResults number of items, NextToken allows you to return more
  items in your list starting at the location pointed to by the next token.
"""
list_recovery_points_by_resource(resourceArn; aws_config::AbstractAWSConfig=global_aws_config()) = backup("GET", "/resources/$(resourceArn)/recovery-points/"; aws_config=aws_config)
list_recovery_points_by_resource(resourceArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = backup("GET", "/resources/$(resourceArn)/recovery-points/", params; aws_config=aws_config)

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

Returns a list of jobs that AWS Backup initiated to restore a saved resource, including
metadata about the recovery process.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"accountId"`: The account ID to list the jobs from. Returns only restore jobs associated
  with the specified account ID.
- `"createdAfter"`: Returns only restore jobs that were created after the specified date.
- `"createdBefore"`: Returns only restore jobs that were created before the specified date.
- `"maxResults"`: The maximum number of items to be returned.
- `"nextToken"`: The next item following a partial list of returned items. For example, if
  a request is made to return maxResults number of items, NextToken allows you to return more
  items in your list starting at the location pointed to by the next token.
- `"status"`: Returns only restore jobs associated with the specified job status.
"""
list_restore_jobs(; aws_config::AbstractAWSConfig=global_aws_config()) = backup("GET", "/restore-jobs/"; aws_config=aws_config)
list_restore_jobs(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = backup("GET", "/restore-jobs/", params; aws_config=aws_config)

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

Returns a list of key-value pairs assigned to a target recovery point, backup plan, or
backup vault.   ListTags are currently only supported with Amazon EFS backups.

# Arguments
- `resource_arn`: An Amazon Resource Name (ARN) that uniquely identifies a resource. The
  format of the ARN depends on the type of resource. Valid targets for ListTags are recovery
  points, backup plans, and backup vaults.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"maxResults"`: The maximum number of items to be returned.
- `"nextToken"`: The next item following a partial list of returned items. For example, if
  a request is made to return maxResults number of items, NextToken allows you to return more
  items in your list starting at the location pointed to by the next token.
"""
list_tags(resourceArn; aws_config::AbstractAWSConfig=global_aws_config()) = backup("GET", "/tags/$(resourceArn)/"; aws_config=aws_config)
list_tags(resourceArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = backup("GET", "/tags/$(resourceArn)/", params; aws_config=aws_config)

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

Sets a resource-based policy that is used to manage access permissions on the target backup
vault. Requires a backup vault name and an access policy document in JSON format.

# Arguments
- `backup_vault_name`: The name of a logical container where backups are stored. Backup
  vaults are identified by names that are unique to the account used to create them and the
  AWS Region where they are created. They consist of lowercase letters, numbers, and hyphens.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Policy"`: The backup vault access policy document in JSON format.
"""
put_backup_vault_access_policy(backupVaultName; aws_config::AbstractAWSConfig=global_aws_config()) = backup("PUT", "/backup-vaults/$(backupVaultName)/access-policy"; aws_config=aws_config)
put_backup_vault_access_policy(backupVaultName, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = backup("PUT", "/backup-vaults/$(backupVaultName)/access-policy", params; aws_config=aws_config)

"""
    put_backup_vault_notifications(backup_vault_events, snstopic_arn, backup_vault_name)
    put_backup_vault_notifications(backup_vault_events, snstopic_arn, backup_vault_name, params::Dict{String,<:Any})

Turns on notifications on a backup vault for the specified topic and events.

# Arguments
- `backup_vault_events`: An array of events that indicate the status of jobs to back up
  resources to the backup vault.
- `snstopic_arn`: The Amazon Resource Name (ARN) that specifies the topic for a backup
  vault’s events; for example, arn:aws:sns:us-west-2:111122223333:MyVaultTopic.
- `backup_vault_name`: The name of a logical container where backups are stored. Backup
  vaults are identified by names that are unique to the account used to create them and the
  AWS Region where they are created. They consist of lowercase letters, numbers, and hyphens.

"""
put_backup_vault_notifications(BackupVaultEvents, SNSTopicArn, backupVaultName; aws_config::AbstractAWSConfig=global_aws_config()) = backup("PUT", "/backup-vaults/$(backupVaultName)/notification-configuration", Dict{String, Any}("BackupVaultEvents"=>BackupVaultEvents, "SNSTopicArn"=>SNSTopicArn); aws_config=aws_config)
put_backup_vault_notifications(BackupVaultEvents, SNSTopicArn, backupVaultName, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = backup("PUT", "/backup-vaults/$(backupVaultName)/notification-configuration", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("BackupVaultEvents"=>BackupVaultEvents, "SNSTopicArn"=>SNSTopicArn), params)); aws_config=aws_config)

"""
    start_backup_job(backup_vault_name, iam_role_arn, resource_arn)
    start_backup_job(backup_vault_name, iam_role_arn, resource_arn, params::Dict{String,<:Any})

Starts an on-demand backup job for the specified resource.

# Arguments
- `backup_vault_name`: The name of a logical container where backups are stored. Backup
  vaults are identified by names that are unique to the account used to create them and the
  AWS Region where they are created. They consist of lowercase letters, numbers, and hyphens.
- `iam_role_arn`: Specifies the IAM role ARN used to create the target recovery point; for
  example, arn:aws:iam::123456789012:role/S3Access.
- `resource_arn`: An Amazon Resource Name (ARN) that uniquely identifies a resource. The
  format of the ARN depends on the resource type.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"BackupOptions"`: Specifies the backup option for a selected resource. This option is
  only available for Windows VSS backup jobs. Valid values: Set to
  \"WindowsVSS”:“enabled\" to enable WindowsVSS backup option and create a VSS Windows
  backup. Set to “WindowsVSS”:”disabled” to create a regular backup. The WindowsVSS
  option is not enabled by default.
- `"CompleteWindowMinutes"`: A value in minutes during which a successfully started backup
  must complete, or else AWS Backup will cancel the job. This value is optional. This value
  begins counting down from when the backup was scheduled. It does not add additional time
  for StartWindowMinutes, or if the backup started later than scheduled.
- `"IdempotencyToken"`: A customer chosen string that can be used to distinguish between
  calls to StartBackupJob.
- `"Lifecycle"`: The lifecycle defines when a protected resource is transitioned to cold
  storage and when it expires. AWS Backup will transition and expire backups automatically
  according to the lifecycle that you define.  Backups transitioned to cold storage must be
  stored in cold storage for a minimum of 90 days. Therefore, the “expire after days”
  setting must be 90 days greater than the “transition to cold after days” setting. The
  “transition to cold after days” setting cannot be changed after a backup has been
  transitioned to cold.  Only Amazon EFS file system backups can be transitioned to cold
  storage.
- `"RecoveryPointTags"`: To help organize your resources, you can assign your own metadata
  to the resources that you create. Each tag is a key-value pair.
- `"StartWindowMinutes"`: A value in minutes after a backup is scheduled before a job will
  be canceled if it doesn't start successfully. This value is optional, and the default is 8
  hours.
"""
start_backup_job(BackupVaultName, IamRoleArn, ResourceArn; aws_config::AbstractAWSConfig=global_aws_config()) = backup("PUT", "/backup-jobs", Dict{String, Any}("BackupVaultName"=>BackupVaultName, "IamRoleArn"=>IamRoleArn, "ResourceArn"=>ResourceArn); aws_config=aws_config)
start_backup_job(BackupVaultName, IamRoleArn, ResourceArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = backup("PUT", "/backup-jobs", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("BackupVaultName"=>BackupVaultName, "IamRoleArn"=>IamRoleArn, "ResourceArn"=>ResourceArn), params)); aws_config=aws_config)

"""
    start_copy_job(destination_backup_vault_arn, iam_role_arn, recovery_point_arn, source_backup_vault_name)
    start_copy_job(destination_backup_vault_arn, iam_role_arn, recovery_point_arn, source_backup_vault_name, params::Dict{String,<:Any})

Starts a job to create a one-time copy of the specified resource. Does not support
continuous backups.

# Arguments
- `destination_backup_vault_arn`: An Amazon Resource Name (ARN) that uniquely identifies a
  destination backup vault to copy to; for example,
  arn:aws:backup:us-east-1:123456789012:vault:aBackupVault.
- `iam_role_arn`: Specifies the IAM role ARN used to copy the target recovery point; for
  example, arn:aws:iam::123456789012:role/S3Access.
- `recovery_point_arn`: An ARN that uniquely identifies a recovery point to use for the
  copy job; for example,
  arn:aws:backup:us-east-1:123456789012:recovery-point:1EB3B5E7-9EB0-435A-A80B-108B488B0D45.
- `source_backup_vault_name`: The name of a logical source container where backups are
  stored. Backup vaults are identified by names that are unique to the account used to create
  them and the AWS Region where they are created. They consist of lowercase letters, numbers,
  and hyphens.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"IdempotencyToken"`: A customer chosen string that can be used to distinguish between
  calls to StartCopyJob.
- `"Lifecycle"`:
"""
start_copy_job(DestinationBackupVaultArn, IamRoleArn, RecoveryPointArn, SourceBackupVaultName; aws_config::AbstractAWSConfig=global_aws_config()) = backup("PUT", "/copy-jobs", Dict{String, Any}("DestinationBackupVaultArn"=>DestinationBackupVaultArn, "IamRoleArn"=>IamRoleArn, "RecoveryPointArn"=>RecoveryPointArn, "SourceBackupVaultName"=>SourceBackupVaultName); aws_config=aws_config)
start_copy_job(DestinationBackupVaultArn, IamRoleArn, RecoveryPointArn, SourceBackupVaultName, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = backup("PUT", "/copy-jobs", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("DestinationBackupVaultArn"=>DestinationBackupVaultArn, "IamRoleArn"=>IamRoleArn, "RecoveryPointArn"=>RecoveryPointArn, "SourceBackupVaultName"=>SourceBackupVaultName), params)); aws_config=aws_config)

"""
    start_restore_job(iam_role_arn, metadata, recovery_point_arn)
    start_restore_job(iam_role_arn, metadata, recovery_point_arn, params::Dict{String,<:Any})

Recovers the saved resource identified by an Amazon Resource Name (ARN).

# Arguments
- `iam_role_arn`: The Amazon Resource Name (ARN) of the IAM role that AWS Backup uses to
  create the target recovery point; for example, arn:aws:iam::123456789012:role/S3Access.
- `metadata`: A set of metadata key-value pairs. Contains information, such as a resource
  name, required to restore a recovery point.  You can get configuration metadata about a
  resource at the time it was backed up by calling GetRecoveryPointRestoreMetadata. However,
  values in addition to those provided by GetRecoveryPointRestoreMetadata might be required
  to restore a resource. For example, you might need to provide a new resource name if the
  original already exists. You need to specify specific metadata to restore an Amazon Elastic
  File System (Amazon EFS) instance:    file-system-id: The ID of the Amazon EFS file system
  that is backed up by AWS Backup. Returned in GetRecoveryPointRestoreMetadata.    Encrypted:
  A Boolean value that, if true, specifies that the file system is encrypted. If KmsKeyId is
  specified, Encrypted must be set to true.    KmsKeyId: Specifies the AWS KMS key that is
  used to encrypt the restored file system. You can specify a key from another AWS account
  provided that key it is properly shared with your account via AWS KMS.    PerformanceMode:
  Specifies the throughput mode of the file system.    CreationToken: A user-supplied value
  that ensures the uniqueness (idempotency) of the request.    newFileSystem: A Boolean value
  that, if true, specifies that the recovery point is restored to a new Amazon EFS file
  system.    ItemsToRestore : An array of one to five strings where each string is a file
  path. Use ItemsToRestore to restore specific files or directories rather than the entire
  file system. This parameter is optional. For example,
  \"itemsToRestore\":\"[\"/my.test\"]\".
- `recovery_point_arn`: An ARN that uniquely identifies a recovery point; for example,
  arn:aws:backup:us-east-1:123456789012:recovery-point:1EB3B5E7-9EB0-435A-A80B-108B488B0D45.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"IdempotencyToken"`: A customer chosen string that can be used to distinguish between
  calls to StartRestoreJob.
- `"ResourceType"`: Starts a job to restore a recovery point for one of the following
  resources:    DynamoDB for Amazon DynamoDB    EBS for Amazon Elastic Block Store    EC2 for
  Amazon Elastic Compute Cloud    EFS for Amazon Elastic File System    RDS for Amazon
  Relational Database Service    Aurora for Amazon Aurora    Storage Gateway for AWS Storage
  Gateway
"""
start_restore_job(IamRoleArn, Metadata, RecoveryPointArn; aws_config::AbstractAWSConfig=global_aws_config()) = backup("PUT", "/restore-jobs", Dict{String, Any}("IamRoleArn"=>IamRoleArn, "Metadata"=>Metadata, "RecoveryPointArn"=>RecoveryPointArn); aws_config=aws_config)
start_restore_job(IamRoleArn, Metadata, RecoveryPointArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = backup("PUT", "/restore-jobs", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("IamRoleArn"=>IamRoleArn, "Metadata"=>Metadata, "RecoveryPointArn"=>RecoveryPointArn), params)); aws_config=aws_config)

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

Attempts to cancel a job to create a one-time backup of a resource.

# Arguments
- `backup_job_id`: Uniquely identifies a request to AWS Backup to back up a resource.

"""
stop_backup_job(backupJobId; aws_config::AbstractAWSConfig=global_aws_config()) = backup("POST", "/backup-jobs/$(backupJobId)"; aws_config=aws_config)
stop_backup_job(backupJobId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = backup("POST", "/backup-jobs/$(backupJobId)", params; aws_config=aws_config)

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

Assigns a set of key-value pairs to a recovery point, backup plan, or backup vault
identified by an Amazon Resource Name (ARN).

# Arguments
- `tags`: Key-value pairs that are used to help organize your resources. You can assign
  your own metadata to the resources you create.
- `resource_arn`: An ARN that uniquely identifies a resource. The format of the ARN depends
  on the type of the tagged resource.

"""
tag_resource(Tags, resourceArn; aws_config::AbstractAWSConfig=global_aws_config()) = backup("POST", "/tags/$(resourceArn)", Dict{String, Any}("Tags"=>Tags); aws_config=aws_config)
tag_resource(Tags, resourceArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = backup("POST", "/tags/$(resourceArn)", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Tags"=>Tags), params)); aws_config=aws_config)

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

Removes a set of key-value pairs from a recovery point, backup plan, or backup vault
identified by an Amazon Resource Name (ARN)

# Arguments
- `tag_key_list`: A list of keys to identify which key-value tags to remove from a resource.
- `resource_arn`: An ARN that uniquely identifies a resource. The format of the ARN depends
  on the type of the tagged resource.

"""
untag_resource(TagKeyList, resourceArn; aws_config::AbstractAWSConfig=global_aws_config()) = backup("POST", "/untag/$(resourceArn)", Dict{String, Any}("TagKeyList"=>TagKeyList); aws_config=aws_config)
untag_resource(TagKeyList, resourceArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = backup("POST", "/untag/$(resourceArn)", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("TagKeyList"=>TagKeyList), params)); aws_config=aws_config)

"""
    update_backup_plan(backup_plan, backup_plan_id)
    update_backup_plan(backup_plan, backup_plan_id, params::Dict{String,<:Any})

Updates an existing backup plan identified by its backupPlanId with the input document in
JSON format. The new version is uniquely identified by a VersionId.

# Arguments
- `backup_plan`: Specifies the body of a backup plan. Includes a BackupPlanName and one or
  more sets of Rules.
- `backup_plan_id`: Uniquely identifies a backup plan.

"""
update_backup_plan(BackupPlan, backupPlanId; aws_config::AbstractAWSConfig=global_aws_config()) = backup("POST", "/backup/plans/$(backupPlanId)", Dict{String, Any}("BackupPlan"=>BackupPlan); aws_config=aws_config)
update_backup_plan(BackupPlan, backupPlanId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = backup("POST", "/backup/plans/$(backupPlanId)", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("BackupPlan"=>BackupPlan), params)); aws_config=aws_config)

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

Updates the current global settings for the AWS account. Use the DescribeGlobalSettings API
to determine the current settings.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"GlobalSettings"`: A list of resources along with the opt-in preferences for the account.
"""
update_global_settings(; aws_config::AbstractAWSConfig=global_aws_config()) = backup("PUT", "/global-settings"; aws_config=aws_config)
update_global_settings(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = backup("PUT", "/global-settings", params; aws_config=aws_config)

"""
    update_recovery_point_lifecycle(backup_vault_name, recovery_point_arn)
    update_recovery_point_lifecycle(backup_vault_name, recovery_point_arn, params::Dict{String,<:Any})

Sets the transition lifecycle of a recovery point. The lifecycle defines when a protected
resource is transitioned to cold storage and when it expires. AWS Backup transitions and
expires backups automatically according to the lifecycle that you define. Backups
transitioned to cold storage must be stored in cold storage for a minimum of 90 days.
Therefore, the “expire after days” setting must be 90 days greater than the
“transition to cold after days” setting. The “transition to cold after days”
setting cannot be changed after a backup has been transitioned to cold. Only Amazon EFS
file system backups can be transitioned to cold storage. Does not support continuous
backups.

# Arguments
- `backup_vault_name`: The name of a logical container where backups are stored. Backup
  vaults are identified by names that are unique to the account used to create them and the
  AWS Region where they are created. They consist of lowercase letters, numbers, and hyphens.
- `recovery_point_arn`: An Amazon Resource Name (ARN) that uniquely identifies a recovery
  point; for example,
  arn:aws:backup:us-east-1:123456789012:recovery-point:1EB3B5E7-9EB0-435A-A80B-108B488B0D45.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Lifecycle"`: The lifecycle defines when a protected resource is transitioned to cold
  storage and when it expires. AWS Backup transitions and expires backups automatically
  according to the lifecycle that you define.  Backups transitioned to cold storage must be
  stored in cold storage for a minimum of 90 days. Therefore, the “expire after days”
  setting must be 90 days greater than the “transition to cold after days” setting. The
  “transition to cold after days” setting cannot be changed after a backup has been
  transitioned to cold.
"""
update_recovery_point_lifecycle(backupVaultName, recoveryPointArn; aws_config::AbstractAWSConfig=global_aws_config()) = backup("POST", "/backup-vaults/$(backupVaultName)/recovery-points/$(recoveryPointArn)"; aws_config=aws_config)
update_recovery_point_lifecycle(backupVaultName, recoveryPointArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = backup("POST", "/backup-vaults/$(backupVaultName)/recovery-points/$(recoveryPointArn)", params; aws_config=aws_config)

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

Updates the current service opt-in settings for the Region. If service-opt-in is enabled
for a service, AWS Backup tries to protect that service's resources in this Region, when
the resource is included in an on-demand backup or scheduled backup plan. Otherwise, AWS
Backup does not try to protect that service's resources in this Region. Use the
DescribeRegionSettings API to determine the resource types that are supported.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"ResourceTypeOptInPreference"`: Updates the list of services along with the opt-in
  preferences for the Region.
"""
update_region_settings(; aws_config::AbstractAWSConfig=global_aws_config()) = backup("PUT", "/account-settings"; aws_config=aws_config)
update_region_settings(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = backup("PUT", "/account-settings", params; aws_config=aws_config)


text:
function _budgeted_spanning_tree_compute_weight(
    i::MinimumBudget{SpanningTreeInstance{T, Maximise}, U},
    tree::Vector{Edge{T}},
) where {T, U}
    if length(tree) == 0
        return 0
    end
    return sum(i.weights[(e in keys(i.weights)) ? e : reverse(e)] for e in tree)
end

# Compute the value of a raw solution (array of edges). Different convention
# from the global `value` interface: return 0 for empty trees, not -Inf. Here,
# an empty tree is being built; there, an empty tree is an infeasible solution.

function _budgeted_spanning_tree_compute_value(
    i::SpanningTreeInstance{T},
    tree::Vector{Edge{T}},
) where {T}
    if length(tree) == 0
        return 0
    end
    return sum(i.rewards[(e in keys(i.rewards)) ? e : reverse(e)] for e in tree)
end

function _budgeted_spanning_tree_compute_value(
    i::MinimumBudget{SpanningTreeInstance{T, Maximise}, U},
    tree::Vector{Edge{T}},
) where {T, U}
    if length(tree) == 0
        return 0
    end
    return sum(
        i.instance.rewards[(e in keys(i.instance.rewards)) ? e : reverse(e)] for
        e in tree
    )
end

# How to ensure that adding an edge will not create loops?
# Partition the graph into components, based on the already added edges.
# All the nodes with the same component ID are reachable one from the
# other: adding an edge within that component would create a loop.
# Use -1 for nodes that are currently in no component.
mutable struct LoopDetector
    node_done::Vector{Int}
    next_value::Int

    function LoopDetector(n_vertices::Int)
        return new([-1 for _ in 1:n_vertices], 1)
    end
end

function visit_edge(ld::LoopDetector, e::Edge{Int})
    return visit_edge(ld, src(e), dst(e))
end

function visit_edge(ld::LoopDetector, s::Int, t::Int)
    if ld.node_done[s] == -1
        # Put the source (no currently assigned component) into the
        # same component as the destination.
        if ld.node_done[t] == -1
            ld.node_done[s] = ld.next_value
            ld.node_done[t] = ld.next_value
            ld.next_value += 1
        else
            ld.node_done[s] = ld.node_done[t]
        end
    elseif ld.node_done[t] == -1
        # Put the destination (no currently assigned component) into
        # the same component as the source.
        # No need to check if s already has a component, this is done in
        # the first case.
        ld.node_done[t] = ld.node_done[s]
    else
        # Merge components so that they have the lowest component ID of
        # the two components.
        if ld.node_done[t] < ld.node_done[s]
            ld.node_done[ld.node_done .== ld.node_done[s]] .= ld.node_done[t]
        else
            ld.node_done[ld.node_done .== ld.node_done[t]] .= ld.node_done[s]
        end
    end
    return
end

function edge_would_create_loop(ld::LoopDetector, e::Edge{Int})
    return edge_would_create_loop(ld, src(e), dst(e))
end

function edge_would_create_loop(ld::LoopDetector, s::Int, t::Int)
    # One of the ends of the edge has not yet been visited: impossible to have
    # a loop.
    if ld.node_done[s] == -1 || ld.node_done[t] == -1
        return false
    end

    # Both ends have been visited: are they in the same component?
    return ld.node_done[s] == ld.node_done[t]
end

function Base.copy!(dst::LoopDetector, src::LoopDetector)
    dst.node_done .= src.node_done
    dst.next_value = src.next_value
    return
end

ext: jl


text:
## Abstract Markov Chain
## =====================

typealias AbstractChain{T<:Domain} Vector{T}

"Get point samples out of a abstract Markov chain"
point_sample(chain::AbstractChain) = [rand(state) for state in chain]


text:
using DocumenterCitations
using Test

@testset "tex2unicode" begin
    @test DocumenterCitations.tex2unicode("-- ---") == "– —"
    @test DocumenterCitations.tex2unicode(
      raw"\`{o}\'{o}\^{o}\~{o}\={o}\u{o}\.{o}\\\"{o}\r{a}\H{o}\v{s}\d{u}\c{c}\k{a}\b{b}") == "òóôõōŏȯöåőšụçąḇ"
end


text:
export gmres

function gmres{T1,T2}(A::SparseMatrixCSC{T1,Int},b::Array{T2,1},restrt::Int; kwargs...)
	Ax = zeros(promote_type(T1,T2),size(A,1))
	return gmres(x -> A_mul_B!(1.0,A,x,0.0,Ax),b,restrt;kwargs...)
end

gmres(A,b::Vector,restrt;kwargs...) = gmres(x -> A*x ,b,restrt;kwargs...)

"""
x,flag,err,iter,resvec = gmres(A,b,restrt,tol=1e-2,maxIter=100,M=1,x=[],out=0)

Generalized Minimal residual ( GMRESm ) method with restarts applied to A*x = b.

Input:

  A       - function computing A*x
  b       - right hand side vector
  restrt  - number of iterations between restarts
  tol     - error tolerance
  maxIter - maximum number of iterations
  M       - preconditioner, function computing M\\x
  x       - starting guess
  out     - flag for output (0 : only errors, 1 : final status, 2: error at each iteration)

Output:

  x       - approximate solution
  flag    - exit flag (  0 : desired tolerance achieved,
                        -1 : maxIter reached without converging
                        -9 : right hand side was zero)
  err     - norm of relative residual, i.e., norm(A*x-b)/norm(b)
  iter    - number of iterations
  resvec  - norm of relative residual at each iteration
"""
function gmres(A::Function,b::Vector,restrt::Int; tol::Real=1e-2,maxIter::Int=100,M::Function=identity,x::Vector=[],out::Int=0,storeInterm::Bool=false)

    # initialization
    n  = length(b)
	if norm(b)==0; return zeros(eltype(b),n),-9,0.0,0,[0.0]; end
    if isempty(x)
        x = zeros(n)
        r = M(b)
    else
        r = M(b-A(x))
    end
	if storeInterm
        X = zeros(n,maxIter)	# allocate space for intermediates
    end

    bnrm2 = norm(b)
    if bnrm2 == 0.0; bnrm2 = 1.0; end

    err = norm( r ) / bnrm2
    if err < tol; return x, err; end

    restrt = min(restrt,n-1)
    V     = zeros(n,restrt+1)
    H     = zeros(restrt+1,restrt)
    cs    = zeros(restrt)
    sn    = zeros(restrt)
    e1    = zeros(n)
    e1[1] = 1.0

    if eltype(b) <: Complex || eltype(r) <: Complex || eltype(A) <: Complex
        e1 = complex(e1)
        b  = complex(b)
        r  = complex(r)
        x  = complex(x)
        V  = complex(V)
        H  = complex(H)
        cs = complex(cs)
        sn = complex(sn)
    end

    resvec = zeros((1+restrt)*maxIter)
    if out==2
    	println(@sprintf("=== gmres ===\n%4s\t%7s\n","iter","relres"))
    end

    iter = 0
    flag = -1
    cnt  = 1
    for iter = 1:maxIter
        V[:,1] = r / norm( r )
        s      = norm( r )*e1;

        if out==2;; print(@sprintf("%3d\t", iter));end

        for i = 1:restrt
            w = A(V[:,i])
            w = M(w)

            for k = 1:i # basis using Gram-Schmidt
                H[k,i] = dot(w,V[:,k])
                w     -= H[k,i]*V[:,k]
            end
            H[i+1,i] = norm( w )
            V[:,i+1] = w / H[i+1,i]

            for k = 1:i-1 # apply Givens rotation
                temp     =  cs[k]*H[k,i] + sn[k]*H[k+1,i]
                H[k+1,i] = -sn[k]*H[k,i] + cs[k]*H[k+1,i]
                H[k,i]   = temp
            end

            # Approximate residual norm
            cs[i],sn[i], = symOrtho( H[i,i], H[i+1,i] )
            s[i+1] = -sn[i]*s[i]
            s[i]   = cs[i]*s[i]
            H[i,i] = cs[i]*H[i,i] + sn[i]*H[i+1,i]
            H[i+1,i] = 0.0
            err  = abs(s[i+1]) / bnrm2

            if out==2; print(@sprintf("%1.1e ", err));end

            resvec[cnt] = err

            if err <= tol
                y  = H[1:i,1:i] \ s[1:i]
                x += V[:,1:i]*y
                if out==2; print("\n"); end
                flag = 0; break
            end
            cnt = cnt+1
        end
        if  err <= tol
            flag = 0
            break
        end
        y  = H[1:restrt,1:restrt]\s[1:restrt]
        x += V[:,1:restrt]*y
        if storeInterm; X[:,iter] = x; end

        r = b - A(x)
        r = M(r)

        s[restrt+1] = norm(r)
        resvec[cnt] = abs(s[restrt+1]) / bnrm2

        if out==2; print(@sprintf("\t %1.1e\n", err)); end
    end

    if out>=0
        if flag==-1
            println(@sprintf("gmres iterated maxIter (=%d) times without achieving the desired tolerance.",maxIter))
        elseif flag==0 && out>=1
            println(@sprintf("gmres achieved desired tolerance at iteration %d. Residual norm is %1.2e.",iter,resvec[cnt]))
        end
    end
    if storeInterm
	    return X[:,1:iter],flag,resvec[cnt],iter,resvec[1:cnt]
	else
	    return x,flag,resvec[cnt],iter,resvec[1:cnt]
	end
end


text:
push!(LOAD_PATH,"../src/")
import Pkg
cd("../")
include(joinpath(pwd(), "julenvnew.jl"))
Pkg.activate("GTheoryJulEnvNew")
testpath = joinpath(pwd(), "src")
push!(LOAD_PATH, testpath)
import DataStructures: OrderedDict
using Documenter, TestOptJulia, DocumenterTools
#DocumenterTools.genkeys(user="sambuddhac", repo="git@github.com:sambuddhac/TestOptJulia.jl.git")
DocMeta.setdocmeta!(TestOptJulia, :DocTestSetup, :(using TestOptJulia); recursive=true)
pages = OrderedDict(
    "Welcome Page" => "index.md",
)
makedocs(;
    modules=[TestOptJulia],
    authors="Sambuddha Chakrabarti",
    #repo="https://github.com/sambuddhac/TestOptJulia.jl/blob/{commit}{path}#{line}",
    sitename="TestOptJulia.jl",
    format=Documenter.HTML(;
        prettyurls=get(ENV, "CI", "false") == "true",
        canonical="https://sambuddhac.github.io/TestOptJulia.jl",
        assets=String[],
    ),
    pages=[
        "Home" => "index.md",
    ],
)

deploydocs(;
    repo = "github.com/sambuddhac/TestOptJulia.jl",
    target = "build",
    branch = "gh-pages",
    devbranch = "main",
    push_preview = true,
)

max_stars_repo_name: sambuddhac/TestOptJulia

max_issues_repo_name: sambuddhac/TestOptJulia

max_forks_repo_name: sambuddhac/TestOptJulia


text:
using MeshCat, MeshCatMechanisms, RigidBodyDynamics
using FileIO, MeshIO, GeometryTypes, CoordinateTransformations, Rotations

urdf_original = joinpath(pwd(),"src/models/kuka/kuka.urdf")
urdf_new = joinpath(pwd(),"src/models/kuka/temp/kuka.urdf")

function write_kuka_urdf()
    kuka_mesh_dir = joinpath(pwd(),"src/models/kuka/meshes")
    temp_dir = joinpath(pwd(),"src/models/kuka/temp")
    if !isdir(temp_dir)
        mkdir(temp_dir)
    end
    open(urdf_original,"r") do f
        open(urdf_new, "w") do fnew
            for ln in eachline(f)
                pre = findfirst("<mesh filename=",ln)
                post = findlast("/>",ln)
                if !(pre isa Nothing) && !(post isa Nothing)
                    inds = pre[end]+2:post[1]-2
                    pathstr = ln[inds]
                    file = splitdir(pathstr)[2]
                    ln = ln[1:pre[end]+1] * joinpath(kuka_mesh_dir,file) * ln[post[1]-1:end]
                end
                println(fnew,ln)
            end
        end
    end
end

write_kuka_urdf()

max_stars_repo_name: zacmanchester/DirectMotionPlanning

max_issues_repo_name: zacmanchester/DirectMotionPlanning

max_forks_repo_name: zacmanchester/DirectMotionPlanning


text: println(1 -2 3)

max_stars_repo_name: gabriel-doriath-dohler/pjulia

max_issues_repo_name: gabriel-doriath-dohler/pjulia

max_forks_repo_name: gabriel-doriath-dohler/pjulia


text:
# # Rising Thermal Bubble
#
# In this example, we demonstrate the usage of the `ClimateMachine`
# [AtmosModel](@ref AtmosModel-docs) machinery to solve the fluid
# dynamics of a thermal perturbation in a neutrally stratified background state
# defined by its uniform potential temperature. We solve a flow in a box configuration -
# this is representative of a large-eddy simulation. Several versions of the problem
# setup may be found in literature, but the general idea is to examine the
# vertical ascent of a thermal bubble (we can interpret these as simple
# representation of convective updrafts).
#
# ## Description of experiment
# 1) Dry Rising Bubble (circular potential temperature perturbation)
# 2) Boundaries
#    Top and Bottom boundaries:
#    - `Impenetrable(FreeSlip())` - Top and bottom: no momentum flux, no mass flux through
#      walls.
#    - `Impermeable()` - non-porous walls, i.e. no diffusive fluxes through
#       walls.
#    Lateral boundaries
#    - Laterally periodic
# 3) Domain - 2500m (horizontal) x 2500m (horizontal) x 2500m (vertical)
# 4) Resolution - 50m effective resolution
# 5) Total simulation time - 1000s
# 6) Mesh Aspect Ratio (Effective resolution) 1:1
# 7) Overrides defaults for
#    - CPU Initialisation
#    - Time integrator
#    - Sources
#    - Smagorinsky Coefficient

#md # !!! note
#md #     This experiment setup assumes that you have installed the
#md #     `ClimateMachine` according to the instructions on the landing page.
#md #     We assume the users' familiarity with the conservative form of the
#md #     equations of motion for a compressible fluid (see the
#md #     [AtmosModel](@ref AtmosModel-docs) page).
#md #
#md #     The following topics are covered in this example
#md #     - Package requirements
#md #     - Defining a `model` subtype for the set of conservation equations
#md #     - Defining the initial conditions
#md #     - Applying source terms
#md #     - Choosing a turbulence model
#md #     - Adding tracers to the model
#md #     - Choosing a time-integrator
#md #     - Choosing diagnostics (output) configurations
#md #
#md #     The following topics are not covered in this example
#md #     - Defining new boundary conditions
#md #     - Defining new turbulence models
#md #     - Building new time-integrators
#md #     - Adding diagnostic variables (beyond a standard pre-defined list of
#md #       variables)

# ## [Loading code](@id Loading-code-rtb)

# Before setting up our experiment, we recognize that we need to import some
# pre-defined functions from other packages. Julia allows us to use existing
# modules (variable workspaces), or write our own to do so.  Complete
# documentation for the Julia module system can be found
# [here](https://docs.julialang.org/en/v1/manual/modules/#).

# We need to use the `ClimateMachine` module! This imports all functions
# specific to atmospheric and ocean flow modeling.

using ClimateMachine
ClimateMachine.init()
using ClimateMachine.Atmos
using ClimateMachine.Orientations
using ClimateMachine.ConfigTypes
using ClimateMachine.Diagnostics
using ClimateMachine.GenericCallbacks
using ClimateMachine.ODESolvers
using ClimateMachine.TemperatureProfiles
using ClimateMachine.Thermodynamics
using ClimateMachine.TurbulenceClosures
using ClimateMachine.VariableTemplates

# In ClimateMachine we use `StaticArrays` for our variable arrays.
# We also use the `Test` package to help with unit tests and continuous
# integration systems to design sensible tests for our experiment to ensure new
# / modified blocks of code don't damage the fidelity of the physics. The test
# defined within this experiment is not a unit test for a specific
# subcomponent, but ensures time-integration of the defined problem conditions
# within a reasonable tolerance. Immediately useful macros and functions from
# this include `@test` and `@testset` which will allow us to define the testing
# parameter sets.
using StaticArrays
using Test
using CLIMAParameters
using CLIMAParameters.Atmos.SubgridScale: C_smag
using CLIMAParameters.Planet: R_d, cp_d, cv_d, MSLP, grav
struct EarthParameterSet <: AbstractEarthParameterSet end
const param_set = EarthParameterSet();

# ## [Initial Conditions](@id init-rtb)
# This example demonstrates the use of functions defined
# in the [`Thermodynamics`](@ref ClimateMachine.Thermodynamics) package to
# generate the appropriate initial state for our problem.

#md # !!! note
#md #     The following variables are assigned in the initial condition
#md #     - `state.ρ` = Scalar quantity for initial density profile
#md #     - `state.ρu`= 3-component vector for initial momentum profile
#md #     - `state.ρe`= Scalar quantity for initial total-energy profile
#md #       humidity
#md #     - `state.tracers.ρχ` = Vector of four tracers (here, for demonstration
#md #       only; we can interpret these as dye injections for visualization
#md #       purposes)
function init_risingbubble!(problem, bl, state, aux, (x, y, z), t)
    ## Problem float-type
    FT = eltype(state)

    ## Unpack constant parameters
    R_gas::FT = R_d(bl.param_set)
    c_p::FT = cp_d(bl.param_set)
    c_v::FT = cv_d(bl.param_set)
    p0::FT = MSLP(bl.param_set)
    _grav::FT = grav(bl.param_set)
    γ::FT = c_p / c_v

    ## Define bubble center and background potential temperature
    xc::FT = 5000
    yc::FT = 1000
    zc::FT = 2000
    r = sqrt((x - xc)^2 + (z - zc)^2)
    rc::FT = 2000
    θamplitude::FT = 2

    ## This is configured in the reference hydrostatic state
    θ_ref::FT = bl.ref_state.virtual_temperature_profile.T_surface

    ## Add the thermal perturbation:
    Δθ::FT = 0
    if r <= rc
        Δθ = θamplitude * (1.0 - r / rc)
    end

    ## Compute perturbed thermodynamic state:
    θ = θ_ref + Δθ                                      ## potential temperature
    π_exner = FT(1) - _grav / (c_p * θ) * z             ## exner pressure
    ρ = p0 / (R_gas * θ) * (π_exner)^(c_v / R_gas)      ## density
    T = θ * π_exner
    e_int = internal_energy(bl.param_set, T)
    ts = PhaseDry(bl.param_set, e_int, ρ)
    ρu = SVector(FT(0), FT(0), FT(0))                   ## momentum
    ## State (prognostic) variable assignment
    e_kin = FT(0)                                       ## kinetic energy
    e_pot = gravitational_potential(bl, aux)            ## potential energy
    ρe_tot = ρ * total_energy(e_kin, e_pot, ts)         ## total energy

    ρχ = FT(0)                                          ## tracer

    ## We inject tracers at the initial condition at some specified z coordinates
    if 500 < z <= 550
        ρχ += FT(0.05)
    end

    ## We want 4 tracers
    ntracers = 4

    ## Define 4 tracers, (arbitrary scaling for this demo problem)
    ρχ = SVector{ntracers, FT}(ρχ, ρχ / 2, ρχ / 3, ρχ / 4)

    ## Assign State Variables
    state.ρ = ρ
    state.ρu = ρu
    state.ρe = ρe_tot
    state.tracers.ρχ = ρχ
end

# ## [Model Configuration](@id config-helper)
# We define a configuration function to assist in prescribing the physical
# model. The purpose of this is to populate the
# `ClimateMachine.AtmosLESConfiguration` with arguments
# appropriate to the problem being considered.
function config_risingbubble(FT, N, resolution, xmax, ymax, zmax)

    ## Choose an Explicit Single-rate Solver from the existing [`ODESolvers`](@ref ClimateMachine.ODESolvers) options.
    ## Apply the outer constructor to define the `ode_solver`.
    ## The 1D-IMEX method is less appropriate for the problem given the current
    ## mesh aspect ratio (1:1).
    ode_solver = ClimateMachine.ExplicitSolverType(
        solver_method = LSRK144NiegemannDiehlBusch,
    )
    ## If the user prefers a multi-rate explicit time integrator,
    ## the ode_solver above can be replaced with
    ##
    ## `ode_solver = ClimateMachine.MultirateSolverType(
    ##    fast_model = AtmosAcousticGravityLinearModel,
    ##    slow_method = LSRK144NiegemannDiehlBusch,
    ##    fast_method = LSRK144NiegemannDiehlBusch,
    ##    timestep_ratio = 10,
    ## )`
    ## See [ODESolvers](@ref ODESolvers-docs) for all of the available solvers.

    ## Since we want four tracers, we specify this and include the appropriate
    ## diffusivity scaling coefficients (normally these would be physically
    ## informed but for this demonstration we use integers corresponding to the
    ## tracer index identifier)
    ntracers = 4
    δ_χ = SVector{ntracers, FT}(1, 2, 3, 4)
    ## To assemble `AtmosModel` with no tracers, set `tracers = NoTracers()`.

    ## The model coefficient for the turbulence closure is defined via the
    ## [CLIMAParameters
    ## package](https://CliMA.github.io/CLIMAParameters.jl/latest/) A reference
    ## state for the linearisation step is also defined.
    T_surface = FT(300)
    T_min_ref = FT(0)
    T_profile = DryAdiabaticProfile{FT}(param_set, T_surface, T_min_ref)
    ref_state = HydrostaticState(T_profile)

    ## Here we assemble the `AtmosModel`.
    _C_smag = FT(C_smag(param_set))
    model = AtmosModel{FT}(
        AtmosLESConfigType,                            ## Flow in a box, requires the AtmosLESConfigType
        param_set;                                     ## Parameter set corresponding to earth parameters
        init_state_prognostic = init_risingbubble!,    ## Apply the initial condition
        ref_state = ref_state,                         ## Reference state
        turbulence = SmagorinskyLilly(_C_smag),        ## Turbulence closure model
        moisture = DryModel(),                         ## Exclude moisture variables
        source = (Gravity(),),                         ## Gravity is the only source term here
        tracers = NTracers{ntracers, FT}(δ_χ),         ## Tracer model with diffusivity coefficients
    )

    ## Finally, we pass a `Problem Name` string, the mesh information, and the
    ## model type to  the [`AtmosLESConfiguration`] object.
    config = ClimateMachine.AtmosLESConfiguration(
        "DryRisingBubble",       ## Problem title [String]
        N,                       ## Polynomial order [Int]
        resolution,              ## (Δx, Δy, Δz) effective resolution [m]
        xmax,                    ## Domain maximum size [m]
        ymax,                    ## Domain maximum size [m]
        zmax,                    ## Domain maximum size [m]
        param_set,               ## Parameter set.
        init_risingbubble!,      ## Function specifying initial condition
        solver_type = ode_solver,## Time-integrator type
        model = model,           ## Model type
    )
    return config
end

#md # !!! note
#md #     `Keywords` are used to specify some arguments (see appropriate source
#md #     files).

# ## [Diagnostics](@id config_diagnostics)
# Here we define the diagnostic configuration specific to this problem.
function config_diagnostics(driver_config)
    interval = "10000steps"
    dgngrp = setup_atmos_default_diagnostics(
        AtmosLESConfigType(),
        interval,
        driver_config.name,
    )
    return ClimateMachine.DiagnosticsConfiguration([dgngrp])
end

function main()
    ## These are essentially arguments passed to the
    ## [`config_risingbubble`](@ref config-helper) function.  For type
    ## consistency we explicitly define the problem floating-precision.
    FT = Float64
    ## We need to specify the polynomial order for the DG discretization,
    ## effective resolution, simulation end-time, the domain bounds, and the
    ## courant-number for the time-integrator. Note how the time-integration
    ## components `solver_config` are distinct from the spatial / model
    ## components in `driver_config`. `init_on_cpu` is a helper keyword argument
    ## that forces problem initialization on CPU (thereby allowing the use of
    ## random seeds, spline interpolants and other special functions at the
    ## initialization step.)
    N = 4
    Δh = FT(125)
    Δv = FT(125)
    resolution = (Δh, Δh, Δv)
    xmax = FT(10000)
    ymax = FT(500)
    zmax = FT(10000)
    t0 = FT(0)
    timeend = FT(100)
    ## For full simulation set `timeend = 1000`

    ## Use up to 1.7 if ode_solver is the single rate LSRK144.
    CFL = FT(1.7)

    ## Assign configurations so they can be passed to the `invoke!` function
    driver_config = config_risingbubble(FT, N, resolution, xmax, ymax, zmax)
    solver_config = ClimateMachine.SolverConfiguration(
        t0,
        timeend,
        driver_config,
        init_on_cpu = true,
        Courant_number = CFL,
    )
    dgn_config = config_diagnostics(driver_config)

    ## Invoke solver (calls `solve!` function for time-integrator), pass the driver,
    ## solver and diagnostic config information.
    result = ClimateMachine.invoke!(
        solver_config;
        diagnostics_config = dgn_config,
        user_callbacks = (),
        check_euclidean_distance = true,
    )

    ## Check that the solution norm is reasonable.
    @test isapprox(result, FT(1); atol = 1.5e-3)
end

# The experiment definition is now complete. Time to run it.

# ## Running the file
# `julia --project tutorials/Atmos/risingbubble.jl` will run the
# experiment from the main ClimateMachine.jl directory, with diagnostics output
# at the intervals specified in [`config_diagnostics`](@ref
# config_diagnostics).  You can also prescribe command line arguments for
# simulation update and output specifications.  For
# rapid turnaround, we recommend that you run this experiment on a GPU.

# VTK output can be controlled via command line by
# setting `parse_clargs=true` in the `ClimateMachine.init`
# arguments, and then using `--vtk=<interval>`.

# ## [Output Visualisation](@id output-viz)
# See the `ClimateMachine` API interface documentation
# for generating output.
#
#
# - [VisIt](https://wci.llnl.gov/simulation/computer-codes/visit/)
# - [Paraview](https://wci.llnl.gov/simulation/computer-codes/visit/)
# are two commonly used programs for `.vtu` files.
#
# For NetCDF or JLD2 diagnostics you may use any of the following tools:
# Julia's
# [`NCDatasets`](https://github.com/Alexander-Barth/NCDatasets.jl) and
# [`JLD2`](https://github.com/JuliaIO/JLD2.jl) packages with a suitable
#
# or the known and quick NCDF visualization tool:
# [`ncview`](http://meteora.ucsd.edu/~pierce/ncview_home_page.html)
# plotting program.

main()

max_stars_repo_name: mwarusz/CLIMA

max_issues_repo_name: mwarusz/CLIMA

max_forks_repo_name: mwarusz/CLIMA


text:
using Distributions

# Gamma distribution
k = 3
θ = 2
ρ(x) = x > 0 ? 1/(2*θ^k)*x^(k-1)*exp(-x/θ) : 0

#=
Implementation of random walk sampler Metropolis-Hastings.
Inputs:
- n: The number of states to return
- b: The standard deviation of the normal distribution used in the proposal
     distribution
Outputs:
- Returns an array of length n denoting states S_i in Metropolis-Hastings alg.
=#
function metropolis_hastings(n, b)

    # Samples
    samples = zeros(n)
    samples[1] = rand()

    # Conditional Q distribution
    d = Normal(0,b)

    acceptances = 0

    for i=2:n
        # Propose Y
        ξ = rand(d)
        Y = samples[i-1] + ξ

        # Acceptance probability
        α = min(1, ρ(Y)/ρ(samples[i-1]))

        # Next state
        if rand() < α
            samples[i] = Y
            acceptances += 1
        else
            samples[i] = samples[i-1]
        end
    end

    println(acceptances)

    return samples
end

# Obtain 1000 samples with b = 2
S = metropolis_hastings(1000,16)
density_values = [ρ(x) for x = 0:0.01:30]

histogram(S, normalize = true, legend = false,
    bg = RGB(247/255, 236/255, 226/255), fill = RGB(0,0,20/255))
hist = plot!(0:0.01:30, density_values, lc = :lightgreen)

mixing = plot(S, legend = false, bg = RGB(247/255, 236/255, 226/255), lc = RGB(0,0,20/255),xlabel = "k")

plot(mixing, hist)

savefig("../images/mh_sampling_1_2.svg")

max_stars_repo_name: seanrattana/courses

max_issues_repo_name: seanrattana/courses

max_forks_repo_name: seanrattana/courses


text:
using BenchmarkTools

# part 1: find number of IDs that contain exactly 2 of any letter and number
# with exactly 3
input_strings = readlines("02.input")
input = collect.(input_strings)

function count_map(elems::AbstractArray{T}) where T
    counts = Dict{T,Int}()
    for x in elems
        counts[x] = get(counts, x, 0) + 1
    end
    counts
end

n2and3 = reduce((x,y)->x.+y, (x -> (2∈x, 3∈x)).(values.(count_map.(input))))
checksum = prod(n2and3)

# part 2: find two IDs that differ in exactly one position.  make a short
# circuiting distance function that returns true if total edit distance is less
# than n.

function edit_dist_lt_n(x, y, n::Int=2)
    edits = 0
    @inbounds for i in eachindex(x,y)
        edits += x[i] != y[i]
        edits >= n && return false
    end
    return true
end

function edit_dist_lt_n_zip(x, y, n::Int=2)
    edits = 0
    for (xi,yi) in zip(x,y)
        edits += xi != yi
        edits >= n && return false
    end
    return true
end

# they're pretty close (indexing is faster if you add inbounds)
@btime edit_dist_lt_n_zip($input[1], $input[2], 2)
@btime edit_dist_lt_n($input[1], $input[2], 2)

function star2(input; distf::Function=edit_dist_lt_n_zip)
    input = copy(input)
    while !isempty(input)
        x = pop!(input)
        for y in input
            if distf(x, y, 2)
                return x,y
            end
        end
    end
    return nothing
end

# ...but working direclty with strings is way more expensive:
@btime star2(input_strings)               # 571 μs
@btime star2(input)                       # 140 μs
@btime star2(input, distf=edit_dist_lt_n) # 134 μs

matches = star2(input)
join(matches[1][matches[1] .== matches[2]])


text:
export rim
"""
`h, seed = rim([s,] xs, xr, L, T60, Nt, Fs)`

Randomized Image Source Method

#### Arguments:

* `s`   : (Optional) Source signals
* `xs`  : Source position in meters (must be a Tuple)
* `xr`  : Microphone position in meters (must be a `Tuple` or a `Vector{Tuple}` for mic array)
* `Nt`  : Time samples
* `L`   : 3 element `Tuple` containing dimensions of the room
* `beta`/`T60` : 6 element `Tuple` containing reflection coefficients of walls/reverberation time
* `Nt`  : length of the RIR
* `Fs`  : sampling frequency

#### Keyword Arguments:

* `c = 343`    : speed of sound
* `Rd = 1e-2`  : random displacement (in meters)
* `N = (0,0,0)`: 3 element `Tuple` representing order of reflection when `N == (0;0;0)` full order is computed.
* `Tw = 20`    : taps of fractional delay filter
* `Fc = 0.9`   : cut-off frequency of fractional delay filter

#### Outputs:
* `h`: vector or matrix where each column is an impulse response or the sound pressure if `s` was specified corresponding to the microphone positions `xr`
* `seed`: randomization seed to preserve spatial properties when other RIR at different position are needed
"""
function rim(xs::NTuple{3,Number},
             xr::NTuple{3,Number},
             L::NTuple{3,Number},
             beta::NTuple{6,Number},
             Nt::Integer,
             Fs::Number;
             c::Number = 343,
             Rd::Number = 1e-2,
             seed::Integer = 1234,
             N::NTuple{3,Integer} = (0,0,0),
             Tw::Integer = 20,
             Fc::Number = 0.9)

  if any( xs .> (L[1], L[2], L[3]) ) || any( xs .<  (0;0;0) )
    error("xs outside domain")
  end
  if any( xr .> (L[1], L[2], L[3]) ) || any( xr .< (0, 0 , 0) )
    error("xr outside domain")
  end
  if any(N .< 0 )
    error("N should be positive")
  end

  Fsc = Fs/c
  L  = L.*(Fsc*2)  #convert dimensions to indices
  xr = xr.*Fsc
  xs = xs.*Fsc
  Rd = Rd *Fsc

  h = zeros(Nt)            # initialize output
  beta = convert.(eltype(h), beta)
  pos_is = zeros(3)
  if( N == (0,0,0) )
    N = floor.(Int,Nt./L).+1  # compute full order
  end
  Random.seed!(seed)
  if Tw == 0
    run_rim!(h, xs, xr, pos_is, L, beta, N, Rd, Nt)
  else # with fractional delay
    run_rim!(h, xs, xr, pos_is, L, beta, N, Rd, Fc, Tw, Nt)
  end
  h .*= Fsc
  return h, seed
end

# with fractional delay
function run_rim!(h::AbstractVector{T},
                  xs::X, xr::X, pos_is::AbstractVector{T}, L::X,
                  beta::NTuple{6,T},
                  N::NN,
                  Rd::T, Fc::T, Tw::I, Nt::I
                 ) where {T <: AbstractFloat, I<:Integer,
                          X <: NTuple{3,T}, NN <:NTuple{3,I}}
  beta_pow = zeros(I,6)
  for u = 0:1, v = 0:1, w = 0:1
    for l = -N[1]:N[1], m = -N[2]:N[2], n = -N[3]:N[3]
      if (l ==0 && m == 0 && n == 0 && u == 0 && v == 0 && w == 0)
        # we have direct path, so
        # no displacement is added
        RD = 0.0
      else
        RD = Rd
      end
      # compute distance
      pos_is[1] = xs[1]-2*u*xs[1]+l*L[1] + RD*(2*rand()-1)
      pos_is[2] = xs[2]-2*v*xs[2]+m*L[2] + RD*(2*rand()-1)
      pos_is[3] = xs[3]-2*w*xs[3]+n*L[3] + RD*(2*rand()-1)
      # position of image source

      d = norm( pos_is .-xr )+1
      # instead of moving the source on a line
      # as in the paper, we are moving the source
      # in a cube with 2*Rd edge
      id = round(Int64,d)
      if (id > Nt || id < 1)
        #if index not exceed length h
        continue
      end

      A = get_amplitude!(beta, beta_pow, l,m,n, u,v,w, d)
      add_delay!(h, d, A, Tw, Fc, Nt)
    end
  end
  return h
end

# fractional delay
function add_delay!(h::Array{T}, d::T, A::T, Tw::I, Fc::T, Nt::I) where {
                                                                  T <: AbstractFloat,
                                                                  I <: Integer
                                                                 }
  # create time window
  indx = max(ceil(I,d.-Tw/2),1):min(floor(I,d.+Tw/2),Nt)
  # compute filtered impulse
  A2 = A/2
  @inbounds @simd for i in indx
    h[i] += A2 *( 1.0 + cos(2*π*(i-d)/Tw) )*sinc(Fc*(i-d))
  end
  return h
end

function get_amplitude!(beta::NTuple{6,T},
                        beta_pow::Array{I},
                        l::I,m::I,n::I,
                        u::I,v::I,w::I,
                        d::T)  where {I <: Integer,
                                      T <: AbstractFloat}
  beta_pow[1] = abs(l-u)
  beta_pow[2] = abs(l)
  beta_pow[3] = abs(m-v)
  beta_pow[4] = abs(m)
  beta_pow[5] = abs(n-w)
  beta_pow[6] = abs(n)
  A = one(T)
  for i in eachindex(beta)
    A *= beta[i]^beta_pow[i]
  end
  A /= (4*π*(d-1))
  return A
end

# without fractional delay
function run_rim!(h::AbstractVector{T},
                  xs::X, xr::X, pos_is::AbstractVector{T}, L::X,
                  beta::NTuple{6,T},
                  N::NN,
                  Rd::T, Nt::I
                 ) where {T <: AbstractFloat, I<:Integer,
                          X <: NTuple{3,T}, NN <:NTuple{3,I}}
  beta_pow = zeros(I,6)
  for u = 0:1, v = 0:1, w = 0:1
    for l = -N[1]:N[1], m = -N[2]:N[2], n = -N[3]:N[3]
      if (l ==0 && m == 0 && n == 0 && u == 0 && v == 0 && w == 0)
        # we have direct path, so
        # no displacement is added
        RD = 0.0
      else
        RD = Rd
      end
      # compute distance
      pos_is[1] = xs[1]-2*u*xs[1]+l*L[1] + RD*(2*rand()-1)
      pos_is[2] = xs[2]-2*v*xs[2]+m*L[2] + RD*(2*rand()-1)
      pos_is[3] = xs[3]-2*w*xs[3]+n*L[3] + RD*(2*rand()-1)
      # position of image source

      d = norm(pos_is .-xr)+1
      # instead of moving the source on a line
      # as in the paper, we are moving the source
      # in a cube with 2*Rd edge
      id = round(Int64,d)
      if (id > Nt || id < 1)
        #if index not exceed length h
        continue
      end

      A = get_amplitude!(beta, beta_pow, l,m,n, u,v,w, d)
      h[id] += A
    end
  end
  return h

end

# with T60
function rim(xs::Union{ NTuple{3,Number}, Vector{NTuple{3, Number}} },
             xr::Union{ NTuple{3,Number}, Vector{NTuple{3, Number}} },
             L::NTuple{3,Number},
             T60::Number, args...;
             c::Number = 343,
             kwargs...)

    beta = RIM.revTime2beta(L, T60, c)
    return rim(xs, xr, L, beta, args...; kwargs...)

end

# multiple mics
function rim(xs::NTuple{3,Number},
             xr::Vector, args...;
             kwargs...)
    h = ()
    seed = 1234
    for xi in xr
        hi, seed = rim(xs, xi, args...; kwargs...)
        h = (h..., hi)
    end
    return hcat(h...), seed

end

# with source signal
function rim(s::AbstractVector,
             args...;
             kwargs...)
    h, seed = rim(args...; kwargs...)
    P = hcat([conv(s,h[:,i]) for i = 1:size(h,2)]...)
    return P, seed

end


text:
using CompScienceMeshes
using BEAST

using Test

m1 = meshrectangle(1.0, 1.0, 0.5)
m2 = CompScienceMeshes.translate!(meshrectangle(1.0, 1.0, 0.5), point(0,0,1))
m3 = CompScienceMeshes.translate!(meshrectangle(1.0, 1.0, 0.5), point(0,0,2))

X1 = raviartthomas(m1)
X2 = raviartthomas(m2)
X3 = raviartthomas(m3)

X = X1 × X2 × X3

n1 = numfunctions(X1)
n2 = numfunctions(X2)
n3 = numfunctions(X3)

@test numfunctions(X) == n1 + n2 + n3
nt = numfunctions(X)

T = MWSingleLayer3D(1.0)
t = assemble(T, X, X)

@test size(t) == (nt,nt)


text:
module TestSimulateExtinctions
  using Test
  using BioEnergeticFoodWebs

  # basic model
  A = [1 0 0; 0 1 0; 0 0 0]
  p = model_parameters(A)
  b = rand(3)

  #default extinction threshold
  default_extinction_threshold = 1e-6
  tolerated_values = default_extinction_threshold * 0.1
  s = simulate(p, b)
  @test sum((s[:B][:,2] .< tolerated_values) .& (s[:B][:,2] .> 0.0)) == 0
  @test s[:p][:extinctions] == [1, 2]
  @test length(s[:p][:extinctionstime]) == 2

  #passed extinction threshold
  passed_extinction_threshold = 100*eps()
  tolerated_values = passed_extinction_threshold * 0.1
  s = simulate(p, b, extinction_threshold = passed_extinction_threshold)
  @test sum((s[:B] .< tolerated_values) .& (s[:B] .> 0.0)) == 0
  @test s[:p][:extinctions] == [1, 2]
  @test length(s[:p][:extinctionstime]) == 2

  #with nutrients
  p_nutrients = model_parameters(A, productivity = :nutrients)
  default_extinction_threshold = 1e-6
  tolerated_values = default_extinction_threshold * 0.1
  s_nutrients = simulate(p_nutrients, b)
  @test sum((s_nutrients[:B][:,2] .< tolerated_values) .& (s_nutrients[:B][:,2] .> 0.0)) == 0

  #nutrients and passed extinction threshold
  passed_extinction_threshold = 100*eps()
  tolerated_values = passed_extinction_threshold * 0.1
  s_nutrients = simulate(p_nutrients, b, extinction_threshold = passed_extinction_threshold)
  @test sum((s_nutrients[:B][:,2] .< tolerated_values) .& (s_nutrients[:B][:,2] .> 0.0)) == 0

end

max_stars_repo_name: SimmonsBI/BioEnergeticFoodWebs

max_issues_repo_name: SimmonsBI/BioEnergeticFoodWebs

max_forks_repo_name: SimmonsBI/BioEnergeticFoodWebs