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

"""
    create_access_point(client_token, file_system_id)
    create_access_point(client_token, file_system_id, params::Dict{String,<:Any})

Creates an EFS access point. An access point is an application-specific view into an EFS
file system that applies an operating system user and group, and a file system path, to any
file system request made through the access point. The operating system user and group
override any identity information provided by the NFS client. The file system path is
exposed as the access point's root directory. Applications using the access point can only
access data in its own directory and below. To learn more, see Mounting a file system using
EFS access points. This operation requires permissions for the
elasticfilesystem:CreateAccessPoint action.

# Arguments
- `client_token`: A string of up to 64 ASCII characters that Amazon EFS uses to ensure
  idempotent creation.
- `file_system_id`: The ID of the EFS file system that the access point provides access to.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"PosixUser"`: The operating system user and group applied to all file system requests
  made using the access point.
- `"RootDirectory"`: Specifies the directory on the Amazon EFS file system that the access
  point exposes as the root directory of your file system to NFS clients using the access
  point. The clients using the access point can only access the root directory and below. If
  the RootDirectory > Path specified does not exist, EFS creates it and applies the
  CreationInfo settings when a client connects to an access point. When specifying a
  RootDirectory, you need to provide the Path, and the CreationInfo. Amazon EFS creates a
  root directory only if you have provided the CreationInfo: OwnUid, OwnGID, and permissions
  for the directory. If you do not provide this information, Amazon EFS does not create the
  root directory. If the root directory does not exist, attempts to mount using the access
  point will fail.
- `"Tags"`: Creates tags associated with the access point. Each tag is a key-value pair.
"""
create_access_point(ClientToken, FileSystemId; aws_config::AbstractAWSConfig=global_aws_config()) = efs("POST", "/2015-02-01/access-points", Dict{String, Any}("ClientToken"=>ClientToken, "FileSystemId"=>FileSystemId); aws_config=aws_config)
create_access_point(ClientToken, FileSystemId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = efs("POST", "/2015-02-01/access-points", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ClientToken"=>ClientToken, "FileSystemId"=>FileSystemId), params)); aws_config=aws_config)

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

Creates a new, empty file system. The operation requires a creation token in the request
that Amazon EFS uses to ensure idempotent creation (calling the operation with same
creation token has no effect). If a file system does not currently exist that is owned by
the caller's AWS account with the specified creation token, this operation does the
following:   Creates a new, empty file system. The file system will have an Amazon EFS
assigned ID, and an initial lifecycle state creating.   Returns with the description of the
created file system.   Otherwise, this operation returns a FileSystemAlreadyExists error
with the ID of the existing file system.  For basic use cases, you can use a randomly
generated UUID for the creation token.   The idempotent operation allows you to retry a
CreateFileSystem call without risk of creating an extra file system. This can happen when
an initial call fails in a way that leaves it uncertain whether or not a file system was
actually created. An example might be that a transport level timeout occurred or your
connection was reset. As long as you use the same creation token, if the initial call had
succeeded in creating a file system, the client can learn of its existence from the
FileSystemAlreadyExists error. For more information, see Creating a file system in the
Amazon EFS User Guide.  The CreateFileSystem call returns while the file system's lifecycle
state is still creating. You can check the file system creation status by calling the
DescribeFileSystems operation, which among other things returns the file system state.
This operation accepts an optional PerformanceMode parameter that you choose for your file
system. We recommend generalPurpose performance mode for most file systems. File systems
using the maxIO performance mode can scale to higher levels of aggregate throughput and
operations per second with a tradeoff of slightly higher latencies for most file
operations. The performance mode can't be changed after the file system has been created.
For more information, see Amazon EFS performance modes. You can set the throughput mode for
the file system using the ThroughputMode parameter. After the file system is fully created,
Amazon EFS sets its lifecycle state to available, at which point you can create one or more
mount targets for the file system in your VPC. For more information, see CreateMountTarget.
You mount your Amazon EFS file system on an EC2 instances in your VPC by using the mount
target. For more information, see Amazon EFS: How it Works.   This operation requires
permissions for the elasticfilesystem:CreateFileSystem action.

# Arguments
- `creation_token`: A string of up to 64 ASCII characters. Amazon EFS uses this to ensure
  idempotent creation.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"AvailabilityZoneName"`: Used to create a file system that uses One Zone storage
  classes. It specifies the AWS Availability Zone in which to create the file system. Use the
  format us-east-1a to specify the Availability Zone. For more information about One Zone
  storage classes, see Using EFS storage classes in the Amazon EFS User Guide.  One Zone
  storage classes are not available in all Availability Zones in AWS Regions where Amazon EFS
  is available.
- `"Backup"`: Specifies whether automatic backups are enabled on the file system that you
  are creating. Set the value to true to enable automatic backups. If you are creating a file
  system that uses One Zone storage classes, automatic backups are enabled by default. For
  more information, see Automatic backups in the Amazon EFS User Guide. Default is false.
  However, if you specify an AvailabilityZoneName, the default is true.  AWS Backup is not
  available in all AWS Regions where Amazon EFS is available.
- `"Encrypted"`: A Boolean value that, if true, creates an encrypted file system. When
  creating an encrypted file system, you have the option of specifying
  CreateFileSystemRequestKmsKeyId for an existing AWS Key Management Service (AWS KMS)
  customer master key (CMK). If you don't specify a CMK, then the default CMK for Amazon EFS,
  /aws/elasticfilesystem, is used to protect the encrypted file system.
- `"KmsKeyId"`: The ID of the AWS KMS CMK that you want to use to protect the encrypted
  file system. This parameter is only required if you want to use a non-default KMS key. If
  this parameter is not specified, the default CMK for Amazon EFS is used. This ID can be in
  one of the following formats:   Key ID - A unique identifier of the key, for example
  1234abcd-12ab-34cd-56ef-1234567890ab.   ARN - An Amazon Resource Name (ARN) for the key,
  for example arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab.
  Key alias - A previously created display name for a key, for example alias/projectKey1.
  Key alias ARN - An ARN for a key alias, for example
  arn:aws:kms:us-west-2:444455556666:alias/projectKey1.   If KmsKeyId is specified, the
  CreateFileSystemRequestEncrypted parameter must be set to true.  EFS accepts only symmetric
  KMS keys. You cannot use asymmetric KMS keys with EFS file systems.
- `"PerformanceMode"`: The performance mode of the file system. We recommend generalPurpose
  performance mode for most file systems. File systems using the maxIO performance mode can
  scale to higher levels of aggregate throughput and operations per second with a tradeoff of
  slightly higher latencies for most file operations. The performance mode can't be changed
  after the file system has been created.  The maxIO mode is not supported on file systems
  using One Zone storage classes.
- `"ProvisionedThroughputInMibps"`: The throughput, measured in MiB/s, that you want to
  provision for a file system that you're creating. Valid values are 1-1024. Required if
  ThroughputMode is set to provisioned. The upper limit for throughput is 1024 MiB/s. To
  increase this limit, contact AWS Support. For more information, see Amazon EFS quotas that
  you can increase in the Amazon EFS User Guide.
- `"Tags"`: A value that specifies to create one or more tags associated with the file
  system. Each tag is a user-defined key-value pair. Name your file system on creation by
  including a \"Key\":\"Name\",\"Value\":\"{value}\" key-value pair.
- `"ThroughputMode"`: Specifies the throughput mode for the file system, either bursting or
  provisioned. If you set ThroughputMode to provisioned, you must also set a value for
  ProvisionedThroughputInMibps. After you create the file system, you can decrease your file
  system's throughput in Provisioned Throughput mode or change between the throughput modes,
  as long as it’s been more than 24 hours since the last decrease or throughput mode
  change. For more information, see Specifying throughput with provisioned mode in the Amazon
  EFS User Guide.  Default is bursting.
"""
create_file_system(CreationToken; aws_config::AbstractAWSConfig=global_aws_config()) = efs("POST", "/2015-02-01/file-systems", Dict{String, Any}("CreationToken"=>CreationToken); aws_config=aws_config)
create_file_system(CreationToken, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = efs("POST", "/2015-02-01/file-systems", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("CreationToken"=>CreationToken), params)); aws_config=aws_config)

"""
    create_mount_target(file_system_id, subnet_id)
    create_mount_target(file_system_id, subnet_id, params::Dict{String,<:Any})

Creates a mount target for a file system. You can then mount the file system on EC2
instances by using the mount target. You can create one mount target in each Availability
Zone in your VPC. All EC2 instances in a VPC within a given Availability Zone share a
single mount target for a given file system. If you have multiple subnets in an
Availability Zone, you create a mount target in one of the subnets. EC2 instances do not
need to be in the same subnet as the mount target in order to access their file system. You
can create only one mount target for an EFS file system using One Zone storage classes. You
must create that mount target in the same Availability Zone in which the file system is
located. Use the AvailabilityZoneName and AvailabiltyZoneId properties in the
DescribeFileSystems response object to get this information. Use the subnetId associated
with the file system's Availability Zone when creating the mount target. For more
information, see Amazon EFS: How it Works.  To create a mount target for a file system, the
file system's lifecycle state must be available. For more information, see
DescribeFileSystems. In the request, provide the following:   The file system ID for which
you are creating the mount target.   A subnet ID, which determines the following:   The VPC
in which Amazon EFS creates the mount target   The Availability Zone in which Amazon EFS
creates the mount target   The IP address range from which Amazon EFS selects the IP
address of the mount target (if you don't specify an IP address in the request)     After
creating the mount target, Amazon EFS returns a response that includes, a MountTargetId and
an IpAddress. You use this IP address when mounting the file system in an EC2 instance. You
can also use the mount target's DNS name when mounting the file system. The EC2 instance on
which you mount the file system by using the mount target can resolve the mount target's
DNS name to its IP address. For more information, see How it Works: Implementation
Overview.  Note that you can create mount targets for a file system in only one VPC, and
there can be only one mount target per Availability Zone. That is, if the file system
already has one or more mount targets created for it, the subnet specified in the request
to add another mount target must meet the following requirements:   Must belong to the same
VPC as the subnets of the existing mount targets   Must not be in the same Availability
Zone as any of the subnets of the existing mount targets   If the request satisfies the
requirements, Amazon EFS does the following:   Creates a new mount target in the specified
subnet.   Also creates a new network interface in the subnet as follows:   If the request
provides an IpAddress, Amazon EFS assigns that IP address to the network interface.
Otherwise, Amazon EFS assigns a free address in the subnet (in the same way that the Amazon
EC2 CreateNetworkInterface call does when a request does not specify a primary private IP
address).   If the request provides SecurityGroups, this network interface is associated
with those security groups. Otherwise, it belongs to the default security group for the
subnet's VPC.   Assigns the description Mount target fsmt-id for file system fs-id  where
fsmt-id  is the mount target ID, and  fs-id  is the FileSystemId.   Sets the
requesterManaged property of the network interface to true, and the requesterId value to
EFS.   Each Amazon EFS mount target has one corresponding requester-managed EC2 network
interface. After the network interface is created, Amazon EFS sets the NetworkInterfaceId
field in the mount target's description to the network interface ID, and the IpAddress
field to its address. If network interface creation fails, the entire CreateMountTarget
operation fails.    The CreateMountTarget call returns only after creating the network
interface, but while the mount target state is still creating, you can check the mount
target creation status by calling the DescribeMountTargets operation, which among other
things returns the mount target state.  We recommend that you create a mount target in each
of the Availability Zones. There are cost considerations for using a file system in an
Availability Zone through a mount target created in another Availability Zone. For more
information, see Amazon EFS. In addition, by always using a mount target local to the
instance's Availability Zone, you eliminate a partial failure scenario. If the Availability
Zone in which your mount target is created goes down, then you can't access your file
system through that mount target.  This operation requires permissions for the following
action on the file system:    elasticfilesystem:CreateMountTarget    This operation also
requires permissions for the following Amazon EC2 actions:    ec2:DescribeSubnets
ec2:DescribeNetworkInterfaces     ec2:CreateNetworkInterface

# Arguments
- `file_system_id`: The ID of the file system for which to create the mount target.
- `subnet_id`: The ID of the subnet to add the mount target in. For file systems that use
  One Zone storage classes, use the subnet that is associated with the file system's
  Availability Zone.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"IpAddress"`: Valid IPv4 address within the address range of the specified subnet.
- `"SecurityGroups"`: Up to five VPC security group IDs, of the form sg-xxxxxxxx. These
  must be for the same VPC as subnet specified.
"""
create_mount_target(FileSystemId, SubnetId; aws_config::AbstractAWSConfig=global_aws_config()) = efs("POST", "/2015-02-01/mount-targets", Dict{String, Any}("FileSystemId"=>FileSystemId, "SubnetId"=>SubnetId); aws_config=aws_config)
create_mount_target(FileSystemId, SubnetId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = efs("POST", "/2015-02-01/mount-targets", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("FileSystemId"=>FileSystemId, "SubnetId"=>SubnetId), params)); aws_config=aws_config)

"""
    create_tags(file_system_id, tags)
    create_tags(file_system_id, tags, params::Dict{String,<:Any})

 DEPRECATED - CreateTags is deprecated and not maintained. Please use the API action to
create tags for EFS resources.  Creates or overwrites tags associated with a file system.
Each tag is a key-value pair. If a tag key specified in the request already exists on the
file system, this operation overwrites its value with the value provided in the request. If
you add the Name tag to your file system, Amazon EFS returns it in the response to the
DescribeFileSystems operation.  This operation requires permission for the
elasticfilesystem:CreateTags action.

# Arguments
- `file_system_id`: The ID of the file system whose tags you want to modify (String). This
  operation modifies the tags only, not the file system.
- `tags`: An array of Tag objects to add. Each Tag object is a key-value pair.

"""
create_tags(FileSystemId, Tags; aws_config::AbstractAWSConfig=global_aws_config()) = efs("POST", "/2015-02-01/create-tags/$(FileSystemId)", Dict{String, Any}("Tags"=>Tags); aws_config=aws_config)
create_tags(FileSystemId, Tags, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = efs("POST", "/2015-02-01/create-tags/$(FileSystemId)", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Tags"=>Tags), params)); aws_config=aws_config)

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

Deletes the specified access point. After deletion is complete, new clients can no longer
connect to the access points. Clients connected to the access point at the time of deletion
will continue to function until they terminate their connection. This operation requires
permissions for the elasticfilesystem:DeleteAccessPoint action.

# Arguments
- `access_point_id`: The ID of the access point that you want to delete.

"""
delete_access_point(AccessPointId; aws_config::AbstractAWSConfig=global_aws_config()) = efs("DELETE", "/2015-02-01/access-points/$(AccessPointId)"; aws_config=aws_config)
delete_access_point(AccessPointId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = efs("DELETE", "/2015-02-01/access-points/$(AccessPointId)", params; aws_config=aws_config)

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

Deletes a file system, permanently severing access to its contents. Upon return, the file
system no longer exists and you can't access any contents of the deleted file system.  You
can't delete a file system that is in use. That is, if the file system has any mount
targets, you must first delete them. For more information, see DescribeMountTargets and
DeleteMountTarget.   The DeleteFileSystem call returns while the file system state is still
deleting. You can check the file system deletion status by calling the DescribeFileSystems
operation, which returns a list of file systems in your account. If you pass file system ID
or creation token for the deleted file system, the DescribeFileSystems returns a 404
FileSystemNotFound error.  This operation requires permissions for the
elasticfilesystem:DeleteFileSystem action.

# Arguments
- `file_system_id`: The ID of the file system you want to delete.

"""
delete_file_system(FileSystemId; aws_config::AbstractAWSConfig=global_aws_config()) = efs("DELETE", "/2015-02-01/file-systems/$(FileSystemId)"; aws_config=aws_config)
delete_file_system(FileSystemId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = efs("DELETE", "/2015-02-01/file-systems/$(FileSystemId)", params; aws_config=aws_config)

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

Deletes the FileSystemPolicy for the specified file system. The default FileSystemPolicy
goes into effect once the existing policy is deleted. For more information about the
default file system policy, see Using Resource-based Policies with EFS. This operation
requires permissions for the elasticfilesystem:DeleteFileSystemPolicy action.

# Arguments
- `file_system_id`: Specifies the EFS file system for which to delete the FileSystemPolicy.

"""
delete_file_system_policy(FileSystemId; aws_config::AbstractAWSConfig=global_aws_config()) = efs("DELETE", "/2015-02-01/file-systems/$(FileSystemId)/policy"; aws_config=aws_config)
delete_file_system_policy(FileSystemId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = efs("DELETE", "/2015-02-01/file-systems/$(FileSystemId)/policy", params; aws_config=aws_config)

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

Deletes the specified mount target. This operation forcibly breaks any mounts of the file
system by using the mount target that is being deleted, which might disrupt instances or
applications using those mounts. To avoid applications getting cut off abruptly, you might
consider unmounting any mounts of the mount target, if feasible. The operation also deletes
the associated network interface. Uncommitted writes might be lost, but breaking a mount
target using this operation does not corrupt the file system itself. The file system you
created remains. You can mount an EC2 instance in your VPC by using another mount target.
This operation requires permissions for the following action on the file system:
elasticfilesystem:DeleteMountTarget     The DeleteMountTarget call returns while the mount
target state is still deleting. You can check the mount target deletion by calling the
DescribeMountTargets operation, which returns a list of mount target descriptions for the
given file system.   The operation also requires permissions for the following Amazon EC2
action on the mount target's network interface:    ec2:DeleteNetworkInterface

# Arguments
- `mount_target_id`: The ID of the mount target to delete (String).

"""
delete_mount_target(MountTargetId; aws_config::AbstractAWSConfig=global_aws_config()) = efs("DELETE", "/2015-02-01/mount-targets/$(MountTargetId)"; aws_config=aws_config)
delete_mount_target(MountTargetId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = efs("DELETE", "/2015-02-01/mount-targets/$(MountTargetId)", params; aws_config=aws_config)

"""
    delete_tags(file_system_id, tag_keys)
    delete_tags(file_system_id, tag_keys, params::Dict{String,<:Any})

 DEPRECATED - DeleteTags is deprecated and not maintained. Please use the API action to
remove tags from EFS resources.  Deletes the specified tags from a file system. If the
DeleteTags request includes a tag key that doesn't exist, Amazon EFS ignores it and doesn't
cause an error. For more information about tags and related restrictions, see Tag
Restrictions in the AWS Billing and Cost Management User Guide. This operation requires
permissions for the elasticfilesystem:DeleteTags action.

# Arguments
- `file_system_id`: The ID of the file system whose tags you want to delete (String).
- `tag_keys`: A list of tag keys to delete.

"""
delete_tags(FileSystemId, TagKeys; aws_config::AbstractAWSConfig=global_aws_config()) = efs("POST", "/2015-02-01/delete-tags/$(FileSystemId)", Dict{String, Any}("TagKeys"=>TagKeys); aws_config=aws_config)
delete_tags(FileSystemId, TagKeys, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = efs("POST", "/2015-02-01/delete-tags/$(FileSystemId)", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("TagKeys"=>TagKeys), params)); aws_config=aws_config)

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

Returns the description of a specific Amazon EFS access point if the AccessPointId is
provided. If you provide an EFS FileSystemId, it returns descriptions of all access points
for that file system. You can provide either an AccessPointId or a FileSystemId in the
request, but not both.  This operation requires permissions for the
elasticfilesystem:DescribeAccessPoints action.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"AccessPointId"`: (Optional) Specifies an EFS access point to describe in the response;
  mutually exclusive with FileSystemId.
- `"FileSystemId"`: (Optional) If you provide a FileSystemId, EFS returns all access points
  for that file system; mutually exclusive with AccessPointId.
- `"MaxResults"`: (Optional) When retrieving all access points for a file system, you can
  optionally specify the MaxItems parameter to limit the number of objects returned in a
  response. The default value is 100.
- `"NextToken"`:  NextToken is present if the response is paginated. You can use NextMarker
  in the subsequent request to fetch the next page of access point descriptions.
"""
describe_access_points(; aws_config::AbstractAWSConfig=global_aws_config()) = efs("GET", "/2015-02-01/access-points"; aws_config=aws_config)
describe_access_points(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = efs("GET", "/2015-02-01/access-points", params; aws_config=aws_config)

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

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"MaxResults"`:
- `"NextToken"`:
"""
describe_account_preferences(; aws_config::AbstractAWSConfig=global_aws_config()) = efs("GET", "/2015-02-01/account-preferences"; aws_config=aws_config)
describe_account_preferences(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = efs("GET", "/2015-02-01/account-preferences", params; aws_config=aws_config)

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

Returns the backup policy for the specified EFS file system.

# Arguments
- `file_system_id`: Specifies which EFS file system to retrieve the BackupPolicy for.

"""
describe_backup_policy(FileSystemId; aws_config::AbstractAWSConfig=global_aws_config()) = efs("GET", "/2015-02-01/file-systems/$(FileSystemId)/backup-policy"; aws_config=aws_config)
describe_backup_policy(FileSystemId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = efs("GET", "/2015-02-01/file-systems/$(FileSystemId)/backup-policy", params; aws_config=aws_config)

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

Returns the FileSystemPolicy for the specified EFS file system. This operation requires
permissions for the elasticfilesystem:DescribeFileSystemPolicy action.

# Arguments
- `file_system_id`: Specifies which EFS file system to retrieve the FileSystemPolicy for.

"""
describe_file_system_policy(FileSystemId; aws_config::AbstractAWSConfig=global_aws_config()) = efs("GET", "/2015-02-01/file-systems/$(FileSystemId)/policy"; aws_config=aws_config)
describe_file_system_policy(FileSystemId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = efs("GET", "/2015-02-01/file-systems/$(FileSystemId)/policy", params; aws_config=aws_config)

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

Returns the description of a specific Amazon EFS file system if either the file system
CreationToken or the FileSystemId is provided. Otherwise, it returns descriptions of all
file systems owned by the caller's AWS account in the AWS Region of the endpoint that
you're calling. When retrieving all file system descriptions, you can optionally specify
the MaxItems parameter to limit the number of descriptions in a response. Currently, this
number is automatically set to 10. If more file system descriptions remain, Amazon EFS
returns a NextMarker, an opaque token, in the response. In this case, you should send a
subsequent request with the Marker request parameter set to the value of NextMarker.  To
retrieve a list of your file system descriptions, this operation is used in an iterative
process, where DescribeFileSystems is called first without the Marker and then the
operation continues to call it with the Marker parameter set to the value of the NextMarker
from the previous response until the response has no NextMarker.   The order of file
systems returned in the response of one DescribeFileSystems call and the order of file
systems returned across the responses of a multi-call iteration is unspecified.   This
operation requires permissions for the elasticfilesystem:DescribeFileSystems action.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"CreationToken"`: (Optional) Restricts the list to the file system with this creation
  token (String). You specify a creation token when you create an Amazon EFS file system.
- `"FileSystemId"`: (Optional) ID of the file system whose description you want to retrieve
  (String).
- `"Marker"`: (Optional) Opaque pagination token returned from a previous
  DescribeFileSystems operation (String). If present, specifies to continue the list from
  where the returning call had left off.
- `"MaxItems"`: (Optional) Specifies the maximum number of file systems to return in the
  response (integer). This number is automatically set to 100. The response is paginated at
  100 per page if you have more than 100 file systems.
"""
describe_file_systems(; aws_config::AbstractAWSConfig=global_aws_config()) = efs("GET", "/2015-02-01/file-systems"; aws_config=aws_config)
describe_file_systems(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = efs("GET", "/2015-02-01/file-systems", params; aws_config=aws_config)

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

Returns the current LifecycleConfiguration object for the specified Amazon EFS file system.
EFS lifecycle management uses the LifecycleConfiguration object to identify which files to
move to the EFS Infrequent Access (IA) storage class. For a file system without a
LifecycleConfiguration object, the call returns an empty array in the response. This
operation requires permissions for the elasticfilesystem:DescribeLifecycleConfiguration
operation.

# Arguments
- `file_system_id`: The ID of the file system whose LifecycleConfiguration object you want
  to retrieve (String).

"""
describe_lifecycle_configuration(FileSystemId; aws_config::AbstractAWSConfig=global_aws_config()) = efs("GET", "/2015-02-01/file-systems/$(FileSystemId)/lifecycle-configuration"; aws_config=aws_config)
describe_lifecycle_configuration(FileSystemId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = efs("GET", "/2015-02-01/file-systems/$(FileSystemId)/lifecycle-configuration", params; aws_config=aws_config)

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

Returns the security groups currently in effect for a mount target. This operation requires
that the network interface of the mount target has been created and the lifecycle state of
the mount target is not deleted. This operation requires permissions for the following
actions:    elasticfilesystem:DescribeMountTargetSecurityGroups action on the mount
target's file system.     ec2:DescribeNetworkInterfaceAttribute action on the mount
target's network interface.

# Arguments
- `mount_target_id`: The ID of the mount target whose security groups you want to retrieve.

"""
describe_mount_target_security_groups(MountTargetId; aws_config::AbstractAWSConfig=global_aws_config()) = efs("GET", "/2015-02-01/mount-targets/$(MountTargetId)/security-groups"; aws_config=aws_config)
describe_mount_target_security_groups(MountTargetId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = efs("GET", "/2015-02-01/mount-targets/$(MountTargetId)/security-groups", params; aws_config=aws_config)

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

Returns the descriptions of all the current mount targets, or a specific mount target, for
a file system. When requesting all of the current mount targets, the order of mount targets
returned in the response is unspecified. This operation requires permissions for the
elasticfilesystem:DescribeMountTargets action, on either the file system ID that you
specify in FileSystemId, or on the file system of the mount target that you specify in
MountTargetId.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"AccessPointId"`: (Optional) The ID of the access point whose mount targets that you
  want to list. It must be included in your request if a FileSystemId or MountTargetId is not
  included in your request. Accepts either an access point ID or ARN as input.
- `"FileSystemId"`: (Optional) ID of the file system whose mount targets you want to list
  (String). It must be included in your request if an AccessPointId or MountTargetId is not
  included. Accepts either a file system ID or ARN as input.
- `"Marker"`: (Optional) Opaque pagination token returned from a previous
  DescribeMountTargets operation (String). If present, it specifies to continue the list from
  where the previous returning call left off.
- `"MaxItems"`: (Optional) Maximum number of mount targets to return in the response.
  Currently, this number is automatically set to 10, and other values are ignored. The
  response is paginated at 100 per page if you have more than 100 mount targets.
- `"MountTargetId"`: (Optional) ID of the mount target that you want to have described
  (String). It must be included in your request if FileSystemId is not included. Accepts
  either a mount target ID or ARN as input.
"""
describe_mount_targets(; aws_config::AbstractAWSConfig=global_aws_config()) = efs("GET", "/2015-02-01/mount-targets"; aws_config=aws_config)
describe_mount_targets(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = efs("GET", "/2015-02-01/mount-targets", params; aws_config=aws_config)

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

 DEPRECATED - The DeleteTags action is deprecated and not maintained. Please use the API
action to remove tags from EFS resources.  Returns the tags associated with a file system.
The order of tags returned in the response of one DescribeTags call and the order of tags
returned across the responses of a multiple-call iteration (when using pagination) is
unspecified.   This operation requires permissions for the elasticfilesystem:DescribeTags
action.

# Arguments
- `file_system_id`: The ID of the file system whose tag set you want to retrieve.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Marker"`: (Optional) An opaque pagination token returned from a previous DescribeTags
  operation (String). If present, it specifies to continue the list from where the previous
  call left off.
- `"MaxItems"`: (Optional) The maximum number of file system tags to return in the
  response. Currently, this number is automatically set to 100, and other values are ignored.
  The response is paginated at 100 per page if you have more than 100 tags.
"""
describe_tags(FileSystemId; aws_config::AbstractAWSConfig=global_aws_config()) = efs("GET", "/2015-02-01/tags/$(FileSystemId)/"; aws_config=aws_config)
describe_tags(FileSystemId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = efs("GET", "/2015-02-01/tags/$(FileSystemId)/", params; aws_config=aws_config)

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

Lists all tags for a top-level EFS resource. You must provide the ID of the resource that
you want to retrieve the tags for. This operation requires permissions for the
elasticfilesystem:DescribeAccessPoints action.

# Arguments
- `resource_id`: Specifies the EFS resource you want to retrieve tags for. You can retrieve
  tags for EFS file systems and access points using this API endpoint.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"MaxResults"`: (Optional) Specifies the maximum number of tag objects to return in the
  response. The default value is 100.
- `"NextToken"`: (Optional) You can use NextToken in a subsequent request to fetch the next
  page of access point descriptions if the response payload was paginated.
"""
list_tags_for_resource(ResourceId; aws_config::AbstractAWSConfig=global_aws_config()) = efs("GET", "/2015-02-01/resource-tags/$(ResourceId)"; aws_config=aws_config)
list_tags_for_resource(ResourceId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = efs("GET", "/2015-02-01/resource-tags/$(ResourceId)", params; aws_config=aws_config)

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

Modifies the set of security groups in effect for a mount target. When you create a mount
target, Amazon EFS also creates a new network interface. For more information, see
CreateMountTarget. This operation replaces the security groups in effect for the network
interface associated with a mount target, with the SecurityGroups provided in the request.
This operation requires that the network interface of the mount target has been created and
the lifecycle state of the mount target is not deleted.  The operation requires permissions
for the following actions:    elasticfilesystem:ModifyMountTargetSecurityGroups action on
the mount target's file system.     ec2:ModifyNetworkInterfaceAttribute action on the mount
target's network interface.

# Arguments
- `mount_target_id`: The ID of the mount target whose security groups you want to modify.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"SecurityGroups"`: An array of up to five VPC security group IDs.
"""
modify_mount_target_security_groups(MountTargetId; aws_config::AbstractAWSConfig=global_aws_config()) = efs("PUT", "/2015-02-01/mount-targets/$(MountTargetId)/security-groups"; aws_config=aws_config)
modify_mount_target_security_groups(MountTargetId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = efs("PUT", "/2015-02-01/mount-targets/$(MountTargetId)/security-groups", params; aws_config=aws_config)

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

# Arguments
- `resource_id_type`:

"""
put_account_preferences(ResourceIdType; aws_config::AbstractAWSConfig=global_aws_config()) = efs("PUT", "/2015-02-01/account-preferences", Dict{String, Any}("ResourceIdType"=>ResourceIdType); aws_config=aws_config)
put_account_preferences(ResourceIdType, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = efs("PUT", "/2015-02-01/account-preferences", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ResourceIdType"=>ResourceIdType), params)); aws_config=aws_config)

"""
    put_backup_policy(backup_policy, file_system_id)
    put_backup_policy(backup_policy, file_system_id, params::Dict{String,<:Any})

Updates the file system's backup policy. Use this action to start or stop automatic backups
of the file system.

# Arguments
- `backup_policy`: The backup policy included in the PutBackupPolicy request.
- `file_system_id`: Specifies which EFS file system to update the backup policy for.

"""
put_backup_policy(BackupPolicy, FileSystemId; aws_config::AbstractAWSConfig=global_aws_config()) = efs("PUT", "/2015-02-01/file-systems/$(FileSystemId)/backup-policy", Dict{String, Any}("BackupPolicy"=>BackupPolicy); aws_config=aws_config)
put_backup_policy(BackupPolicy, FileSystemId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = efs("PUT", "/2015-02-01/file-systems/$(FileSystemId)/backup-policy", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("BackupPolicy"=>BackupPolicy), params)); aws_config=aws_config)

"""
    put_file_system_policy(file_system_id, policy)
    put_file_system_policy(file_system_id, policy, params::Dict{String,<:Any})

Applies an Amazon EFS FileSystemPolicy to an Amazon EFS file system. A file system policy
is an IAM resource-based policy and can contain multiple policy statements. A file system
always has exactly one file system policy, which can be the default policy or an explicit
policy set or updated using this API operation. EFS file system policies have a 20,000
character limit. When an explicit policy is set, it overrides the default policy. For more
information about the default file system policy, see Default EFS File System Policy.  EFS
file system policies have a 20,000 character limit. This operation requires permissions for
the elasticfilesystem:PutFileSystemPolicy action.

# Arguments
- `file_system_id`: The ID of the EFS file system that you want to create or update the
  FileSystemPolicy for.
- `policy`: The FileSystemPolicy that you're creating. Accepts a JSON formatted policy
  definition. EFS file system policies have a 20,000 character limit. To find out more about
  the elements that make up a file system policy, see EFS Resource-based Policies.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"BypassPolicyLockoutSafetyCheck"`: (Optional) A flag to indicate whether to bypass the
  FileSystemPolicy lockout safety check. The policy lockout safety check determines whether
  the policy in the request will prevent the principal making the request will be locked out
  from making future PutFileSystemPolicy requests on the file system. Set
  BypassPolicyLockoutSafetyCheck to True only when you intend to prevent the principal that
  is making the request from making a subsequent PutFileSystemPolicy request on the file
  system. The default value is False.
"""
put_file_system_policy(FileSystemId, Policy; aws_config::AbstractAWSConfig=global_aws_config()) = efs("PUT", "/2015-02-01/file-systems/$(FileSystemId)/policy", Dict{String, Any}("Policy"=>Policy); aws_config=aws_config)
put_file_system_policy(FileSystemId, Policy, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = efs("PUT", "/2015-02-01/file-systems/$(FileSystemId)/policy", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Policy"=>Policy), params)); aws_config=aws_config)

"""
    put_lifecycle_configuration(file_system_id, lifecycle_policies)
    put_lifecycle_configuration(file_system_id, lifecycle_policies, params::Dict{String,<:Any})

Enables lifecycle management by creating a new LifecycleConfiguration object. A
LifecycleConfiguration object defines when files in an Amazon EFS file system are
automatically transitioned to the lower-cost EFS Infrequent Access (IA) storage class. A
LifecycleConfiguration applies to all files in a file system. Each Amazon EFS file system
supports one lifecycle configuration, which applies to all files in the file system. If a
LifecycleConfiguration object already exists for the specified file system, a
PutLifecycleConfiguration call modifies the existing configuration. A
PutLifecycleConfiguration call with an empty LifecyclePolicies array in the request body
deletes any existing LifecycleConfiguration and disables lifecycle management. In the
request, specify the following:    The ID for the file system for which you are enabling,
disabling, or modifying lifecycle management.   A LifecyclePolicies array of
LifecyclePolicy objects that define when files are moved to the IA storage class. The array
can contain only one LifecyclePolicy item.   This operation requires permissions for the
elasticfilesystem:PutLifecycleConfiguration operation. To apply a LifecycleConfiguration
object to an encrypted file system, you need the same AWS Key Management Service (AWS KMS)
permissions as when you created the encrypted file system.

# Arguments
- `file_system_id`: The ID of the file system for which you are creating the
  LifecycleConfiguration object (String).
- `lifecycle_policies`: An array of LifecyclePolicy objects that define the file system's
  LifecycleConfiguration object. A LifecycleConfiguration object tells lifecycle management
  when to transition files from the Standard storage class to the Infrequent Access storage
  class.

"""
put_lifecycle_configuration(FileSystemId, LifecyclePolicies; aws_config::AbstractAWSConfig=global_aws_config()) = efs("PUT", "/2015-02-01/file-systems/$(FileSystemId)/lifecycle-configuration", Dict{String, Any}("LifecyclePolicies"=>LifecyclePolicies); aws_config=aws_config)
put_lifecycle_configuration(FileSystemId, LifecyclePolicies, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = efs("PUT", "/2015-02-01/file-systems/$(FileSystemId)/lifecycle-configuration", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("LifecyclePolicies"=>LifecyclePolicies), params)); aws_config=aws_config)

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

Creates a tag for an EFS resource. You can create tags for EFS file systems and access
points using this API operation. This operation requires permissions for the
elasticfilesystem:TagResource action.

# Arguments
- `resource_id`: The ID specifying the EFS resource that you want to create a tag for.
- `tags`: An array of Tag objects to add. Each Tag object is a key-value pair.

"""
tag_resource(ResourceId, Tags; aws_config::AbstractAWSConfig=global_aws_config()) = efs("POST", "/2015-02-01/resource-tags/$(ResourceId)", Dict{String, Any}("Tags"=>Tags); aws_config=aws_config)
tag_resource(ResourceId, Tags, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = efs("POST", "/2015-02-01/resource-tags/$(ResourceId)", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Tags"=>Tags), params)); aws_config=aws_config)

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

Removes tags from an EFS resource. You can remove tags from EFS file systems and access
points using this API operation. This operation requires permissions for the
elasticfilesystem:UntagResource action.

# Arguments
- `resource_id`: Specifies the EFS resource that you want to remove tags from.
- `tag_keys`: The keys of the key-value tag pairs that you want to remove from the
  specified EFS resource.

"""
untag_resource(ResourceId, tagKeys; aws_config::AbstractAWSConfig=global_aws_config()) = efs("DELETE", "/2015-02-01/resource-tags/$(ResourceId)", Dict{String, Any}("tagKeys"=>tagKeys); aws_config=aws_config)
untag_resource(ResourceId, tagKeys, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = efs("DELETE", "/2015-02-01/resource-tags/$(ResourceId)", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("tagKeys"=>tagKeys), params)); aws_config=aws_config)

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

Updates the throughput mode or the amount of provisioned throughput of an existing file
system.

# Arguments
- `file_system_id`: The ID of the file system that you want to update.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"ProvisionedThroughputInMibps"`: (Optional) Sets the amount of provisioned throughput,
  in MiB/s, for the file system. Valid values are 1-1024. If you are changing the throughput
  mode to provisioned, you must also provide the amount of provisioned throughput. Required
  if ThroughputMode is changed to provisioned on update.
- `"ThroughputMode"`: (Optional) Updates the file system's throughput mode. If you're not
  updating your throughput mode, you don't need to provide this value in your request. If you
  are changing the ThroughputMode to provisioned, you must also set a value for
  ProvisionedThroughputInMibps.
"""
update_file_system(FileSystemId; aws_config::AbstractAWSConfig=global_aws_config()) = efs("PUT", "/2015-02-01/file-systems/$(FileSystemId)"; aws_config=aws_config)
update_file_system(FileSystemId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = efs("PUT", "/2015-02-01/file-systems/$(FileSystemId)", params; aws_config=aws_config)


text:
using Pipe

"""
    search_filtered(func, dict)

Produce a set of entries for which `func(entry)` returns `true`. This is considered
an internal function and not part of the public API for this package; use at your own risk!
"""
function search_filtered(filter_func, dict::ChineseDictionary)
    word_entries = Set{DictionaryEntry}()

    for entry_list in values(dict)
        for entry in entry_list
            filter_func(entry) && push!(word_entries, entry)
        end
    end

    word_entries
end

"""
    search_headwords(dict, keyword)

Search for the given `keyword` in the dictionary as a headword, in either traditional or
simplified characters (will only return results where the headword is an exact match for
`keyword`; this behavior may change in future releases).

## Examples
```julia-repl
julia> search_headwords(dict, "2019冠狀病毒病") .|> println;
2019冠狀病毒病 (2019冠状病毒病): [er4 ling2 yi1 jiu3 guan1 zhuang4 bing4 du2 bing4]
        COVID-19, the coronavirus disease identified in 2019
```
"""
search_headwords(dict::ChineseDictionary, keyword) =
    search_filtered(dict) do entry
        occursin(keyword, entry.trad) || occursin(keyword, entry.simp)
    end

"""
    search_senses(dict, keyword)

Search for the given `keyword` in the dictionary among the meanings/senses (the `keyword` must
appear exactly in one or more of the definition senses; this behavior may change in future
releases).

## Examples
julia> search_senses(dict, "fishnet") .|> println;
漁網 (渔网): [yu2 wang3]
        fishing net
        fishnet
扳罾: [ban1 zeng1]
        to lift the fishnet
網襪 (网袜): [wang3 wa4]
        fishnet stockings

"""
search_senses(dict::ChineseDictionary, keyword) =
    search_filtered(dict) do entry
        any(occursin.(keyword, entry.senses))
    end

"""
    search_pinyin(dict, keyword)

Search the dictionary for terms that fuzzy match the pinyin search key provided.
The language that is understood for the search key is described below.

# Examples
```julia-repl
julia> search_pinyin(dict, "yi2 han4") .|> println;
遺憾 (遗憾): [yi2 han4]
        regret
        to regret
        to be sorry that

julia> search_pinyin(dict, "bang shou") .|> println;
榜首: [bang3 shou3]
        top of the list
幫手 (帮手): [bang1 shou3]
        helper
        assistant

```
"""
function search_pinyin(dict::ChineseDictionary, pinyin_searchkey)
    search_regex = _convert_pinyin_regex(pinyin_searchkey)
    search_filtered(dict) do entry
        match(search_regex, entry.pinyin) != nothing
    end
end

function _convert_pinyin_regex(searchkey)
    re = @pipe split(searchkey, " ") |>
            map(w -> (w == "*" ? raw"(\w+\d)*" : w), _) |> # TODO: doesn't handle spaces correctly'
            map(w -> (w == "+" ? raw"(\w+\d)+" : w), _) |>
            map(w -> (w == "?" ? raw"(\w+\d)?" : w), _) |>
            map(w -> w * raw"\d?", _)|>
            join(_, raw"\s")
    Regex("^$(re)\$")
end

ext: jl


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

mutable struct ApplicationGatewayProbeHealthResponseMatch <: SwaggerModel
    body::Any # spec type: Union{ Nothing, String } # spec name: body
    statusCodes::Any # spec type: Union{ Nothing, Vector{String} } # spec name: statusCodes

    function ApplicationGatewayProbeHealthResponseMatch(;body=nothing, statusCodes=nothing)
        o = new()
        validate_property(ApplicationGatewayProbeHealthResponseMatch, Symbol("body"), body)
        setfield!(o, Symbol("body"), body)
        validate_property(ApplicationGatewayProbeHealthResponseMatch, Symbol("statusCodes"), statusCodes)
        setfield!(o, Symbol("statusCodes"), statusCodes)
        o
    end
end # type ApplicationGatewayProbeHealthResponseMatch

const _property_map_ApplicationGatewayProbeHealthResponseMatch = Dict{Symbol,Symbol}(Symbol("body")=>Symbol("body"), Symbol("statusCodes")=>Symbol("statusCodes"))
const _property_types_ApplicationGatewayProbeHealthResponseMatch = Dict{Symbol,String}(Symbol("body")=>"String", Symbol("statusCodes")=>"Vector{String}")
Base.propertynames(::Type{ ApplicationGatewayProbeHealthResponseMatch }) = collect(keys(_property_map_ApplicationGatewayProbeHealthResponseMatch))
Swagger.property_type(::Type{ ApplicationGatewayProbeHealthResponseMatch }, name::Symbol) = Union{Nothing,eval(Base.Meta.parse(_property_types_ApplicationGatewayProbeHealthResponseMatch[name]))}
Swagger.field_name(::Type{ ApplicationGatewayProbeHealthResponseMatch }, property_name::Symbol) =  _property_map_ApplicationGatewayProbeHealthResponseMatch[property_name]

function check_required(o::ApplicationGatewayProbeHealthResponseMatch)
    true
end

function validate_property(::Type{ ApplicationGatewayProbeHealthResponseMatch }, name::Symbol, val)
end


text:
abstract AbstractCovarianceFunction

abstract StationaryCovarianceFunction <: AbstractCovarianceFunction

Base.call(f::StationaryCovarianceFunction,x,y) = f(sqrt(sumabs2(x-y)))

doc"""
A Gaussian covariance function is of the form

C(x_1,x_2) = σ^2 e^{-\|x_1-x_2\|^2/2L^2}

where L is the bandwidth of the Gaussian kernel.
"""
type GaussianCovarianceFunction <: StationaryCovarianceFunction
    L::Real
    σ::Real
end

Base.call(f::GaussianCovarianceFunction,h) = f.σ^2*exp(-h^2/(2*f.L^2))

doc"""
A Matérn covariance function takes the form

C(x_1,x_2) = σ^2 \frac{2^{1-ν}}{Γ(ν)}(\sqrt{2ν}\|x_1-x_2\|/ρ)^ν K_ν(\sqrt{2ν}\|x_1-x_2\|/ρ)

where ν gives the order of the modified Bessel function of the second kind, K_ν, ρ is the bandwidth/correlation length and σ is the total covariance.
"""
type MatérnCovarianceFunction <: StationaryCovarianceFunction
    ν::Real
    ρ::Real
    σ::Real
end

Base.call(f::MatérnCovarianceFunction,h) = (h==0?f.σ^2:f.σ^2*2.0^(1-f.ν)/gamma(f.ν)*(sqrt(2*f.ν)*h/f.ρ)^f.ν*besselk(f.ν,sqrt(2*f.ν)*h/f.ρ))

doc"""
Generates a covariance matrix from a stationary covariance function
and a matrix of distances as might be generated by Distances.jl's
`pairwise` function
"""
covariancematrix(f::StationaryCovarianceFunction,D::Matrix) = map(f,D)


text:
<extend src="layout.jl">
    <block name="content">

{{ message }}

    </block>
</extend>

max_stars_repo_name: misterdev/angel

max_issues_repo_name: misterdev/angel

max_forks_repo_name: misterdev/angel


text:
export MNIST

"""
The MNIST database of handwritten digits

- Authors: Yann LeCun, Corinna Cortes, Christopher J.C. Burges
- Website: http://yann.lecun.com/exdb/mnist/

MNIST is a classic image-classification dataset that is often
used in small-scale machine learning experiments. It contains
70,000 images of handwritten digits. Each observation is a 28x28
pixel gray-scale image that depicts a handwritten version of 1 of
the 10 possible digits (0-9).

# Interface

- [`MNIST.traintensor`](@ref), [`MNIST.trainlabels`](@ref), [`MNIST.traindata`](@ref)
- [`MNIST.testtensor`](@ref), [`MNIST.testlabels`](@ref), [`MNIST.testdata`](@ref)

# Utilities

- [`MNIST.download`](@ref)
- [`MNIST.convert2image`](@ref)
"""
module MNIST
    using DataDeps
    using ColorTypes
    using FixedPointNumbers
    using ..MLDatasets: bytes_to_type, datafile, download_dep, download_docstring,
                        _colorview

    export

        traintensor,
        testtensor,

        trainlabels,
        testlabels,

        traindata,
        testdata,

        convert2image,

        download

    @deprecate convert2features reshape

    const DEPNAME = "MNIST"
    const TRAINIMAGES = "train-images-idx3-ubyte.gz"
    const TRAINLABELS = "train-labels-idx1-ubyte.gz"
    const TESTIMAGES  = "t10k-images-idx3-ubyte.gz"
    const TESTLABELS  = "t10k-labels-idx1-ubyte.gz"

    """
        download([dir]; [i_accept_the_terms_of_use])

    Trigger the (interactive) download of the full dataset into
    "`dir`". If no `dir` is provided the dataset will be
    downloaded into "~/.julia/datadeps/$DEPNAME".

    This function will display an interactive dialog unless
    either the keyword parameter `i_accept_the_terms_of_use` or
    the environment variable `DATADEPS_ALWAYS_ACCEPT` is set to
    `true`. Note that using the data responsibly and respecting
    copyright/terms-of-use remains your responsibility.
    """
    download(args...; kw...) = download_dep(DEPNAME, args...; kw...)

    include(joinpath("Reader","Reader.jl"))
    include("interface.jl")
    include("utils.jl")

    function __init__()
        register(DataDep(
            DEPNAME,
            """
            Dataset: THE MNIST DATABASE of handwritten digits
            Authors: Yann LeCun, Corinna Cortes, Christopher J.C. Burges
            Website: http://yann.lecun.com/exdb/mnist/

            [LeCun et al., 1998a]
                Y. LeCun, L. Bottou, Y. Bengio, and P. Haffner.
                "Gradient-based learning applied to document recognition."
                Proceedings of the IEEE, 86(11):2278-2324, November 1998

            The files are available for download at the offical
            website linked above. Note that using the data
            responsibly and respecting copyright remains your
            responsibility. The authors of MNIST aren't really
            explicit about any terms of use, so please read the
            website to make sure you want to download the
            dataset.
            """,
            "https://ossci-datasets.s3.amazonaws.com/mnist/" .* [TRAINIMAGES, TRAINLABELS, TESTIMAGES, TESTLABELS],
            "0bb1d5775d852fc5bb32c76ca15a7eb4e9a3b1514a2493f7edfcf49b639d7975",
        ))
    end
end


text:
# Default implmenentation for CuArrays
using CUDA: @workspace, @argout

memsize(a::CuArray) = sizeof(a)

scalar(C::CuArray) = ndims(C)==0 ? collect(C)[] : throw(DimensionMismatch())

function add!(α, A::CuArray{<:Any, N}, CA::Symbol,
                β, C::CuArray{<:Any, N}, indCinA) where {N}

    T = eltype(C)
    N == length(indCinA) || throw(IndexError("Invalid permutation of length $N: $indCinA"))
    CA == :N || CA == :C ||
        throw(ArgumentError("Value of conjA should be :N or :C instead of $CA"))
    opA = (T <: Real || CA == :N) ? CUTENSOR_OP_IDENTITY : CUTENSOR_OP_CONJ
    opAC = CUTENSOR_OP_ADD

    descA = CuTensorDescriptor(A; op = opA)
    descC = CuTensorDescriptor(C; op = CUTENSOR_OP_IDENTITY)
    descD = descC
    typeCompute = convert(cudaDataType, T)
    modeA = collect(Cint, 1:N)
    modeC = collect(Cint, indCinA)
    stream = CuDefaultStream()
    if β == zero(β)
        cutensorPermutation(handle(), T[α], A, descA, modeA, C, descC, modeC,
                            typeCompute, stream)
    else
        cutensorElementwiseBinary(handle(), T[α], A, descA, modeA, T[β], C, descC,
                                  modeC, C, descC, modeC, opAC, typeCompute, stream)
    end

    return C
end

# TODO: the following seems broken due to bug in CUTENSOR?#
# function add!(α, A::CuArray{T, N}, CA::Symbol,
#                 β, C::CuArray{Complex{T}, N}, indCinA) where {T<:CublasReal,N}
#
#     N == length(indCinA) || throw(IndexError("Invalid permutation of length $N: $indCinA"))
#     CA == :N || CA == :C ||
#         throw(ArgumentError("Value of conjA should be :N or :C instead of $CA"))
#     opid = CUTENSOR_OP_IDENTITY
#     opAC = CUTENSOR_OP_ADD
#
#     if β == zero(β)
#         fill!(C, zero(Complex{T}))
#     elseif β != one(β)
#         rmul!(C, β)
#     end
#     sizeC = size(C)
#     stridesC = 2 .* strides(C)
#     Cr = reinterpret(T, C, (2*length(C),))
#
#     @show stridesC, sizeC
#
#     descA = CuTensorDescriptor(A; op = opid)
#     descCr = CuTensorDescriptor(Cr; size = sizeC, strides = stridesC, op = opid)
#     typeCompute = cudaDataType(T)
#     modeA = collect(Cint, 1:N)
#     modeC = collect(Cint, indCinA)
#     stream = CuDefaultStream()
#     cutensorElementwiseBinary(handle(), T[real(α)], A, descA, modeA, T[1], Cr, descCr,
#                               modeC, Cr, descCr, modeC, opAC, typeCompute, stream)
#     if imag(α) != 0
#         Ci = view(Cr, 2:length(Cr))
#         descCi = CuTensorDescriptor(Ci; size = sizeC, strides = stridesC, op = opid)
#         cutensorElementwiseBinary(handle(), T[imag(α)], A, descA, modeA, T[1], Ci, descCi,
#                                   modeC, Ci, descCi, modeC, opAC, typeCompute, stream)
#     end
#     return C
# end

function trace!(α, A::CuArray, CA::Symbol, β, C::CuArray,
                indCinA, cindA1, cindA2)

    T = eltype(C)
    NA, NC = ndims(A), ndims(C)
    NC == length(indCinA) ||
        throw(IndexError("Invalid selection of $NC out of $NA: $indCinA"))
    NA-NC == 2*length(cindA1) == 2*length(cindA2) ||
        throw(IndexError("invalid number of trace dimension"))

    opA = (T <: Real || CA == :N) ? CUTENSOR_OP_IDENTITY : CUTENSOR_OP_CONJ
    opReduce = CUTENSOR_OP_ADD

    sizeA = i->size(A, i)
    strideA = i->stride(A, i)
    tracesize = sizeA.(cindA1)
    tracesize == sizeA.(cindA2) || throw(DimensionMismatch("non-matching trace sizes"))
    size(C) == sizeA.(indCinA) || throw(DimensionMismatch("non-matching sizes"))

    newstrides = (strideA.(indCinA)..., (strideA.(cindA1) .+ strideA.(cindA2))...)
    newsize = (size(C)..., tracesize...)
    descA = CuTensorDescriptor(A; op = opA, size = newsize, strides = newstrides)
    descC = CuTensorDescriptor(C; op = CUTENSOR_OP_IDENTITY)
    descD = descC
    typeCompute = cutensorComputeType(T)
    modeA = collect(Cint, 1:NA)
    modeC = collect(Cint, 1:NC)
    stream = CuDefaultStream()
    @workspace fallback=1<<13 size=@argout(
            cutensorReductionGetWorkspace(handle(),
                A, descA, modeA,
                C, descC, modeC,
                C, descC, modeC,
                opReduce, typeCompute,
                out(Ref{UInt64}(C_NULL)))
        )[] workspace->begin
            cutensorReduction(handle(),
                T[α], A, descA, modeA,
                T[β], C, descC, modeC,
                        C, descC, modeC,
                opReduce, typeCompute,
                workspace, sizeof(workspace), stream)
        end
    return C
end

function contract!(α, A::CuArray, CA::Symbol,
                    B::CuArray, CB::Symbol,
                    β, C::CuArray,
                    oindA::IndexTuple, cindA::IndexTuple,
                    oindB::IndexTuple, cindB::IndexTuple,
                    indCinoAB::IndexTuple, syms::Union{Nothing, NTuple{3,Symbol}} = nothing)

    pA = (oindA...,cindA...)
    (length(pA) == ndims(A) && isperm(pA)) ||
        throw(IndexError("invalid permutation of length $(ndims(A)): $pA"))
    pB = (oindB...,cindB...)
    (length(pB) == ndims(B) && isperm(pB)) ||
        throw(IndexError("invalid permutation of length $(ndims(B)): $pB"))
    (length(oindA) + length(oindB) == ndims(C)) ||
        throw(IndexError("non-matching output indices in contraction"))
    (ndims(C) == length(indCinoAB) && isperm(indCinoAB)) ||
        throw(IndexError("invalid permutation of length $(ndims(C)): $indCinoAB"))

    sizeA = i->size(A, i)
    sizeB = i->size(B, i)
    sizeC = i->size(C, i)

    csizeA = sizeA.(cindA)
    csizeB = sizeB.(cindB)
    osizeA = sizeA.(oindA)
    osizeB = sizeB.(oindB)

    csizeA == csizeB ||
        throw(DimensionMismatch("non-matching sizes in contracted dimensions"))
    sizeAB = let osize = (osizeA..., osizeB...)
        i->osize[i]
    end
    sizeAB.(indCinoAB) == size(C) ||
        throw(DimensionMismatch("non-matching sizes in uncontracted dimensions"))

    TC = eltype(C)

    CA == :N || CA == :C ||
        throw(ArgumentError("Value of conjA should be :N or :C instead of $CA"))
    CB == :N || CB == :C ||
        throw(ArgumentError("Value of conjB should be :N or :C instead of $CB"))

    opA = (TC <: Real || CA == :N) ? CUTENSOR_OP_IDENTITY : CUTENSOR_OP_CONJ
    opB = (TC <: Real || CB == :N) ? CUTENSOR_OP_IDENTITY : CUTENSOR_OP_CONJ
    opC = CUTENSOR_OP_IDENTITY

    strideA = i->stride(A, i)
    strideB = i->stride(B, i)

    cstrideA = strideA.(cindA)
    cstrideB = strideB.(cindB)
    ostrideA = strideA.(oindA)
    ostrideB = strideB.(oindB)

    descA = CuTensorDescriptor(A; op = opA, size = (osizeA..., csizeA...),
                                    strides = (ostrideA..., cstrideA...))
    descB = CuTensorDescriptor(B; op = opB, size = (osizeB..., csizeB...),
                                    strides = (ostrideB..., cstrideB...))
    descC = CuTensorDescriptor(C)
    T = eltype(C)
    typeCompute = cutensorComputeType(T)
    opOut = CUTENSOR_OP_IDENTITY

    NoA = length(osizeA)
    NoB = length(osizeB)
    Nc = length(csizeA)
    modeoA = ntuple(n->n, NoA)
    modeoB = ntuple(n->NoA+n, NoB)
    modec = ntuple(n->NoA+NoB+n, Nc)

    modeA = collect(Cint, (modeoA..., modec...))
    modeB = collect(Cint, (modeoB..., modec...))
    modeC = collect(Cint, indCinoAB)

    algo = CUTENSOR_ALGO_DEFAULT
    stream = CuDefaultStream()
    pref = CUTENSOR_WORKSPACE_RECOMMENDED

    alignmentRequirementA = Ref{UInt32}(C_NULL)
    cutensorGetAlignmentRequirement(handle(), A, descA, alignmentRequirementA)
    alignmentRequirementB = Ref{UInt32}(C_NULL)
    cutensorGetAlignmentRequirement(handle(), B, descB, alignmentRequirementB)
    alignmentRequirementC = Ref{UInt32}(C_NULL)
    cutensorGetAlignmentRequirement(handle(), C, descC, alignmentRequirementC)
    desc = Ref{cutensorContractionDescriptor_t}()
    cutensorInitContractionDescriptor(handle(),
                                      desc,
                   descA, modeA, alignmentRequirementA[],
                   descB, modeB, alignmentRequirementB[],
                   descC, modeC, alignmentRequirementC[],
                   descC, modeC, alignmentRequirementC[],
                   typeCompute)

    find = Ref{cutensorContractionFind_t}()
    cutensorInitContractionFind(handle(), find, algo)

    @workspace fallback=1<<27 size=@argout(
            cutensorContractionGetWorkspace(handle(), desc, find, pref,
                                            out(Ref{UInt64}(C_NULL)))
        )[] workspace->begin
            plan_ref = Ref{cutensorContractionPlan_t}()
            cutensorInitContractionPlan(handle(), plan_ref, desc, find, sizeof(workspace))

            cutensorContraction(handle(), plan_ref, T[α], A, B, T[β], C, C,
                                workspace, sizeof(workspace), stream)
        end

    return C
end

# overwrite similar_from_indices to return zero initialized arrays
function similar_from_indices(T::Type, ind::IndexTuple, A::CuArray, CA::Symbol)
    sz = similarstructure_from_indices(T, ind, A, CA)
    return fill!(similar(A, T, sz), zero(T))
end
function similar_from_indices(T::Type, poA::IndexTuple, poB::IndexTuple,
                                p1::IndexTuple, p2::IndexTuple,
                                A::CuArray, B::CuArray, CA::Symbol, CB::Symbol)
    sz = similarstructure_from_indices(T, poA, poB, p1, p2, A, B, CA, CB)
    return fill!(similar(A, T, sz), zero(T))
end

# overwrite cached_similar_from_indices in order not to use cache for CuArray objects
function cached_similar_from_indices(sym::Symbol, T::Type, p1::IndexTuple, p2::IndexTuple, A::CuArray, CA::Symbol)
    # also zero fill to avoid problems with cutensorElementwiseBinary
    return similar_from_indices(T, p1, p2, A, CA)
end

function cached_similar_from_indices(sym::Symbol, T::Type, poA::IndexTuple, poB::IndexTuple,
    p1::IndexTuple, p2::IndexTuple, A::CuArray, B::CuArray, CA::Symbol, CB::Symbol)
    # also zero fill to avoid problems with cutensorElementwiseBinary
    return similar_from_indices(T, poA, poB, p1, p2, A, B, CA, CB)
end


text:
############################################
#
#    dolfin.cpp.fem
# https://fenicsproject.org/docs/dolfin/latest/python/_autogenerated/dolfin.cpp.fem.html
#
#    dolfin.fem module
# https://fenicsproject.org/docs/dolfin/2017.2.0/python/programmers-reference/fem/index.html
#
############################################

@pyclass dolfin LinearVariationalProblem
@pyclass dolfin LinearVariationalSolver
@pyclass dolfin NonlinearVariationalProblem
@pyclass dolfin NonlinearVariationalSolver
@pyclass dolfin LocalSolver
@pyclass dolfin DirichletBC
@pyclass dolfin MultiMeshDirichletBC
@pyclass dolfin AutoSubDomain
@pyclass dolfin Assembler
@pyclass dolfin SystemAssembler
@pyclass dolfin MultiMeshAssembler
@pyclass dolfin DofMap
@pyclass dolfin DiscreteOperators
@pyclass dolfin PETScDMCollection
@pyclass dolfin PointSource
@pyclass dolfin SparsityPatternBuilder

@pyfunc dolfin assemble
@pyfunc dolfin assemble_system
@pyfunc dolfin assemble_local
@pyfunc dolfin errornorm
@pyfunc dolfin project
@pyfunc dolfin solve
@pyfunc dolfin adapt
@pyfunc dolfin create_mesh
@pyfunc dolfin dof_to_vertex_map
@pyfunc dolfin get_coordinates
@pyfunc dolfin set_coordinates
@pyfunc dolfin vertex_to_dof_map

export LinearVariationalProblem, LinearVariationalSolver, NonlinearVariationalProblem,
       NonlinearVariationalSolver, LocalSolver, DirichletBC, MultiMeshDirichletBC,
       AutoSubDomain, Assembler, SystemAssembler, MultiMeshAssembler, DofMap,
       DiscreteOperators, PETScDMCollection, PointSource, SparsityPatternBuilder,
       assemble, assemble_system, assemble_local, errornorm, project, solve,
       adapt, create_mesh, dof_to_vertex_map, get_coordinates, set_coordinates,
       vertex_to_dof_map

############################################
#
#    ufl.finiteelement
#
# https://fenicsproject.org/docs/ufl/1.6.0/ufl.finiteelement.html
#
############################################

@pyclass ufl FiniteElementBase
@pyclass ufl FiniteElement FiniteElementBase

@pyclass ufl MixedElement FiniteElementBase
@pyclass ufl VectorElement MixedElement
@pyclass ufl TensorElement MixedElement

@pyclass ufl EnrichedElement FiniteElementBase
@pyclass ufl RestrictedElement FiniteElementBase
@pyclass ufl TensorProductElement FiniteElementBase

# OuterProductElement:  no need to export
# OuterProductElement:  not exported in `ufl`
@pyclass ufl OuterProductElement FiniteElementBase

# 暂时没搞懂，先注释掉
#@pyclass ufl HDiv OuterProductElement
#@pyclass ufl HCurl OuterProductElement

# no need to export
# not exported in `ufl`
@pyclass ufl OuterProductVectorElement MixedElement
@pyclass ufl TraceElement FiniteElementBase

@pyclass ufl BrokenElement FiniteElementBase

@pyfunc ufl FacetElement
@pyfunc ufl InteriorElement

*(fe1::FiniteElementBase, fe2::FiniteElementBase) = FiniteElementBase(fe1.pyobject * fe2.pyobject)

export FiniteElementBase, FiniteElement, MixedElement, VectorElement, TensorElement, EnrichedElement,
        RestrictedElement, TensorProductElement, BrokenElement, FacetElement, InteriorElement

############################################
#
#    dolfin.cpp.adaptivity
#
# https://fenicsproject.org/docs/dolfin/2018.1.0/python/_autogenerated/dolfin.cpp.adaptivity.html?highlight=timeseries#dolfin.cpp.adaptivity.TimeSeries
#
############################################

# no need to export
# not exported in `dolfin` or `ufl`
@pyclass dolfin GoalFunctional Form
@pyclass dolfin ErrorControl Variable
@pyclass dolfin GenericAdaptiveVariationalSolver Variable

@pyclass dolfin TimeSeries Variable
@pyclass dolfin AdaptiveLinearVariationalSolver GenericAdaptiveVariationalSolver
@pyclass dolfin AdaptiveNonlinearVariationalSolver GenericAdaptiveVariationalSolver

export TimeSeries, AdaptiveLinearVariationalSolver, AdaptiveNonlinearVariationalSolver


text:
using GaussianProcesses
using GPR
using Optim
using ConstrainedDynamicsVis
using ConstrainedDynamics
using LineSearches
using Statistics

function _experiment_p2_min(config, id; usesin = false, meandynamics = false)
    traindfs, testdfs = config["datasets"]  # Each thread operates on its own dataset -> no races
    traindf = traindfs.df[id][shuffle(1:nrow(traindfs.df[id]))[1:config["nsamples"]], :]
    testdf = testdfs.df[id][shuffle(1:nrow(testdfs.df[id]))[1:config["testsamples"]], :]
    mechanism = doublependulum2D(1; Δt=0.01, threadlock = config["mechanismlock"])[2]  # Reset Δt to 0.01 in mechanism
    l1, l2 = mechanism.bodies[1].shape.xyz[3], mechanism.bodies[2].shape.xyz[3]

    xtest_future_true = [CState(x) for x in testdf.sfuture]
    # Add noise to the dataset
    for df in [traindf, testdf]
        applynoise!(df, config["Σ"], "P2", config["Δtsim"], l1, l2)
    end
    # Create train and testsets
    xtrain_old = [max2mincoordinates(CState(x), mechanism) for x in traindf.sold]
    if usesin
        xtrain_old = reduce(hcat, [[sin(s[1]), cos(s[1]), s[2], sin(s[3]), cos(s[3]), s[4]] for s in xtrain_old])
    else
        xtrain_old = reduce(hcat, xtrain_old)
    end
    xtrain_curr = [max2mincoordinates(CState(x), mechanism) for x in traindf.scurr]
    ytrain = [[s[id] for s in xtrain_curr] for id in [2,4]]  # ω11, ω21
    xtest_old = [max2mincoordinates(CState(x),mechanism) for x in testdf.sold]

    predictedstates = Vector{CState{Float64,2}}()
    params = config["params"]
    params = [params[1], params[2], params[2], params[3], params[4], params[4], params[5]]
    gps = Vector{GPE}()

    function xtransform(x, _)
        if usesin
            sθ1, cθ1, ω1, sθ2, cθ2, ω2 = x
            θ1, θ2 = atan(sθ1, cθ1), atan(sθ2, cθ2)
        else
            θ1, ω1, θ2, ω2 = x
        end
        q1, q2 = UnitQuaternion(RotX(θ1)), UnitQuaternion(RotX(θ1+θ2))
        x1curr = [0, .5sin(θ1)l1, -.5cos(θ1)l1]
        x2curr = [0, sin(θ1)l1 + .5sin(θ1+θ2)l2, -cos(θ1)l1 - .5cos(θ1+θ2)l2]
        θ1next = θ1 + ω1*0.01
        θ2next = θ2 + ω2*0.01
        x1next = [0, .5sin(θ1next)l1, -.5cos(θ1next)l1]
        x2next = [0, sin(θ1next)l1 + .5sin(θ1next+θ2next)l2, -cos(θ1next)l1 - .5cos(θ1next+θ2next)l2]
        v1 = (x1next - x1curr) / 0.01
        v2 = (x2next - x2curr) / 0.01
        return [x1curr..., q2vec(q1)..., v1..., ω1, 0, 0,
                x2curr..., q2vec(q2)..., v2..., ω1+ω2, 0, 0]
    end

    _getμ(mech) = return [mech.bodies[1].state.ωsol[2][1], mech.bodies[2].state.ωsol[2][1] - mech.bodies[1].state.ωsol[2][1]]
    cache = MDCache()
    for (id, yi) in enumerate(ytrain)
        kernel = SEArd(log.(params[2:end]), log(params[1]))
        mean = meandynamics ? MeanDynamics(mechanism, _getμ, id, cache, xtransform=xtransform) : MeanZero()
        gp = GP(xtrain_old, yi, mean, kernel)
        GaussianProcesses.optimize!(gp, LBFGS(linesearch = BackTracking(order=2)), Optim.Options(time_limit=10.))
        push!(gps, gp)
    end

    for i in 1:length(xtest_old)
        predictedstate = predictdynamicsmin(mechanism, "P2", gps, xtest_old[i], config["simsteps"]; usesin = usesin)
        push!(predictedstates, predictedstate)
    end
    return predictedstates, xtest_future_true
end

function experiment_p2_mz_min(config, id)
    return _experiment_p2_min(config, id, usesin=false, meandynamics=false)
end

function experiment_p2_mz_min_sin(config, id)
    return _experiment_p2_min(config, id, usesin=true, meandynamics=false)
end

function experiment_p2_md_min(config, id)
    return _experiment_p2_min(config, id, usesin=false, meandynamics=true)
end

function experiment_p2_md_min_sin(config, id)
    return _experiment_p2_min(config, id, usesin=true, meandynamics=true)
end


text:
module Regularizers

import PyCall: PyObject, pycall, PyAny

import ..Keras
import ..Keras: PyDoc

const keras_regularizer_classes = [ "Regularizer", "L1L2"]
const keras_regularizer_aliases = [
    "l1",
    "l2",
    "l1_l2",
]

for r in keras_regularizer_classes
    reg_name = Symbol(r)

    @eval begin
        struct $reg_name
            obj::PyObject

            @doc PyDoc(Keras._regularizers, Symbol($r)) function $reg_name(args...; kwargs...)
                new(Keras._regularizers[Symbol($r)](args...; kwargs...))
            end
        end

        # convert(::Type{$(reg_name)}, obj::PyObject) = $reg_name(obj)
        PyObject(reg::$(reg_name)) = reg.obj
        pycall(reg::$(reg_name), args...; kws...) = pycall(reg.obj, args...; kws...)
    end
end

for r in keras_regularizer_aliases
    rf = Symbol(r)

    @eval begin
        @doc PyDoc(Keras._regularizers, Symbol($r)) function $rf(args...; kwargs...)
            return pycall(Keras._regularizers[Symbol($r)], PyAny, args...; kwargs...)
        end
    end
end

end


text:
"""
Used to specify the properties of simple breeders.
"""
type SimpleBreederDefinition <: BreederDefinition

  """
  The selection operator to be used by this breeder.
  """
  selection::SelectionDefinition

  """
  The mutation operator to be used by this breeder.
  """
  mutation::MutationDefinition

  """
  The crossover operator to be used by this breeder.
  """
  crossover::CrossoverDefinition

  SimpleBreederDefinition() = new()
end

"""
Composes a simple breeder for a given species from a provided definition.
"""
compose!(def::SimpleBreederDefinition, s::Species) =
  compose!(linear([def.selection, def.mutation, def.crossover]), s)

"""
Simple breeders operator are composed of a selection operation, followed by a
crossover operation, and then a mutation operation. For most simple problems,
this breeder will suffice.

**Parameters:**

* `selection::Selection`, the selection operator to be used by this breeder.
* `mutation::Mutation`, the mutation operator to be used by this breeder.
* `crossover::Crossover`, the crossover operator to be used by this breeder.
"""
function simple(f::Function)
  b = SimpleBreederDefinition()
  f(b)
  b
end


text:
@doc raw"""
`IODE`: Implicit Ordinary Differential Equation

Defines an implicit initial value problem
```math
\begin{aligned}
\dot{q} (t) &= v(t) , &
q(t_{0}) &= q_{0} , \\
\dot{p} (t) &= f(t, q(t), v(t)) , &
p(t_{0}) &= p_{0} , \\
p(t) &= ϑ(t, q(t), v(t))
\end{aligned}
```
with force field ``f``, the momentum defined by ``p``, initial conditions ``(q_{0}, p_{0})`` and the solution
``(q,p)`` taking values in ``\mathbb{R}^{d} \times \mathbb{R}^{d}``.
This is a special case of a differential algebraic equation with dynamical
variables ``(q,p)`` and algebraic variable ``v``.

### Parameters

* `DT <: Number`: data type
* `TT <: Real`: time step type
* `AT <: AbstractArray{DT}`: array type
* `ϑType <: Function`: type of `ϑ`
* `fType <: Function`: type of `f`
* `gType <: Function`: type of `g`
* `v̄Type <: Function`: type of `v̄`
* `f̄Type <: Function`: type of `f̄`
* `hType <: OptionalFunction`: type of `h`
* `pType <: Union{NamedTuple,Nothing}`: parameters type

### Fields

* `d`: dimension of dynamical variables ``q`` and ``p`` as well as the vector fields ``f`` and ``p``
* `ϑ`: function determining the momentum
* `f`: function computing the vector field
* `g`: function determining the projection, given by ``\nabla \vartheta (q) \cdot \lambda``
* `v̄`: function computing an initial guess for the velocity field ``v`` (optional)
* `f̄`: function computing an initial guess for the force field ``f`` (optional)
* `h`: function computing the Hamiltonian (optional)
* `t₀`: initial time (optional)
* `q₀`: initial condition for `q`
* `p₀`: initial condition for `p`
* `parameters`: either a `NamedTuple` containing the equations parameters or `nothing`
* `periodicity`: determines the periodicity of the state vector `q` for cutting periodic solutions

The functions `ϑ` and `f` must have the interface
```julia
    function ϑ(t, q, v, p)
        p[1] = ...
        p[2] = ...
        ...
    end
```
and
```julia
    function f(t, q, v, f)
        f[1] = ...
        f[2] = ...
        ...
    end
```
where `t` is the current time, `q` is the current solution vector, `v` is the
current velocity and `f` and `p` are the vectors which hold the result of
evaluating the functions ``f`` and ``ϑ`` on `t`, `q` and `v`.
In addition, the functions `g`, `v̄` and `f̄` are specified by
```julia
    function g(t, q, λ, g)
        g[1] = ...
        g[2] = ...
        ...
    end

    function v̄(t, q, v)
        v[1] = ...
        v[2] = ...
        ...
    end

    function f̄(t, q, v, f)
        f[1] = ...
        f[2] = ...
        ...
    end
```
The function `g` is used in projection methods that enforce ``p = ϑ(q)``.
The functions `v̄` and `f̄` are used for initial guesses in nonlinear implicit solvers.

### Constructors

```julia
IODE(ϑ, f, v̄, f̄, t₀, q₀, p₀, λ₀, invariants, parameters, periodicity)

IODE(ϑ, f, t₀, q₀::StateVector, p₀::StateVector, λ₀::StateVector=zero(q₀); kwargs...)
IODE(ϑ, f, q₀::StateVector, p₀::StateVector, λ₀::StateVector=zero(q₀); kwargs...)
IODE(ϑ, f, t₀, q₀::State, p₀::State, λ₀::StateVector=zero(q₀); kwargs...)
IODE(ϑ, f, q₀::State, p₀::State, λ₀::StateVector=zero(q₀); kwargs...)
```

### Keyword arguments

* `v̄ = (t,q,v) -> nothing`
* `f̄ = f`
* `invariants = nothing`
* `parameters = nothing`
* `periodicity = nothing`

"""
struct IODE{ϑType <: Callable, fType <: Callable, gType <: Callable,
            v̄Type <: Callable, f̄Type <: Callable,
            invType <: OptionalInvariants,
            parType <: OptionalParameters,
            perType <: OptionalPeriodicity} <: AbstractEquationPODE{invType,parType,perType}

    ϑ::ϑType
    f::fType
    g::gType
    v̄::v̄Type
    f̄::f̄Type

    invariants::invType
    parameters::parType
    periodicity::perType

    function IODE(ϑ, f, g, v̄, f̄, invariants, parameters, periodicity)
        new{typeof(ϑ), typeof(f), typeof(g), typeof(v̄), typeof(f̄),
            typeof(invariants), typeof(parameters), typeof(periodicity)}(
                ϑ, f, g, v̄, f̄, invariants, parameters, periodicity)
    end
end

_iode_default_v̄(t,q,v,params) = nothing

IODE(ϑ, f, g; invariants=NullInvariants(), parameters=NullParameters(), periodicity=NullPeriodicity(), v̄=_iode_default_v̄, f̄=f) = IODE(ϑ, f, g, v̄, f̄, invariants, parameters, periodicity)

GeometricBase.invariants(equation::IODE) = equation.invariants
GeometricBase.parameters(equation::IODE) = equation.parameters
GeometricBase.periodicity(equation::IODE) = equation.periodicity

hasvectorfield(::IODE) = true

function check_initial_conditions(::IODE, ics::NamedTuple)
    haskey(ics, :q) || return false
    haskey(ics, :p) || return false
    haskey(ics, :λ) || return false
    eltype(ics.q) == eltype(ics.p) == eltype(ics.λ) || return false
    typeof(ics.q) == typeof(ics.p) == typeof(ics.λ) || return false
    axes(ics.q) == axes(ics.p) == axes(ics.λ) || return false
    return true
end

function check_methods(equ::IODE, tspan, ics::NamedTuple, params)
    applicable(equ.ϑ, tspan[begin], ics.q, zero(ics.q), zero(ics.p), params) || return false
    applicable(equ.f, tspan[begin], ics.q, zero(ics.q), zero(ics.p), params) || return false
    applicable(equ.g, tspan[begin], ics.q, zero(ics.q), zero(ics.p), params) || return false
    return true
end

function datatype(equ::IODE, ics::NamedTuple)
    @assert check_initial_conditions(equ, ics)
    return eltype(ics.q)
end

function arrtype(equ::IODE, ics::NamedTuple)
    @assert check_initial_conditions(equ, ics)
    typeof(ics.q)
end

_get_ϑ(equ::IODE, params) = (t,q,v,ϑ) -> equ.ϑ(t, q, v, ϑ, params)
_get_f(equ::IODE, params) = (t,q,v,f) -> equ.f(t, q, v, f, params)
_get_g(equ::IODE, params) = (t,q,v,g) -> equ.g(t, q, v, g, params)
_get_v̄(equ::IODE, params) = (t,q,v) -> equ.v̄(t, q, v, params)
_get_f̄(equ::IODE, params) = (t,q,v,f) -> equ.f̄(t, q, v, f, params)

_functions(equ::IODE) = (ϑ = equ.ϑ, f = equ.f, g = equ.g, v̄ = equ.v̄, f̄ = equ.f̄)
_functions(equ::IODE, params::OptionalParameters) = (ϑ = _get_ϑ(equ, params),
                                                     f = _get_f(equ, params),
                                                     g = _get_g(equ, params),
                                                     v̄ = _get_v̄(equ, params),
                                                     f̄ = _get_f̄(equ, params))


text:
using ParameterInference
using NonstationaryProcesses
using Plots
using Catch22
fourseas!()

# * Define a path in parameter space for an AR system
N = 1000000
a = sineWave((pa = (N, 0.6, 0, 0))...)
plot(0:N, a)
b = sineWave((pb = (N, 0.6, -N÷4, 0))...)
plot!(0:N, b)

S = arSim(parameter_profiles = (sineWave, sineWave),
          parameters = (pa, pb),
          tmax = N,
          transient_t0 = 0,
          t0 = 0,
          X0 = [0.0]) # Specifying 1 initial condition returns a univariate time series.

@userplot FeatureSpaceImage
@recipe function f(g::FeatureSpaceImage; var=1, lowdim=principalcomponents, nwindows=50, colors=[:cornflowerblue, :crimson])
    @assert g.args[1] isa Process
    S = g.args[1]
    if length(g.args) == 2
        f = g.args[2]
    else
        f = catch22
    end
    layout := (1, 2)
    p = parameterseries(S)
    t = times(S)
    x = timeseries(S, var)
    X, _ = slidingWindow(x, length(t)÷nwindows)
    F = f(X)
    if size(F, 1) > 2 # Do PCA
        m = F |> Array |> lowdim
        F = embed(m, F, 1:2)
    end
    aspect_ratio --> :equal
    arrow --> arrow(:closed, :head, 30.0, 20.0)
    size --> (800, 400)
    bottom_margin --> 0.5Plots.cm
    left_margin --> 0.5Plots.cm
    narrows = 4
    for nn = 1:narrows
        Nn = length(t)÷narrows
        if nn == narrows
            nx = Nn*(nn-1)+1:length(t)
        else
            nx = Nn*(nn-1)+1:Nn*nn
        end
        @series begin
            subplot := 1
            title := "Parameter space"
            seriescolor --> colors[1]
            titlefontsize --> 16
            xguide --> "\$\\theta_1\$"
            yguide --> "\$\\theta_2\$"
            linealpha --> 0.75
            seriestype --> :path
            markersize --> 2
            markercolor --> colors[1]
            x := p[1, nx]
            y := p[2, nx]
            xlims := [minimum(p[1, :])-0.2, maximum(p[1, :])+0.2]
            ylims := [minimum(p[2, :])-0.2, maximum(p[2, :])+0.2]
            ()
        end
        Nn = size(F, 2)÷narrows
        if nn == narrows
            nx = Nn*(nn-1)+1:size(F, 2)
        else
            nx = Nn*(nn-1)+1:Nn*nn+1
        end
        @series begin
            subplot := 2
            aspect_ratio := :auto
            seriescolor --> colors[2]
            seriestype --> :path
            linealpha --> 0.75
            x := F[1, nx]
            y := F[2, nx]
            ()
        end
    end
    @series begin
        subplot := 2
        aspect_ratio := :auto
        arrow := nothing
        title := "Feature space"
        seriescolor --> colors[2]
        titlefontsize --> 16
        xguide --> "\$f_1\$"
        yguide --> "\$f_2\$"
        markeralpha --> 0.75
        seriestype --> :scatter
        linealpha --> 0.5
        markersize --> 2.5
        markerstrokewidth --> 0.01
        x := F[1, :]
        y := F[2, :]
        xlims := [minimum(F[1, :])-0.2, maximum(F[1, :])+0.2]
        ylims := [minimum( F[2, :])-0.2, maximum( F[2, :])+0.2]
        ()
    end
end

featurespaceimage(S, AC[1:2], colors=[:black, :black]);
savefig("../Figures/$(rand(UInt16)).svg");
l = length(timeseries(S, 1))
n = round(Int, 2*8/3)
plot(vec(timeseries(S, 1))[n*l÷8+1:n*l÷8+251], color=:black);
savefig("../Figures/$(rand(UInt16)).svg");

SS = arSim(parameter_profiles = (constant,),
          parameters = (0.97),
          tmax = 250,
          transient_t0 = 0,
          t0 = 0,
          X0 = [0.0])
plot(SS)
savefig("../Figures/$(rand(UInt16)).svg");

SS = arSim(parameter_profiles = (constant,),
          parameters = (0.03),
          tmax = 250,
          transient_t0 = 0,
          t0 = 0,
          X0 = [0.0])
plot(SS)
savefig("../Figures/$(rand(UInt16)).svg");

SSS = updateparam(ikedaSim(), 4, 0.6)
plot(timeseries(SSS, 1)[1:150])
savefig("../Figures/$(rand(UInt16)).svg");

SSS = updateparam(ikedaSim(), 1, 25)
plot(timeseries(SSS, 1)[1:150])
savefig("../Figures/$(rand(UInt16)).svg");


text:
module Zip

using ZipFile

function unzip(callback,src)
    r = ZipFile.Reader(src);
    try
        for f in r.files
            callback(f);
        end
        return true
    catch e
        throw(e)
    finally
        close(r)
    end
end

function newdir(path)
    if isfile(path)
        throw(ErrorException("Failed to create directory; $path is a file."))
    end
    if !isdir(path)
        mkpath(path)
    end
end

entry_exists(path) = isfile(path) || isdir(path)

function extract(src,dst,delete_existing::Bool=true)
    newdir(dst)
    unzip(src) do file
        path = joinpath(dst,file.name)
        if delete_existing && entry_exists(path)
            rm(path,force=true)
        end
        needed_dirs,_ = splitdir(path)
        newdir(needed_dirs)
        write(path,file)
    end
end

export unzip,extract

end

max_stars_repo_name: BirdClef/birdclef

max_issues_repo_name: BirdClef/birdclef

max_forks_repo_name: BirdClef/birdclef


text:
module AST
using MLStyle
using MLStyle.Render
using MLStyle.Err
include("AST.Compat.jl")
export @matchast, @capture

function matchast(target, actions, source, mod::Module)
    stmts = @match actions begin
       Expr(:quote, quote $(stmts...) end) => stmts

       _ => begin
            msg = "Malformed ast template, the second arg should be a block with a series of pairs(`a => b`), at $(string(source))."
            throw(SyntaxError(msg))
        end
    end
    last_lnode = source
    map(stmts) do stmt
        @match stmt begin
            ::LineNumberNode => (last_lnode = stmt)
            :($a => $b) => :($(Expr(:quote, a)) => $b)
            _ => throw(SyntaxError("Malformed ast template, should be formed as `a => b`, at $(string(last_lnode))."))
        end
    end |> actions ->
    gen_match(target, Expr(:block, actions...), source, mod)
end

"""
An eye candy of `@match` for AST matching.

e.g.,

```julia
    @matchast :(1 + 1) quote
        \$a + 1 => a
    end # 1

    @matchast :(f(a, b)) quote
        \$(Expr(:call, :f, :a, :b)) =>
         dosomething
    end
```
"""
macro matchast(template, actions)
    matchast(template, actions, __source__, __module__) |> esc
end

"""
@capture template
@capture template expr

Template matching for expressions.

```julia
julia> @capture f(\$x)  :(f(2))
Dict{Symbol,Int64} with 1 entry:
  :x => 2
```

If the template doesn't match input AST, return `nothing`.
"""
:(@capture)

macro capture(template)
    capture(template, __source__, __module__) |> esc
end

macro capture(template, ex)
    Expr(:call, capture(template, __source__, __module__), ex) |> esc
end

function capture(template, source, mod::Module)
    out_expr = @static VERSION < v"1.1.0" ?
        begin
            syms = Set(Symbol[])
            capturing_analysis(template, syms, true)
            Expr(:call, Dict, (Expr(:call, =>, QuoteNode(each), each) for each in syms)...)
        end :
        :($Base.@locals)

    arg_sym = gensym()
    let template = Expr(:quote, template),
        actions = Expr(:block, :($template => $out_expr), :(_ => nothing)),
        match_gen = gen_match(arg_sym, actions, source, mod)
        @format [arg_sym, match_gen] quote
            function (arg_sym)
                match_gen
            end
        end
    end
end

end


text:
# ISDF
import Random: randperm

"""
    ISDF type

Stores information on interpolations vectors and interpolated values.
The arrays `ζ_ij` and `u_ij` are chosen such that approximately
`u_i u_j ≈ ζ_ij * u_i_ij u_j_ij`.
"""
struct ISDF
    N_μ_vv
    N_μ_cc
    N_μ_vc
    r_μ_vv_indices
    r_μ_cc_indices
    r_μ_vc_indices
    u_v_vv
    u_c_cc
    u_v_vc
    u_c_vc
    ζ_vv
    ζ_cc
    ζ_vc
end

# abstract type AbstractInterpolationMethod
# end

# struct UniformInterpolation <: AbstractInterpolationMethod

"""
    size(isdf)

Return the size as tuple (N_μ_v, N_μ_c, N_μ_vc).
"""
function size(isdf::ISDF)
    return (size(isdf.u_v_vv, 1), size(isdf.u_c_cc, 1), size(
    isdf.u_v_vc, 1))
end

"""
    interpolation_vectors(isdf)

Returns a 3-tuple of interpolation vectors of sizes `(N_r, N_μ_v)`, `(N_r, N_μ_c)`, and `(N_r, N_μ_vc)`.
"""
function interpolation_vectors(isdf::ISDF)
    return isdf.ζ_vv, isdf.ζ_cc, isdf.ζ_vc
end

"""
    interpolation_coefficients(isdf)

Returns a 4-tuple of interpolation coefficients of sizes `(N_μ_v, N_v, N_k)`, `(N_μ_c, N_c, N_k)`, `(N_μ_vc, N_v, N_k)` and `(N_μ_vc, N_c, N_k)`.
"""
function interpolation_coefficients(isdf::ISDF)
    return isdf.u_v_vv, isdf.u_c_cc, isdf.u_v_vc, isdf.u_c_vc
end

function ISDF(prob::AbstractBSEProblem, r_μ_vv_indices::AbstractVector, r_μ_cc_indices::AbstractVector, r_μ_vc_indices::AbstractVector)
    u_v, u_c = orbitals(prob)

    ζ_vv = assemble_ζ(u_v, r_μ_vv_indices)
    ζ_cc = assemble_ζ(u_c, r_μ_cc_indices)
    ζ_vc = assemble_ζ(u_v, u_c, r_μ_vc_indices)

    return ISDF(length(r_μ_vv_indices), length(r_μ_cc_indices), length(r_μ_vc_indices),
        r_μ_vv_indices, r_μ_cc_indices, r_μ_vc_indices,
        u_v[r_μ_vv_indices, :, :], u_c[r_μ_cc_indices, :, :],
        u_v[r_μ_vc_indices, :, :], u_c[r_μ_vc_indices, :, :],
        ζ_vv, ζ_cc, ζ_vc)
end

function ISDF(prob::AbstractBSEProblem, N_μ_vv::Int, N_μ_cc::Int, N_μ_vc::Int)
    N_v, N_c, N_k = size(prob)
    N_sub_max = 30

    N_sub_vv = min(N_sub_max, N_v * N_k)
    N_sub_cc = min(N_sub_max, N_c * N_k)
    N_sub_vc = min(N_sub_max^2, N_v * N_c * N_k)

    r_μ_vv_indices = find_r_μ(prob.u_v, N_μ_vv, N_sub_vv)
    r_μ_cc_indices = find_r_μ(prob.u_c, N_μ_cc, N_sub_cc)
    r_μ_vc_indices = find_r_μ(prob.u_v, prob.u_c, N_μ_vc, N_sub_vc)

    return ISDF(prob, r_μ_vv_indices, r_μ_cc_indices, r_μ_vc_indices)
end

"""
    find_r_μ(u_i, N_μ, N_sub)

Return an array of indices corresponding to interpolation
points in the unit cell. The points are computed via the algorithm proposed in
Lu, Ying; 2016; Fast Allgorithm for periodic Fitting for Bloch Waves
"""
function find_r_μ(u_i, N_μ, N_sub)
    return qrcp(u_i, N_sub).p[1:N_μ]
end
function qrcp(u_i, N_sub)
    N_r, N_i, N_k = size(u_i)

    random_phase = rand(MersenneTwister(42), N_i * N_k)
    random_unit_complex = cos.(2 .* pi .* random_phase) .+ im * sin.(2 .* pi .* random_phase)
    u_i_r_transformed = zeros(Complex{Float64}, N_i * N_k)
    sub_ind = randperm(MersenneTwister(42), N_i * N_k)[1:N_sub]
    M = zeros(Complex{Float64}, N_sub^2, N_r)
    for ir in 1:N_r
        u_i_r_transformed[:] .= random_unit_complex .* vec(u_i[ir, :, :])
        fft!(u_i_r_transformed)
        M[:, ir] = vec(conj.(reshape(u_i_r_transformed[sub_ind], :, 1)) .* reshape(u_i_r_transformed[sub_ind], 1, :))
    end
    F = qr(M, Val(true))

    return F
end

function find_r_μ(u_v, u_c, N_μ, N_sub)
    return qrcp(u_v, u_c, N_sub).p[1:N_μ]
end
function qrcp(u_v, u_c, N_sub)
    N_r, N_v, N_k = size(u_v)
    N_r, N_c, N_k = size(u_c)

    random_phase = rand(MersenneTwister(42), N_v * N_c * N_k)
    random_unit_complex = cos.(2 .* pi .* random_phase) .+ im * sin.(2 .* pi .* random_phase)
    u_vc_r_transformed = zeros(Complex{Float64}, N_v * N_c * N_k)
    sub_ind = randperm(MersenneTwister(42), N_v * N_c * N_k)[1:N_sub]
    M = zeros(Complex{Float64}, N_sub, N_r)
    for ir in 1:N_r
        u_vc_r_transformed[:] .= random_unit_complex .* vec(conj.(reshape(u_v[ir, :, :], N_v, 1, N_k)) .* reshape(u_c[ir, :, :], 1, N_c, N_k))
        fft!(u_vc_r_transformed)
        M[:, ir] = u_vc_r_transformed[sub_ind]
    end
    F = qr(M, Val(true))

    return F
end

function assemble_ζ(u_i, r_μ_indices)
    N_unit, N_i, N_k = size(u_i)
    U_i = reshape(u_i, N_unit, N_i * N_k)
    P_i = conj.(U_i * U_i[r_μ_indices, :]')
    P_ii = abs2.(P_i)
    A = P_ii[:, :]
    B = P_ii[r_μ_indices, :]
    ζ = copy((qr(B', Val(true)) \ A')')
    return ζ
end

function assemble_ζ(u_i, u_j, r_μ_indices)
    N_unit, N_i, N_k = size(u_i)
    N_unit, N_j, N_k = size(u_j)
    U_i = reshape(u_i, N_unit, N_i * N_k)
    U_j = reshape(u_j, N_unit, N_j * N_k)
    P_i = conj.(U_i * U_i[r_μ_indices, :]')
    P_j = conj.(U_j * U_j[r_μ_indices, :]')
    P_ij = P_j .* conj(P_i)
    A = P_ij[:, :]
    B = P_ij[r_μ_indices, :]
    ζ = copy((qr(B', Val(true)) \ A')')
    return ζ
end

# routines for estimating errors

function isdf_error(prob, isdf)
    error_M_vv = isdf_error(prob.u_v, isdf.ζ_vv, isdf.r_μ_vv_indices)
    error_M_cc = isdf_error(prob.u_c, isdf.ζ_cc, isdf.r_μ_cc_indices)
    error_M_vc = isdf_error(prob.u_v, prob.u_c, isdf.ζ_vc, isdf.r_μ_vc_indices)
    return error_M_vv, error_M_cc, error_M_vc
end

"""
should be equivalent to

    M_i = assemble_M(u_i)
    norm(M_i - ζ * M_i[r_μ_indices, :]) / norm(M_i)
"""
function isdf_error(u_i, ζ, r_μ_indices)
    N_unit, N_i, N_k = size(u_i)
    error2 = 0.0
    normalization2 = 0.0
    col = zeros(Complex{Float64}, N_unit)
    for ii in 1:N_i, ik in 1:N_k, jj in 1:N_i, jk in 1:N_k
        @views col[:] .= u_i[:, jj, jk] .* conj.(u_i[:, ii, ik])
        normalization2 += norm(col)^2
        error2 += norm(col - ζ * col[r_μ_indices])^2
    end

    return sqrt(error2 / normalization2)
end

function isdf_error(u_v, u_c, ζ, r_μ_indices)
    N_unit, N_c, N_k = size(u_c)
    N_unit, N_v, N_k = size(u_v)
    error2 = 0.0
    normalization2 = 0.0
    col = zeros(Complex{Float64}, N_unit)
    for iv in 1:N_v, ic in 1:N_c, ik in 1:N_k
        @views col[:] .= u_c[:, ic, ik] .* conj.(u_v[:, iv, ik])
        normalization2 += norm(col)^2
        error2 += norm(col - ζ * col[r_μ_indices])^2
    end

    return sqrt(error2 / normalization2)
end

function estimate_error(prob, isdf, N_k_samples = 20)
    error_M_vv = isdf_error_estimate(prob.u_v, isdf.ζ_vv, isdf.r_μ_vv_indices, N_k_samples)
    error_M_cc = isdf_error_estimate(prob.u_c, isdf.ζ_cc, isdf.r_μ_cc_indices, N_k_samples)
    error_M_vc = isdf_error_estimate(prob.u_v, prob.u_c, isdf.ζ_vc, isdf.r_μ_vc_indices, N_k_samples)
    return error_M_vv, error_M_cc, error_M_vc
end

function isdf_error_estimate(u_i, ζ, r_μ_indices, N_k_samples)
    N_unit, N_i, N_k = size(u_i)
    rng = MersenneTwister(0)
    ik_samples = rand(rng, 1:N_k, N_k_samples)
    error2 = 0.0
    normalization2 = 0.0
    col = zeros(Complex{Float64}, N_unit)
    for ii in 1:N_i, ik in ik_samples, jj in 1:N_i, jk in ik_samples
        @views col[:] .= u_i[:, jj, jk] .* conj.(u_i[:, ii, ik])
        normalization2 += norm(col)^2
        error2 += norm(col - ζ * col[r_μ_indices])^2
    end

    return sqrt(error2 / normalization2)
end

function isdf_error_estimate(u_v, u_c, ζ, r_μ_indices, N_k_samples)
    N_unit, N_c, N_k = size(u_c)
    N_unit, N_v, N_k = size(u_v)
    rng = MersenneTwister(0)
    ik_samples = rand(rng, 1:N_k, N_k_samples)
    error2 = 0.0
    normalization2 = 0.0
    col = zeros(Complex{Float64}, N_unit)
    for iv in 1:N_v, ic in 1:N_c, ik in ik_samples
        @views col[:] .= u_c[:, ic, ik] .* conj.(u_v[:, iv, ik])
        normalization2 += norm(col)^2
        error2 += norm(col - ζ * col[r_μ_indices])^2
    end

    return sqrt(error2 / normalization2)
end