text:
#==============================================================================#
# EFS.jl
#
# This file is generated from:
# https://github.com/aws/aws-sdk-js/blob/master/apis/elasticfilesystem-2015-02-01.normal.json
#==============================================================================#

__precompile__()

module EFS

using AWSCore

"""
    using AWSSDK.EFS.create_file_system
    create_file_system([::AWSConfig], arguments::Dict)
    create_file_system([::AWSConfig]; CreationToken=, <keyword arguments>)

    using AWSCore.Services.elasticfilesystem
    elasticfilesystem([::AWSConfig], "POST", "/2015-02-01/file-systems", arguments::Dict)
    elasticfilesystem([::AWSConfig], "POST", "/2015-02-01/file-systems", CreationToken=, <keyword arguments>)

# CreateFileSystem Operation

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.

**Note**
> 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.

**Note**
> 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](@ref) operation, which among other things returns the file system state.

This operation also takes 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](http://docs.aws.amazon.com/efs/latest/ug/performance.html#performancemodes.html).

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](@ref). You mount your Amazon EFS file system on an EC2 instances in your VPC via the mount target. For more information, see [Amazon EFS: How it Works](http://docs.aws.amazon.com/efs/latest/ug/how-it-works.html).

This operation requires permissions for the `elasticfilesystem:CreateFileSystem` action.

# Arguments

## `CreationToken = ::String` -- *Required*
String of up to 64 ASCII characters. Amazon EFS uses this to ensure idempotent creation.

## `PerformanceMode = "generalPurpose" or "maxIO"`
The `PerformanceMode` 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. This can't be changed after the file system has been created.

## `Encrypted = ::Bool`
A Boolean value that, if true, creates an encrypted file system. When creating an encrypted file system, you have the option of specifying a [CreateFileSystemRequest\$KmsKeyId](@ref) 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 = ::String`
The ID of the AWS KMS CMK to be used to protect the encrypted file system. This parameter is only required if you want to use a non-default CMK. 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 [CreateFileSystemRequest\$Encrypted](@ref) parameter must be set to true.

## `ThroughputMode = "bursting" or "provisioned"`
The throughput mode for the file system to be created. There are two throughput modes to choose from for your file system: bursting and provisioned. 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.

## `ProvisionedThroughputInMibps = double`
The throughput, measured in MiB/s, that you want to provision for a file system that you're creating. The limit on throughput is 1024 MiB/s. You can get these limits increased by contacting AWS Support. For more information, see [Amazon EFS Limits That You Can Increase](http://docs.aws.amazon.com/efs/latest/ug/limits.html#soft-limits) in the *Amazon EFS User Guide.*

# Returns

`FileSystemDescription`

# Exceptions

`BadRequest`, `InternalServerError`, `FileSystemAlreadyExists`, `FileSystemLimitExceeded`, `InsufficientThroughputCapacity` or `ThroughputLimitExceeded`.

# Example: To create a new file system

This operation creates a new file system with the default generalpurpose performance mode.

Input:
```
[
    "CreationToken" => "tokenstring",
    "PerformanceMode" => "generalPurpose"
]
```

Output:
```
Dict(
    "CreationTime" => "1481841524.0",
    "CreationToken" => "tokenstring",
    "FileSystemId" => "fs-01234567",
    "LifeCycleState" => "creating",
    "NumberOfMountTargets" => 0,
    "OwnerId" => "012345678912",
    "PerformanceMode" => "generalPurpose",
    "SizeInBytes" => Dict(
        "Value" => 0
    )
)
```

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/elasticfilesystem-2015-02-01/CreateFileSystem)
"""
@inline create_file_system(aws::AWSConfig=default_aws_config(); args...) = create_file_system(aws, args)

@inline create_file_system(aws::AWSConfig, args) = AWSCore.Services.elasticfilesystem(aws, "POST", "/2015-02-01/file-systems", args)

@inline create_file_system(args) = create_file_system(default_aws_config(), args)

"""
    using AWSSDK.EFS.create_mount_target
    create_mount_target([::AWSConfig], arguments::Dict)
    create_mount_target([::AWSConfig]; FileSystemId=, SubnetId=, <keyword arguments>)

    using AWSCore.Services.elasticfilesystem
    elasticfilesystem([::AWSConfig], "POST", "/2015-02-01/mount-targets", arguments::Dict)
    elasticfilesystem([::AWSConfig], "POST", "/2015-02-01/mount-targets", FileSystemId=, SubnetId=, <keyword arguments>)

# CreateMountTarget Operation

Creates a mount target for a file system. You can then mount the file system on EC2 instances via 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. For more information, see [Amazon EFS: How it Works](http://docs.aws.amazon.com/efs/latest/ug/how-it-works.html).

In the request, you also specify a file system ID for which you are creating the mount target and the file system's lifecycle state must be `available`. For more information, see [DescribeFileSystems](@ref).

In the request, you also provide a subnet ID, which determines the following:

*   VPC in which Amazon EFS creates the mount target

*   Availability Zone in which Amazon EFS creates the mount target

*   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 via the mount target can resolve the mount target's DNS name to its IP address. For more information, see [How it Works: Implementation Overview](http://docs.aws.amazon.com/efs/latest/ug/how-it-works.html#how-it-works-implementation).

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.

**Note**
> 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](@ref) operation, which among other things returns the mount target state.

We recommend 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](http://aws.amazon.com/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 won't be able to 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

## `FileSystemId = ::String` -- *Required*
ID of the file system for which to create the mount target.

## `SubnetId = ::String` -- *Required*
ID of the subnet to add the mount target in.

## `IpAddress = ::String`
Valid IPv4 address within the address range of the specified subnet.

## `SecurityGroups = [::String, ...]`
Up to five VPC security group IDs, of the form `sg-xxxxxxxx`. These must be for the same VPC as subnet specified.

# Returns

`MountTargetDescription`

# Exceptions

`BadRequest`, `InternalServerError`, `FileSystemNotFound`, `IncorrectFileSystemLifeCycleState`, `MountTargetConflict`, `SubnetNotFound`, `NoFreeAddressesInSubnet`, `IpAddressInUse`, `NetworkInterfaceLimitExceeded`, `SecurityGroupLimitExceeded`, `SecurityGroupNotFound` or `UnsupportedAvailabilityZone`.

# Example: To create a new mount target

This operation creates a new mount target for an EFS file system.

Input:
```
[
    "FileSystemId" => "fs-01234567",
    "SubnetId" => "subnet-1234abcd"
]
```

Output:
```
Dict(
    "FileSystemId" => "fs-01234567",
    "IpAddress" => "192.0.0.2",
    "LifeCycleState" => "creating",
    "MountTargetId" => "fsmt-12340abc",
    "NetworkInterfaceId" => "eni-cedf6789",
    "OwnerId" => "012345678912",
    "SubnetId" => "subnet-1234abcd"
)
```

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/elasticfilesystem-2015-02-01/CreateMountTarget)
"""
@inline create_mount_target(aws::AWSConfig=default_aws_config(); args...) = create_mount_target(aws, args)

@inline create_mount_target(aws::AWSConfig, args) = AWSCore.Services.elasticfilesystem(aws, "POST", "/2015-02-01/mount-targets", args)

@inline create_mount_target(args) = create_mount_target(default_aws_config(), args)

"""
    using AWSSDK.EFS.create_tags
    create_tags([::AWSConfig], arguments::Dict)
    create_tags([::AWSConfig]; FileSystemId=, Tags=)

    using AWSCore.Services.elasticfilesystem
    elasticfilesystem([::AWSConfig], "POST", "/2015-02-01/create-tags/{FileSystemId}", arguments::Dict)
    elasticfilesystem([::AWSConfig], "POST", "/2015-02-01/create-tags/{FileSystemId}", FileSystemId=, Tags=)

# CreateTags Operation

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](@ref) operation.

This operation requires permission for the `elasticfilesystem:CreateTags` action.

# Arguments

## `FileSystemId = ::String` -- *Required*
ID of the file system whose tags you want to modify (String). This operation modifies the tags only, not the file system.

## `Tags = [[ ... ], ...]` -- *Required*
Array of `Tag` objects to add. Each `Tag` object is a key-value pair.
```
 Tags = [[
        "Key" => <required> ::String,
        "Value" => <required> ::String
    ], ...]
```

# Exceptions

`BadRequest`, `InternalServerError` or `FileSystemNotFound`.

# Example: To create a new tag

This operation creates a new tag for an EFS file system.

Input:
```
[
    "FileSystemId" => "fs-01234567",
    "Tags" => [
        [
            "Key" => "Name",
            "Value" => "MyFileSystem"
        ]
    ]
]
```

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/elasticfilesystem-2015-02-01/CreateTags)
"""
@inline create_tags(aws::AWSConfig=default_aws_config(); args...) = create_tags(aws, args)

@inline create_tags(aws::AWSConfig, args) = AWSCore.Services.elasticfilesystem(aws, "POST", "/2015-02-01/create-tags/{FileSystemId}", args)

@inline create_tags(args) = create_tags(default_aws_config(), args)

"""
    using AWSSDK.EFS.delete_file_system
    delete_file_system([::AWSConfig], arguments::Dict)
    delete_file_system([::AWSConfig]; FileSystemId=)

    using AWSCore.Services.elasticfilesystem
    elasticfilesystem([::AWSConfig], "DELETE", "/2015-02-01/file-systems/{FileSystemId}", arguments::Dict)
    elasticfilesystem([::AWSConfig], "DELETE", "/2015-02-01/file-systems/{FileSystemId}", FileSystemId=)

# DeleteFileSystem Operation

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](@ref) and [DeleteMountTarget](@ref).

**Note**
> The `DeleteFileSystem` call returns while the file system state is still `deleting`. You can check the file system deletion status by calling the [DescribeFileSystems](@ref) 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](@ref) returns a `404 FileSystemNotFound` error.

This operation requires permissions for the `elasticfilesystem:DeleteFileSystem` action.

# Arguments

## `FileSystemId = ::String` -- *Required*
ID of the file system you want to delete.

# Exceptions

`BadRequest`, `InternalServerError`, `FileSystemNotFound` or `FileSystemInUse`.

# Example: To delete a file system

This operation deletes an EFS file system.

Input:
```
[
    "FileSystemId" => "fs-01234567"
]
```

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/elasticfilesystem-2015-02-01/DeleteFileSystem)
"""
@inline delete_file_system(aws::AWSConfig=default_aws_config(); args...) = delete_file_system(aws, args)

@inline delete_file_system(aws::AWSConfig, args) = AWSCore.Services.elasticfilesystem(aws, "DELETE", "/2015-02-01/file-systems/{FileSystemId}", args)

@inline delete_file_system(args) = delete_file_system(default_aws_config(), args)

"""
    using AWSSDK.EFS.delete_mount_target
    delete_mount_target([::AWSConfig], arguments::Dict)
    delete_mount_target([::AWSConfig]; MountTargetId=)

    using AWSCore.Services.elasticfilesystem
    elasticfilesystem([::AWSConfig], "DELETE", "/2015-02-01/mount-targets/{MountTargetId}", arguments::Dict)
    elasticfilesystem([::AWSConfig], "DELETE", "/2015-02-01/mount-targets/{MountTargetId}", MountTargetId=)

# DeleteMountTarget Operation

Deletes the specified mount target.

This operation forcibly breaks any mounts of the file system via 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 may 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 via another mount target.

This operation requires permissions for the following action on the file system:

*   `elasticfilesystem:DeleteMountTarget`

**Note**
> The `DeleteMountTarget` call returns while the mount target state is still `deleting`. You can check the mount target deletion by calling the [DescribeMountTargets](@ref) 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

## `MountTargetId = ::String` -- *Required*
ID of the mount target to delete (String).

# Exceptions

`BadRequest`, `InternalServerError`, `DependencyTimeout` or `MountTargetNotFound`.

# Example: To delete a mount target

This operation deletes a mount target.

Input:
```
[
    "MountTargetId" => "fsmt-12340abc"
]
```

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/elasticfilesystem-2015-02-01/DeleteMountTarget)
"""
@inline delete_mount_target(aws::AWSConfig=default_aws_config(); args...) = delete_mount_target(aws, args)

@inline delete_mount_target(aws::AWSConfig, args) = AWSCore.Services.elasticfilesystem(aws, "DELETE", "/2015-02-01/mount-targets/{MountTargetId}", args)

@inline delete_mount_target(args) = delete_mount_target(default_aws_config(), args)

"""
    using AWSSDK.EFS.delete_tags
    delete_tags([::AWSConfig], arguments::Dict)
    delete_tags([::AWSConfig]; FileSystemId=, TagKeys=)

    using AWSCore.Services.elasticfilesystem
    elasticfilesystem([::AWSConfig], "POST", "/2015-02-01/delete-tags/{FileSystemId}", arguments::Dict)
    elasticfilesystem([::AWSConfig], "POST", "/2015-02-01/delete-tags/{FileSystemId}", FileSystemId=, TagKeys=)

# DeleteTags Operation

Deletes the specified tags from a file system. If the `DeleteTags` request includes a tag key that does not exist, Amazon EFS ignores it and doesn't cause an error. For more information about tags and related restrictions, see [Tag Restrictions](http://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/cost-alloc-tags.html) in the *AWS Billing and Cost Management User Guide*.

This operation requires permissions for the `elasticfilesystem:DeleteTags` action.

# Arguments

## `FileSystemId = ::String` -- *Required*
ID of the file system whose tags you want to delete (String).

## `TagKeys = [::String, ...]` -- *Required*
List of tag keys to delete.

# Exceptions

`BadRequest`, `InternalServerError` or `FileSystemNotFound`.

# Example: To delete tags for an EFS file system

This operation deletes tags for an EFS file system.

Input:
```
[
    "FileSystemId" => "fs-01234567",
    "TagKeys" => [
        "Name"
    ]
]
```

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/elasticfilesystem-2015-02-01/DeleteTags)
"""
@inline delete_tags(aws::AWSConfig=default_aws_config(); args...) = delete_tags(aws, args)

@inline delete_tags(aws::AWSConfig, args) = AWSCore.Services.elasticfilesystem(aws, "POST", "/2015-02-01/delete-tags/{FileSystemId}", args)

@inline delete_tags(args) = delete_tags(default_aws_config(), args)

"""
    using AWSSDK.EFS.describe_file_systems
    describe_file_systems([::AWSConfig], arguments::Dict)
    describe_file_systems([::AWSConfig]; <keyword arguments>)

    using AWSCore.Services.elasticfilesystem
    elasticfilesystem([::AWSConfig], "GET", "/2015-02-01/file-systems", arguments::Dict)
    elasticfilesystem([::AWSConfig], "GET", "/2015-02-01/file-systems", <keyword arguments>)

# DescribeFileSystems Operation

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. 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 implementation may return fewer than `MaxItems` file system descriptions while still including a `NextMarker` value.

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.

# Arguments

## `MaxItems = ::Int`
(Optional) Specifies the maximum number of file systems to return in the response (integer). This parameter value must be greater than 0. The number of items that Amazon EFS returns is the minimum of the `MaxItems` parameter specified in the request and the service's internal maximum number of items per page.

## `Marker = ::String`
(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.

## `CreationToken = ::String`
(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 = ::String`
(Optional) ID of the file system whose description you want to retrieve (String).

# Returns

`DescribeFileSystemsResponse`

# Exceptions

`BadRequest`, `InternalServerError` or `FileSystemNotFound`.

# Example: To describe an EFS file system

This operation describes all of the EFS file systems in an account.

Input:
```
[

]
```

Output:
```
Dict(
    "FileSystems" => [
        Dict(
            "CreationTime" => "1481841524.0",
            "CreationToken" => "tokenstring",
            "FileSystemId" => "fs-01234567",
            "LifeCycleState" => "available",
            "Name" => "MyFileSystem",
            "NumberOfMountTargets" => 1,
            "OwnerId" => "012345678912",
            "PerformanceMode" => "generalPurpose",
            "SizeInBytes" => Dict(
                "Value" => 6144
            )
        )
    ]
)
```

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/elasticfilesystem-2015-02-01/DescribeFileSystems)
"""
@inline describe_file_systems(aws::AWSConfig=default_aws_config(); args...) = describe_file_systems(aws, args)

@inline describe_file_systems(aws::AWSConfig, args) = AWSCore.Services.elasticfilesystem(aws, "GET", "/2015-02-01/file-systems", args)

@inline describe_file_systems(args) = describe_file_systems(default_aws_config(), args)

"""
    using AWSSDK.EFS.describe_mount_target_security_groups
    describe_mount_target_security_groups([::AWSConfig], arguments::Dict)
    describe_mount_target_security_groups([::AWSConfig]; MountTargetId=)

    using AWSCore.Services.elasticfilesystem
    elasticfilesystem([::AWSConfig], "GET", "/2015-02-01/mount-targets/{MountTargetId}/security-groups", arguments::Dict)
    elasticfilesystem([::AWSConfig], "GET", "/2015-02-01/mount-targets/{MountTargetId}/security-groups", MountTargetId=)

# DescribeMountTargetSecurityGroups Operation

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

## `MountTargetId = ::String` -- *Required*
ID of the mount target whose security groups you want to retrieve.

# Returns

`DescribeMountTargetSecurityGroupsResponse`

# Exceptions

`BadRequest`, `InternalServerError`, `MountTargetNotFound` or `IncorrectMountTargetState`.

# Example: To describe the security groups for a mount target

This operation describes all of the security groups for a file system's mount target.

Input:
```
[
    "MountTargetId" => "fsmt-12340abc"
]
```

Output:
```
Dict(
    "SecurityGroups" => [
        "sg-fghi4567"
    ]
)
```

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/elasticfilesystem-2015-02-01/DescribeMountTargetSecurityGroups)
"""
@inline describe_mount_target_security_groups(aws::AWSConfig=default_aws_config(); args...) = describe_mount_target_security_groups(aws, args)

@inline describe_mount_target_security_groups(aws::AWSConfig, args) = AWSCore.Services.elasticfilesystem(aws, "GET", "/2015-02-01/mount-targets/{MountTargetId}/security-groups", args)

@inline describe_mount_target_security_groups(args) = describe_mount_target_security_groups(default_aws_config(), args)

"""
    using AWSSDK.EFS.describe_mount_targets
    describe_mount_targets([::AWSConfig], arguments::Dict)
    describe_mount_targets([::AWSConfig]; <keyword arguments>)

    using AWSCore.Services.elasticfilesystem
    elasticfilesystem([::AWSConfig], "GET", "/2015-02-01/mount-targets", arguments::Dict)
    elasticfilesystem([::AWSConfig], "GET", "/2015-02-01/mount-targets", <keyword arguments>)

# DescribeMountTargets Operation

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`.

# Arguments

## `MaxItems = ::Int`
(Optional) Maximum number of mount targets to return in the response. It must be an integer with a value greater than zero.

## `Marker = ::String`
(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.

## `FileSystemId = ::String`
(Optional) ID of the file system whose mount targets you want to list (String). It must be included in your request if `MountTargetId` is not included.

## `MountTargetId = ::String`
(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.

# Returns

`DescribeMountTargetsResponse`

# Exceptions

`BadRequest`, `InternalServerError`, `FileSystemNotFound` or `MountTargetNotFound`.

# Example: To describe the mount targets for a file system

This operation describes all of a file system's mount targets.

Input:
```
[
    "FileSystemId" => "fs-01234567"
]
```

Output:
```
Dict(
    "MountTargets" => [
        Dict(
            "FileSystemId" => "fs-01234567",
            "IpAddress" => "192.0.0.2",
            "LifeCycleState" => "available",
            "MountTargetId" => "fsmt-12340abc",
            "NetworkInterfaceId" => "eni-cedf6789",
            "OwnerId" => "012345678912",
            "SubnetId" => "subnet-1234abcd"
        )
    ]
)
```

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/elasticfilesystem-2015-02-01/DescribeMountTargets)
"""
@inline describe_mount_targets(aws::AWSConfig=default_aws_config(); args...) = describe_mount_targets(aws, args)

@inline describe_mount_targets(aws::AWSConfig, args) = AWSCore.Services.elasticfilesystem(aws, "GET", "/2015-02-01/mount-targets", args)

@inline describe_mount_targets(args) = describe_mount_targets(default_aws_config(), args)

"""
    using AWSSDK.EFS.describe_tags
    describe_tags([::AWSConfig], arguments::Dict)
    describe_tags([::AWSConfig]; FileSystemId=, <keyword arguments>)

    using AWSCore.Services.elasticfilesystem
    elasticfilesystem([::AWSConfig], "GET", "/2015-02-01/tags/{FileSystemId}/", arguments::Dict)
    elasticfilesystem([::AWSConfig], "GET", "/2015-02-01/tags/{FileSystemId}/", FileSystemId=, <keyword arguments>)

# DescribeTags Operation

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 multi-call iteration (when using pagination) is unspecified.

This operation requires permissions for the `elasticfilesystem:DescribeTags` action.

# Arguments

## `MaxItems = ::Int`
(Optional) Maximum number of file system tags to return in the response. It must be an integer with a value greater than zero.

## `Marker = ::String`
(Optional) 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.

## `FileSystemId = ::String` -- *Required*
ID of the file system whose tag set you want to retrieve.

# Returns

`DescribeTagsResponse`

# Exceptions

`BadRequest`, `InternalServerError` or `FileSystemNotFound`.

# Example: To describe the tags for a file system

This operation describes all of a file system's tags.

Input:
```
[
    "FileSystemId" => "fs-01234567"
]
```

Output:
```
Dict(
    "Tags" => [
        Dict(
            "Key" => "Name",
            "Value" => "MyFileSystem"
        )
    ]
)
```

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/elasticfilesystem-2015-02-01/DescribeTags)
"""
@inline describe_tags(aws::AWSConfig=default_aws_config(); args...) = describe_tags(aws, args)

@inline describe_tags(aws::AWSConfig, args) = AWSCore.Services.elasticfilesystem(aws, "GET", "/2015-02-01/tags/{FileSystemId}/", args)

@inline describe_tags(args) = describe_tags(default_aws_config(), args)

"""
    using AWSSDK.EFS.modify_mount_target_security_groups
    modify_mount_target_security_groups([::AWSConfig], arguments::Dict)
    modify_mount_target_security_groups([::AWSConfig]; MountTargetId=, <keyword arguments>)

    using AWSCore.Services.elasticfilesystem
    elasticfilesystem([::AWSConfig], "PUT", "/2015-02-01/mount-targets/{MountTargetId}/security-groups", arguments::Dict)
    elasticfilesystem([::AWSConfig], "PUT", "/2015-02-01/mount-targets/{MountTargetId}/security-groups", MountTargetId=, <keyword arguments>)

# ModifyMountTargetSecurityGroups Operation

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](@ref). 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

## `MountTargetId = ::String` -- *Required*
ID of the mount target whose security groups you want to modify.

## `SecurityGroups = [::String, ...]`
Array of up to five VPC security group IDs.

# Exceptions

`BadRequest`, `InternalServerError`, `MountTargetNotFound`, `IncorrectMountTargetState`, `SecurityGroupLimitExceeded` or `SecurityGroupNotFound`.

# Example: To modify the security groups associated with a mount target for a file system

This operation modifies the security groups associated with a mount target for a file system.

Input:
```
[
    "MountTargetId" => "fsmt-12340abc",
    "SecurityGroups" => [
        "sg-abcd1234"
    ]
]
```

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/elasticfilesystem-2015-02-01/ModifyMountTargetSecurityGroups)
"""
@inline modify_mount_target_security_groups(aws::AWSConfig=default_aws_config(); args...) = modify_mount_target_security_groups(aws, args)

@inline modify_mount_target_security_groups(aws::AWSConfig, args) = AWSCore.Services.elasticfilesystem(aws, "PUT", "/2015-02-01/mount-targets/{MountTargetId}/security-groups", args)

@inline modify_mount_target_security_groups(args) = modify_mount_target_security_groups(default_aws_config(), args)

"""
    using AWSSDK.EFS.update_file_system
    update_file_system([::AWSConfig], arguments::Dict)
    update_file_system([::AWSConfig]; FileSystemId=, <keyword arguments>)

    using AWSCore.Services.elasticfilesystem
    elasticfilesystem([::AWSConfig], "PUT", "/2015-02-01/file-systems/{FileSystemId}", arguments::Dict)
    elasticfilesystem([::AWSConfig], "PUT", "/2015-02-01/file-systems/{FileSystemId}", FileSystemId=, <keyword arguments>)

# UpdateFileSystem Operation

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

# Arguments

## `FileSystemId = ::String` -- *Required*
The ID of the file system that you want to update.

## `ThroughputMode = "bursting" or "provisioned"`
(Optional) The throughput mode that you want your file system to use. If you're not updating your throughput mode, you don't need to provide this value in your request.

## `ProvisionedThroughputInMibps = double`
(Optional) The amount of throughput, in MiB/s, that you want to provision for your file system. If you're not updating the amount of provisioned throughput for your file system, you don't need to provide this value in your request.

# Returns

`FileSystemDescription`

# Exceptions

`BadRequest`, `FileSystemNotFound`, `IncorrectFileSystemLifeCycleState`, `InsufficientThroughputCapacity`, `InternalServerError`, `ThroughputLimitExceeded` or `TooManyRequests`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/elasticfilesystem-2015-02-01/UpdateFileSystem)
"""
@inline update_file_system(aws::AWSConfig=default_aws_config(); args...) = update_file_system(aws, args)

@inline update_file_system(aws::AWSConfig, args) = AWSCore.Services.elasticfilesystem(aws, "PUT", "/2015-02-01/file-systems/{FileSystemId}", args)

@inline update_file_system(args) = update_file_system(default_aws_config(), args)

end # module EFS

#==============================================================================#
# End of file
#==============================================================================#


text:
include("../src/Rhapsodie.jl")

DSIZE=128;
NTOT=64;
Nframe=2;
Nrot=1
Nangle=Int64.(NTOT/(Nrot*Nframe*4))
Center=[DSIZE/2;  DSIZE/2];
DerotAng=Vector{Float64}();
Epsilon=Vector{Tuple{Array{Float64,1},Array{Float64,1}}}();

for iter=1:NTOT
    ind=div(iter-1, NTOT/4)+1
    push!(Epsilon,([0. ,0. ],[10.7365 , -1.39344]));
    push!(DerotAng, deg2rad(-300.0));
end

psf_center=Rhapsodie.readdlm("../data/PSF_centers_Airy.txt");
Rhapsodie.load_parameters((DSIZE, 2*DSIZE, NTOT), Nframe, Nrot, Nangle, Center, (psf_center[1:2], psf_center[3:4]), Epsilon, DerotAng)

Rhapsodie.writedlm("test_results/Parameters.txt", [DSIZE; NTOT; Nframe; Nrot; Center; 300; [10.7365 , -1.39344]]);

psf=read(Rhapsodie.FitsArray,  "../data/PSF_parametered_Airy.fits");
const A=Rhapsodie.set_fft_op((psf[1:end÷2,:]'), Rhapsodie.get_par().psf_center[1]);

BadPixMap=rand(0.0:1e-16:1.0,(DSIZE, 2*DSIZE)).< 0.9;

for tau in [0.01, 0.03, 0.07, 0.1, 0.15, 0.25, 0.5]

    data, weight, S, S_convolved=Rhapsodie.data_simulator(BadPixMap, tau, A);

    write(Rhapsodie.FitsFile, "test_results/DATA_$tau-$DSIZE.fits",
          mapslices(transpose,data,dims=[1,2]), overwrite=true)
    write(Rhapsodie.FitsFile, "test_results/WEIGHT_$tau-$DSIZE.fits",
          mapslices(transpose,weight,dims=[1,2]), overwrite=true)

    Rhapsodie.write(S, "test_results/TRUE_$tau-$DSIZE.fits")
    Rhapsodie.write(S_convolved, "test_results/TRUE_convolved_$tau-$DSIZE.fits")

end

ext: jl


text:
#################### Geweke Diagnostic ####################

function gewekediag(x::Vector{T}; first::Real=0.1, last::Real=0.5,
                             etype=:imse, args...) where {T<:Real}
  if !(0.0 < first < 1.0)
    throw(ArgumentError("first is not in (0, 1)"))
  elseif !(0.0 < last < 1.0)
    throw(ArgumentError("last is not in (0, 1)"))
  elseif first + last > 1.0
    throw(ArgumentError("first and last proportions overlap"))
  end
  n = length(x)
  x1 = x[1:round(Int, first * n)]
  x2 = x[round(Int, n - last * n + 1):n]
  z = (mean(x1) - mean(x2)) /
      sqrt(mcse(x1, etype; args...)^2 + mcse(x2, etype; args...)^2)
  [round(z, digits = 3), round(1.0 - erf(abs(z) / sqrt(2.0)), digits = 4)]
end

function gewekediag(c::AbstractChains; first::Real=0.1, last::Real=0.5,
                    etype=:imse, args...)
  _, p, m = size(c.value)
  vals = Array{Float64}(undef, p, 2, m)
  for j in 1:p, k in 1:m
    vals[j, :, k] = gewekediag(c.value[:, j, k], first=first, last=last,
                               etype=etype; args...)
  end
  hdr = header(c) * "\nGeweke Diagnostic:\nFirst Window Fraction = $first\n" *
        "Second Window Fraction = $last\n"
  ChainSummary(vals, c.names, ["Z-score", "p-value"], hdr)
end


text:
module NormalHermiteSplines

export prepare, construct, interpolate
export evaluate, evaluate!, evaluate_one, evaluate_gradient, evaluate_derivative
export NormalSpline, RK_H0, RK_H1, RK_H2
export get_epsilon, estimate_epsilon, get_cond, estimate_cond, estimate_accuracy

using LinearAlgebra
using StaticArrays
using UnPack
using UnsafeArrays

const AbstractArrOfSVecs{n,T,N} = AbstractArray{SVector{n,T},N}
const AbstractVecOfSVecs{n,T} = AbstractVector{SVector{n,T}}
const VecOfSVecs{n,T} = Vector{SVector{n,T}}

@inline svectors(x::AbstractMatrix{T}) where {T} = reinterpret(reshape, SVector{size(x,1),T}, x)
@inline svectors(x::AbstractVector{T}) where {T} = reinterpret(SVector{1,T}, x)

include("./ReproducingKernels.jl")
include("./GramMatrix.jl")
include("./Splines.jl")
include("./Utils.jl")
include("./Interpolate.jl")

####
#### Public API
####

#### ReproducingKernel_0

"""
`prepare(nodes::AbstractMatrix{T}, kernel::RK = RK_H0()) where {T <: Real, RK <: ReproducingKernel_0}`

Prepare the spline by constructing and factoring a Gram matrix of the interpolation problem.
Initialize the `NormalSpline` object.
# Arguments
- `nodes`: The function value nodes.
           This should be an `n×n_1` matrix, where `n` is dimension of the sampled space and
           `n₁` is the number of function value nodes. It means that each column in the matrix defines one node.
- `kernel`: reproducing kernel of Bessel potential space the normal spline is constructed in.
            It must be a struct object of the following type:
              `RK_H0` if the spline is constructing as a continuous function,
              `RK_H1` if the spline is constructing as a differentiable function,
              `RK_H2` if the spline is constructing as a twice differentiable function.

Return: the partly initialized `NormalSpline` object that must be passed to `construct` function
        in order to complete the spline initialization.
"""
@inline function prepare(nodes::AbstractMatrix{T}, kernel::RK = RK_H0()) where {T <: Real, RK <: ReproducingKernel_0}
    return prepare(svectors(nodes), kernel)
end
@inline function prepare(nodes::AbstractVecOfSVecs{n,T}, kernel::RK = RK_H0()) where {n, T <: Real, RK <: ReproducingKernel_0}
    return _prepare(nodes, kernel)
end

"""
`construct(spline::AbstractNormalSpline{n,T,RK}, values::AbstractVector{T}) where {n, T <: Real, RK <: ReproducingKernel_0}`

Construct the spline by calculating its coefficients and completely initializing the `NormalSpline` object.
# Arguments
- `spline`: the partly initialized `NormalSpline` object returned by `prepare` function.
- `values`: function values at `nodes` nodes.

Return: the completely initialized `NormalSpline` object that can be passed to `evaluate` function
        to interpolate the data to required points.
"""
@inline function construct(spline::AbstractNormalSpline{n,T,RK}, values::AbstractVector{T}) where {n, T <: Real, RK <: ReproducingKernel_0}
    return _construct!(deepcopy(spline), values)
end

"""
`interpolate(nodes::AbstractMatrix{T}, values::AbstractVector{T}, kernel::RK = RK_H0()) where {T <: Real, RK <: ReproducingKernel_0}`

Prepare and construct the spline.
# Arguments
- `nodes`: The function value nodes.
           This should be an `n×n_1` matrix, where `n` is dimension of the sampled space
           and `n₁` is the number of function value nodes.
           It means that each column in the matrix defines one node.
- `values`: function values at `nodes` nodes.
- `kernel`: reproducing kernel of Bessel potential space the normal spline is constructed in.
            It must be a struct object of the following type:
              `RK_H0` if the spline is constructing as a continuous function,
              `RK_H1` if the spline is constructing as a differentiable function,
              `RK_H2` if the spline is constructing as a twice differentiable function.

Return: the completely initialized `NormalSpline` object that can be passed to `evaluate` function.
"""
@inline function interpolate(nodes::AbstractMatrix{T}, values::AbstractVector{T}, kernel::RK = RK_H0()) where {T <: Real, RK <: ReproducingKernel_0}
    return interpolate(svectors(nodes), values, kernel)
end
@inline function interpolate(nodes::AbstractVecOfSVecs{n,T}, values::AbstractVector{T}, kernel::RK = RK_H0()) where {n, T <: Real, RK <: ReproducingKernel_0}
    spline = _prepare(nodes, kernel)
    return _construct!(spline, values)
end

"""
`evaluate(spline::AbstractNormalSpline{n,T,RK}, points::AbstractMatrix{T}) where {n, T <: Real, RK <: ReproducingKernel_0}`

Evaluate the spline values at the locations defined in `points`.

# Arguments
- `spline: the `NormalSpline` object returned by `interpolate` or `construct` function.
- `points`: locations at which spline values are evaluating.
            This should be an `n×m` matrix, where `n` is dimension of the sampled space
            and `m` is the number of locations where spline values are evaluating.
            It means that each column in the matrix defines one location.

Return: `Vector{T}` of the spline values at the locations defined in `points`.
"""
@inline function evaluate(spline::AbstractNormalSpline{n,T,RK}, points::AbstractMatrix{T}) where {n, T <: Real, RK <: ReproducingKernel_0}
    return evaluate(spline, svectors(points))
end
@inline function evaluate(spline::AbstractNormalSpline{n,T,RK}, points::AbstractArrOfSVecs{n,T}) where {n, T <: Real, RK <: ReproducingKernel_0}
    return evaluate!(zeros(T, size(points)), spline, points)
end
@inline function evaluate!(spline_values::AbstractArray{T,N}, spline::AbstractNormalSpline{n,T,RK}, points::AbstractArrOfSVecs{n,T,N}) where {n, T <: Real, N, RK <: ReproducingKernel_0}
    return _evaluate!(spline_values, spline, points)
end
@inline function evaluate(spline::AbstractNormalSpline{n,T,RK}, point::SVector{n,T}) where {n, T <: Real, N, RK <: ReproducingKernel_0}
    return _evaluate(spline, point)
end

"""
`evaluate_one(spline::AbstractNormalSpline{n,T,RK}, point::AbstractVector{T}) where {n, T <: Real, RK <: ReproducingKernel_0}`

Evaluate the spline value at the `point` location.

# Arguments
- `spline`: the `NormalSpline` object returned by `interpolate` or `construct` function.
- `point`: location at which spline value is evaluating.
           This should be a vector of size `n`, where `n` is dimension of the sampled space.

Return: the spline value at the location defined in `point`.
"""
@inline function evaluate_one(spline::AbstractNormalSpline{n,T,RK}, point::AbstractVector{T}) where {n, T <: Real, RK <: ReproducingKernel_0}
    return evaluate_one(spline, SVector{n,T}(ntuple(i -> point[i], n)))
end
@inline function evaluate_one(spline::AbstractNormalSpline{n,T,RK}, point::SVector{n,T}) where {n, T <: Real, RK <: ReproducingKernel_0}
    return evaluate(spline, point)
end

"""
`evaluate_gradient(spline::AbstractNormalSpline{n,T,RK}, point::AbstractVector{T}) where {n, T <: Real, RK <: ReproducingKernel_0}`

Evaluate gradient of the spline at the location defined in `point`.

# Arguments
- `spline`: the `NormalSpline` object returned by `interpolate` or `construct` function.
- `point`: location at which gradient value is evaluating.
           This should be a vector of size `n`, where `n` is dimension of the sampled space.

Note: Gradient of spline built with reproducing kernel RK_H0 does not exist at the spline nodes.

Return: `Vector{T}` - gradient of the spline at the location defined in `point`.
"""
@inline function evaluate_gradient(spline::AbstractNormalSpline{n,T,RK}, point::AbstractVector{T}) where {n, T <: Real, RK <: ReproducingKernel_0}
    return evaluate_gradient(spline, SVector{n,T}(ntuple(i -> point[i], n)))
end
@inline function evaluate_gradient(spline::AbstractNormalSpline{n,T,RK}, point::SVector{n,T}) where {n, T <: Real, RK <: ReproducingKernel_0}
    return _evaluate_gradient(spline, point)
end

#### ReproducingKernel_1

"""
`prepare(nodes::AbstractMatrix{T}, d_nodes::AbstractMatrix{T}, d_dirs::AbstractMatrix{T}, kernel::RK = RK_H1()) where {T <: Real, RK <: ReproducingKernel_1}`

Prepare the spline by constructing and factoring a Gram matrix of the interpolation problem.
Initialize the `NormalSpline` object.
# Arguments
- `nodes`: The function value nodes.
           This should be an `n×n_1` matrix, where `n` is dimension of the sampled space and
           `n₁` is the number of function value nodes.
            It means that each column in the matrix defines one node.
- `d_nodes`: The function directional derivatives nodes.
             This should be an `n×n_2` matrix, where `n` is dimension of the sampled space and
             `n₂` is the number of function directional derivative nodes.
- `d_dirs`: Directions of the function directional derivatives.
        This should be an `n×n_2` matrix, where `n` is dimension of the sampled space and
        `n₂` is the number of function directional derivative nodes.
        It means that each column in the matrix defines one direction of the function directional derivative.
- `kernel`: reproducing kernel of Bessel potential space the normal spline is constructed in.
            It must be a struct object of the following type:
              `RK_H1` if the spline is constructing as a differentiable function,
              `RK_H2` if the spline is constructing as a twice differentiable function.

Return: the partly initialized `NormalSpline` object that must be passed to `construct` function
        in order to complete the spline initialization.
"""
@inline function prepare(nodes::AbstractMatrix{T}, d_nodes::AbstractMatrix{T}, d_dirs::AbstractMatrix{T}, kernel::RK = RK_H1()) where {T <: Real, RK <: ReproducingKernel_1}
    return prepare(svectors(nodes), svectors(d_nodes), svectors(d_dirs), kernel)
end
@inline function prepare(nodes::AbstractVecOfSVecs{n,T}, d_nodes::AbstractVecOfSVecs{n,T}, d_dirs::AbstractVecOfSVecs{n,T}, kernel::RK = RK_H1()) where {n, T <: Real, RK <: ReproducingKernel_1}
    return _prepare(nodes, d_nodes, d_dirs, kernel)
end

"""
`construct(spline::AbstractNormalSpline{n,T,RK}, values::AbstractVector{T}, d_values::AbstractVector{T}) where {n, T <: Real, RK <: ReproducingKernel_1}`

Construct the spline by calculating its coefficients and completely initializing the `NormalSpline` object.
# Arguments
- `spline`: the partly initialized `NormalSpline` object returned by `prepare` function.
- `values`: function values at `nodes` nodes.
- `d_values`: function directional derivative values at `d_nodes` nodes.

Return: the completely initialized `NormalSpline` object that can be passed to `evaluate` function
        to interpolate the data to required points.
"""
@inline function construct(spline::AbstractNormalSpline{n,T,RK}, values::AbstractVector{T}, d_values::AbstractVector{T}) where {n, T <: Real, RK <: ReproducingKernel_1}
    return _construct!(deepcopy(spline), values, d_values)
end

"""
`interpolate(nodes::AbstractMatrix{T}, values::AbstractVector{T}, d_nodes::AbstractMatrix{T}, d_dirs::AbstractMatrix{T}, d_values::AbstractVector{T}, kernel::RK = RK_H1()) where {T <: Real, RK <: ReproducingKernel_1}`

Prepare and construct the spline.
# Arguments
- `nodes`: The function value nodes.
           This should be an `n×n_1` matrix, where `n` is dimension of the sampled space
           and `n₁` is the number of function value nodes.
           It means that each column in the matrix defines one node.
- `values`: function values at `nodes` nodes.
- `d_nodes`: The function directional derivative nodes.
            This should be an `n×n_2` matrix, where `n` is dimension of the sampled space and
            `n₂` is the number of function directional derivative nodes.
- `d_dirs`: Directions of the function directional derivatives.
       This should be an `n×n_2` matrix, where `n` is dimension of the sampled space and
       `n₂` is the number of function directional derivative nodes.
       It means that each column in the matrix defines one direction of the function directional derivative.
- `d_values`: function directional derivative values at `d_nodes` nodes.
- `kernel`: reproducing kernel of Bessel potential space the normal spline is constructed in.
            It must be a struct object of the following type:
              `RK_H1` if the spline is constructing as a differentiable function,
              `RK_H2` if the spline is constructing as a twice differentiable function.

Return: the completely initialized `NormalSpline` object that can be passed to `evaluate` function.
"""
@inline function interpolate(nodes::AbstractMatrix{T}, values::AbstractVector{T}, d_nodes::AbstractMatrix{T}, d_dirs::AbstractMatrix{T}, d_values::AbstractVector{T}, kernel::RK = RK_H1()) where {T <: Real, RK <: ReproducingKernel_1}
    return interpolate(svectors(nodes), values, svectors(d_nodes), svectors(d_dirs), d_values, kernel)
end
@inline function interpolate(nodes::AbstractVecOfSVecs{n,T}, values::AbstractVector{T}, d_nodes::AbstractVecOfSVecs{n,T}, d_dirs::AbstractVecOfSVecs{n,T}, d_values::AbstractVector{T}, kernel::RK = RK_H1()) where {n, T <: Real, RK <: ReproducingKernel_1}
    spline = _prepare(nodes, d_nodes, d_dirs, kernel)
    return _construct!(spline, values, d_values)
end

#### ReproducingKernel_0 (1-dimensional case)

"""
`prepare(nodes::AbstractVector{T}, kernel::RK = RK_H0()) where {T <: Real, RK <: ReproducingKernel_0}`

Prepare the 1D spline by constructing and factoring a Gram matrix of the interpolation problem.
Initialize the `NormalSpline` object.
# Arguments
- `nodes`: function value interpolation nodes.
           This should be an `n₁` vector where `n₁` is the number of function value nodes.
- `kernel`: reproducing kernel of Bessel potential space the normal spline is constructed in.
            It must be a struct object of the following type:
              `RK_H0` if the spline is constructing as a continuous function,
              `RK_H1` if the spline is constructing as a differentiable function,
              `RK_H2` if the spline is constructing as a twice differentiable function.

Return: the partly initialized `NormalSpline` object that must be passed to `construct` function
        in order to complete the spline initialization.
"""
@inline function prepare(nodes::AbstractVector{T}, kernel::RK = RK_H0()) where {T <: Real, RK <: ReproducingKernel_0}
    return prepare(svectors(nodes), kernel)
end

"""
`interpolate(nodes::AbstractVector{T}, values::AbstractVector{T}, kernel::RK = RK_H0()) where {T <: Real, RK <: ReproducingKernel_0}`

Prepare and construct the 1D spline.
# Arguments
- `nodes`: function value interpolation nodes.
           This should be an `n₁` vector where `n₁` is the number of function value nodes.
- `values`: function values at `n₁` interpolation nodes.
- `kernel`: reproducing kernel of Bessel potential space the normal spline is constructed in.
            It must be a struct object of the following type:
              `RK_H0` if the spline is constructing as a continuous function,
              `RK_H1` if the spline is constructing as a differentiable function,
              `RK_H2` if the spline is constructing as a twice differentiable function.

Return: the completely initialized `NormalSpline` object that can be passed to `evaluate` function.
"""
@inline function interpolate(nodes::AbstractVector{T}, values::AbstractVector{T}, kernel::RK = RK_H0()) where {T <: Real, RK <: ReproducingKernel_0}
    interpolate(svectors(nodes), values, kernel)
end

"""
`evaluate(spline::AbstractNormalSpline{n,T,RK}, points::AbstractVector{T}) where {n, T <: Real, RK <: ReproducingKernel_0}`

Evaluate the 1D spline values/value at the `points` locations.

# Arguments
- `spline`: the `NormalSpline` object returned by `interpolate` or `construct` function.
- `points`: locations at which spline values are evaluating.
            This should be a vector of size `m` where `m` is the number of evaluating points.

Return: spline value at the `point` location.
"""
@inline function evaluate(spline::AbstractNormalSpline{n,T,RK}, points::AbstractVector{T}) where {n, T <: Real, RK <: ReproducingKernel_0}
    return evaluate(spline, svectors(points))
end

"""
`evaluate_one(spline::AbstractNormalSpline{1,T,RK}, point::T) where {T <: Real, RK <: ReproducingKernel_0}`

Evaluate the 1D spline value at the `point` location.

# Arguments
- `spline`: the `NormalSpline` object returned by `interpolate` or `construct` function.
- `point`: location at which spline value is evaluating.

Return: spline value at the `point` location.
"""
@inline function evaluate_one(spline::AbstractNormalSpline{1,T,RK}, point::T) where {T <: Real, RK <: ReproducingKernel_0}
    return evaluate(spline, SVector{1,T}((point,)))
end

"""
`evaluate_derivative(spline::AbstractNormalSpline{1,T,RK}, point::T) where {T <: Real, RK <: ReproducingKernel_0}`

Evaluate the 1D spline derivative at the `point` location.

# Arguments
- `spline`: the `NormalSpline` object returned by `interpolate` or `construct` function.
- `point`: location at which spline derivative is evaluating.

Note: Derivative of spline built with reproducing kernel RK_H0 does not exist at the spline nodes.

Return: the spline derivative value at the `point` location.
"""
@inline function evaluate_derivative(spline::AbstractNormalSpline{1,T,RK}, point::T) where {T <: Real, RK <: ReproducingKernel_0}
    return evaluate_gradient(spline, SVector{1,T}((point,)))[1]
end

#### ReproducingKernel_1 (1-dimensional case)

"""
`prepare(nodes::AbstractVector{T}, d_nodes::AbstractVector{T}, kernel::RK = RK_H1()) where {T <: Real, RK <: ReproducingKernel_1}`

Prepare the 1D interpolating normal spline by constructing and factoring a Gram matrix of the problem.
Initialize the `NormalSpline` object.
# Arguments
- `nodes`: function value interpolation nodes.
           This should be an `n₁` vector where `n₁` is the number of function value nodes.
- `d_nodes`: The function derivatives nodes.
             This should be an `n₂` vector where `n₂` is the number of function derivatives nodes.
- `kernel`: reproducing kernel of Bessel potential space the normal spline is constructed in.
            It must be a struct object of the following type:
              `RK_H1` if the spline is constructing as a differentiable function,
              `RK_H2` if the spline is constructing as a twice differentiable function.

Return: the partly initialized `NormalSpline` object that must be passed to `construct` function
        in order to complete the spline initialization.
"""
@inline function prepare(nodes::AbstractVector{T}, d_nodes::AbstractVector{T}, kernel::RK = RK_H1()) where {T <: Real, RK <: ReproducingKernel_1}
    d_dirs = fill(ones(SVector{1,T}), length(d_nodes))
    return prepare(svectors(nodes), svectors(d_nodes), d_dirs, kernel)
end

"""
`interpolate(nodes::AbstractVector{T}, values::AbstractVector{T}, d_nodes::AbstractVector{T}, d_values::AbstractVector{T}, kernel::RK = RK_H1()) where {T <: Real, RK <: ReproducingKernel_1}`

Prepare and construct the 1D interpolating normal spline.
# Arguments
- `nodes`: function value interpolation nodes.
           This should be an `n₁` vector where `n₁` is the number of function value nodes.
- `values`: function values at `nodes` nodes.
- `d_nodes`: The function derivatives nodes.
             This should be an `n₂` vector where `n₂` is the number of function derivatives nodes.
- `d_values`: function derivative values at `d_nodes` nodes.
- `kernel`: reproducing kernel of Bessel potential space the normal spline is constructed in.
            It must be a struct object of the following type:
              `RK_H1` if the spline is constructing as a differentiable function,
              `RK_H2` if the spline is constructing as a twice differentiable function.

Return: the completely initialized `NormalSpline` object that can be passed to `evaluate` function.
"""
@inline function interpolate(nodes::AbstractVector{T}, values::AbstractVector{T}, d_nodes::AbstractVector{T}, d_values::AbstractVector{T}, kernel::RK = RK_H1()) where {T <: Real, RK <: ReproducingKernel_1}
    d_dirs = fill(ones(SVector{1,T}), length(d_nodes))
    return interpolate(svectors(nodes), values, svectors(d_nodes), d_dirs, d_values, kernel)
end

#### Utils for general case

"""
`get_epsilon(spline::AbstractNormalSpline{n,T,RK}) where {n, T <: Real, RK <: ReproducingKernel_0}`

Get the 'scaling parameter' of Bessel Potential space the spline was built in.
# Arguments
- `spline`: the `NormalSpline` object returned by `prepare`, `construct` or `interpolate` function.

Return: `ε` - the 'scaling parameter'.
"""
@inline function get_epsilon(spline::AbstractNormalSpline{n,T,RK}) where {n, T <: Real, RK <: ReproducingKernel_0}
    return _get_kernel(spline).ε
end

"""
`estimate_epsilon(nodes::AbstractMatrix{T}, kernel::RK = RK_H0()) where {T <: Real, RK <: ReproducingKernel_0}`

Get the estimation of the 'scaling parameter' of Bessel Potential space the spline being built in.
It coincides with the result returned by `get_epsilon` function.
# Arguments
- `nodes`: The function value nodes.
           This should be an `n×n_1` matrix, where `n` is dimension of the sampled space
           and `n₁` is the number of function value nodes.
           It means that each column in the matrix defines one node.
- `kernel`: reproducing kernel of Bessel potential space the normal spline will be constructed in.
           It must be a struct object of the following type:
             `RK_H0` if the spline is constructing as a continuous function,
             `RK_H1` if the spline is constructing as a differentiable function,
             `RK_H2` if the spline is constructing as a twice differentiable function.
Return: estimation of `ε`.
"""
@inline function estimate_epsilon(nodes::AbstractMatrix{T}, kernel::RK = RK_H0()) where {T <: Real, RK <: ReproducingKernel_0}
    return estimate_epsilon(svectors(nodes), kernel)
end
@inline function estimate_epsilon(nodes::AbstractVecOfSVecs{n,T}, kernel::RK = RK_H0()) where {n, T <: Real, RK <: ReproducingKernel_0}
    return _estimate_epsilon(nodes, kernel)
end

"""
`estimate_epsilon(nodes::AbstractMatrix{T}, d_nodes::AbstractMatrix{T}, kernel::RK = RK_H1()) where {T <: Real, RK <: ReproducingKernel_1}`

Get an the estimation of the 'scaling parameter' of Bessel Potential space the spline being built in.
It coincides with the result returned by `get_epsilon` function.
# Arguments
- `nodes`: The function value nodes.
           This should be an `n×n_1` matrix, where `n` is dimension of the sampled space
           and `n₁` is the number of function value nodes.
           It means that each column in the matrix defines one node.
- `d_nodes`: The function directional derivative nodes.
           This should be an `n×n_2` matrix, where `n` is dimension of the sampled space and
           `n₂` is the number of function directional derivative nodes.
- `kernel`: reproducing kernel of Bessel potential space the normal spline will be constructed in.
            It must be a struct object of the following type:
            `RK_H1` if the spline is constructing as a differentiable function,
            `RK_H2` if the spline is constructing as a twice differentiable function.

Return: estimation of `ε`.
"""
@inline function estimate_epsilon(nodes::AbstractMatrix{T}, d_nodes::AbstractMatrix{T}, kernel::RK = RK_H1()) where {T <: Real, RK <: ReproducingKernel_1}
    return estimate_epsilon(svectors(nodes), svectors(d_nodes), kernel)
end
@inline function estimate_epsilon(nodes::AbstractVecOfSVecs{n,T}, d_nodes::AbstractVecOfSVecs{n,T}, kernel::RK = RK_H1()) where {n, T <: Real, RK <: ReproducingKernel_1}
    return _estimate_epsilon(nodes, d_nodes, kernel)
end

"""
`estimate_cond(spline::AbstractNormalSpline{n,T,RK}) where {n, T <: Real, RK <: ReproducingKernel_0}`

Get an estimation of the Gram matrix condition number. It needs the `spline` object is prepared and requires O(N^2) operations.
(C. Brás, W. Hager, J. Júdice, An investigation of feasible descent algorithms for estimating the condition number of a matrix. TOP Vol.20, No.3, 2012.)
# Arguments
- `spline`: the `NormalSpline` object returned by `prepare`, `construct` or `interpolate` function.

Return: an estimation of the Gram matrix condition number.
"""
@inline function estimate_cond(spline::AbstractNormalSpline{n,T,RK}) where {n, T <: Real, RK <: ReproducingKernel}
    return _get_cond(spline)
end

"""
`estimate_accuracy(spline::AbstractNormalSpline{n,T,RK}) where {n, T <: Real, RK <: ReproducingKernel_0}`

Assess accuracy of interpolation results by analyzing residuals.
# Arguments
- `spline`: the `NormalSpline` object returned by `construct` or `interpolate` function.

Return: an estimation of the number of significant digits in the interpolation result.
"""
@inline function estimate_accuracy(spline::AbstractNormalSpline{n,T,RK}) where {n, T <: Real, RK <: ReproducingKernel_0}
    return _estimate_accuracy(spline)
end

"""
`get_cond(nodes::AbstractMatrix{T}, kernel::RK = RK_H0()) where {T <: Real, RK <: ReproducingKernel_0}`

Get a value of the Gram matrix spectral condition number. It is obtained by means of the matrix SVD decomposition and requires ``O(N^3)`` operations.
# Arguments
- `nodes`: The function value nodes.
           This should be an `n×n_1` matrix, where `n` is dimension of the sampled space and
           `n₁` is the number of function value nodes. It means that each column in the matrix defines one node.
- `kernel`: reproducing kernel of Bessel potential space the normal spline is constructed in.
            It must be a struct object of the following type:
              `RK_H0` if the spline is constructing as a continuous function,
              `RK_H1` if the spline is constructing as a differentiable function,
              `RK_H2` if the spline is constructing as a twice differentiable function.

Return: a value of the Gram matrix spectral condition number.
"""
@inline function get_cond(nodes::AbstractMatrix{T}, kernel::RK) where {T <: Real, RK <: ReproducingKernel_0}
    return get_cond(svectors(nodes), kernel)
end
@inline function get_cond(nodes::AbstractVecOfSVecs{n,T}, kernel::RK) where {n, T <: Real, RK <: ReproducingKernel_0}
    return get_cond(nodes, kernel)
end

"""
`get_cond(nodes::AbstractMatrix{T}, d_nodes::AbstractMatrix{T}, d_dirs::AbstractMatrix{T}, kernel::RK = RK_H1()) where {T <: Real, RK <: ReproducingKernel_1}`

Get a value of the Gram matrix spectral condition number. It is obtained by means of the matrix SVD decomposition and requires ``O(N^3)`` operations.
# Arguments
- `nodes`: The function value nodes.
           This should be an `n×n_1` matrix, where `n` is dimension of the sampled space and
           `n₁` is the number of function value nodes.
            It means that each column in the matrix defines one node.
- `d_nodes`: The function directional derivatives nodes.
             This should be an `n×n_2` matrix, where `n` is dimension of the sampled space and
             `n₂` is the number of function directional derivative nodes.
- `d_dirs`: Directions of the function directional derivatives.
        This should be an `n×n_2` matrix, where `n` is dimension of the sampled space and
        `n₂` is the number of function directional derivative nodes.
        It means that each column in the matrix defines one direction of the function directional derivative.
- `kernel`: reproducing kernel of Bessel potential space the normal spline is constructed in.
            It must be a struct object of the following type:
              `RK_H1` if the spline is constructing as a differentiable function,
              `RK_H2` if the spline is constructing as a twice differentiable function.

Return: a value of the Gram matrix spectral condition number.
"""
@inline function get_cond(nodes::AbstractMatrix{T}, d_nodes::AbstractMatrix{T}, d_dirs::AbstractMatrix{T}, kernel::RK = RK_H1()) where {T <: Real, RK <: ReproducingKernel_1}
    return get_cond(svectors(nodes), svectors(d_nodes), svectors(d_dirs), kernel)
end
@inline function get_cond(nodes::AbstractVecOfSVecs{n,T}, d_nodes::AbstractVecOfSVecs{n,T}, d_dirs::AbstractVecOfSVecs{n,T}, kernel::RK = RK_H1()) where {n, T <: Real, RK <: ReproducingKernel_1}
    return get_cond(nodes, d_nodes, d_dirs, kernel)
end

#### Utils for 1-dimensional case

"""
`estimate_epsilon(nodes::AbstractVector{T}, kernel::RK = RK_H0()) where {T <: Real, RK <: ReproducingKernel_0}`

Get an the estimation of the 'scaling parameter' of Bessel Potential space the 1D spline is being built in.
It coincides with the result returned by `get_epsilon` function.
# Arguments
- `nodes`: The function value nodes.
- `kernel`: reproducing kernel of Bessel potential space the normal spline is constructed in.
            It must be a struct object of the following type:
              `RK_H0` if the spline is constructing as a continuous function,
              `RK_H1` if the spline is constructing as a differentiable function,
              `RK_H2` if the spline is constructing as a twice differentiable function.

Return: estimation of `ε`.
"""
@inline function estimate_epsilon(nodes::AbstractVector{T}, kernel::RK = RK_H0()) where {T <: Real, RK <: ReproducingKernel_0}
    return estimate_epsilon(svectors(nodes), kernel)
end

"""
`estimate_epsilon(nodes::AbstractVector{T}, d_nodes::AbstractVector{T}, kernel::RK = RK_H1()) where {T <: Real, RK <: ReproducingKernel_1}`

Get an the estimation of the 'scaling parameter' of Bessel Potential space the 1D spline is being built in.
It coincides with the result returned by `get_epsilon` function.
# Arguments
- `nodes`: The function value nodes.
- `d_nodes`: The function derivative nodes.
- `kernel`: reproducing kernel of Bessel potential space the normal spline is constructed in.
            It must be a struct object of the following type:
              `RK_H1` if the spline is constructing as a differentiable function,
              `RK_H2` if the spline is constructing as a twice differentiable function.

Return: estimation of `ε`.
"""
@inline function estimate_epsilon(nodes::AbstractVector{T}, d_nodes::AbstractVector{T}, kernel::RK = RK_H1()) where {T <: Real, RK <: ReproducingKernel_1}
    return estimate_epsilon(svectors(nodes), svectors(d_nodes), kernel)
end

end # module NormalHermiteSplines


text:
# Tudor Berariu <tudor.berariu@gmail.com>, 2015

module KMeans

end

max_stars_repo_name: tudor-berariu/ml-hacks

max_issues_repo_name: tudor-berariu/ml-hacks

max_forks_repo_name: tudor-berariu/ml-hacks


text:
using CompileBot

bot_config = BotConfig(
    "MartaCT";
    os = ["linux", "macos", "windows"],
    else_os = "linux",
    version = [v"1.5.0"],
    else_version = v"1.5.0",
)

snoop_bot(bot_config, "$(@__DIR__)/example_script.jl")


text:
@testset "MPcondition" begin

@testset "Constructor" begin
    @test_throws ErrorException MPcondition( "attribute", ∈, 5 )
    @test_throws ErrorException MPcondition( "attribute", >, "beep" )
    @test_throws ErrorException MPcondition( "attribute", <,
        ["foo", "bar"] )
    condition = MPcondition( "attribute", >=, 5 )
    @test all( [condition.attribute == "attribute",
        condition.operator == Base.:(>=), condition.value == 5] )
end  # @testset "Constructor"

end  # @testset "MPcondition"


text:
mutable struct DDOptimizer <: AbstractGraphOptimizer
    dd_model::DDModel
end

function DDOptimizer()

end

JuMP.optimize!(graph::ModelGraph,optimizer::DDOptimizer) = dual_decomposition_solve(graph,optimizer.args...;optimizer.kwargs...)


text:
"""
    WorkSheet
Contains the data for one worksheet.
"""
struct WorkSheet{T}
    book::WorkBook
    name::AbstractString
    data::T
end
function WorkSheet(ws::WorkSheet, preserve_cell = false)
    function parse_row(row)
        v = Array{Union{Cell, Missing}}(1, data_size[2]) .= missing
        for cell in filter(iselement, nodes(row))
            m = match(r"([A-Za-z]*)", cell["r"])
            col_num = col_number(m.captures[1]) - dimension[2] + 1
            v[1, col_num] = Cell(ws.book, cell)
        end
        v
    end
    xml = ws.data

    dimension = extract_dimension(xml)
    data_size = (dimension[3] - dimension[1] +1, dimension[4] - dimension[2] +1)

    # reading by row
    rowdata_node = Iterators.filter(x -> nodename(x) == "sheetData", eachnode(xml))
    row_datas = collect(rowdata_node)[1] |> nodes

    data = Array{Union{Missing, Cell}}(data_size) .= missing
    for x in filter(iselement, row_datas)
        row_num = parse(Int, x["r"]) - dimension[1] +1
        data[row_num, :] = parse_row(x)
    end

    if preserve_cell
        WorkSheet(ws.book, ws.name, data)
    else
        WorkSheet(ws.book, ws.name, _peeloff(data))
    end
end

function parse_xlsx_row(row, data_size)
    v = Array{Union{Cell, Missing}}(1, data_size[2]) .= missing
    for cell in filter(iselement, nodes(row))
        m = match(r"([A-Za-z]*)", cell["r"])
        col_num = col_number(m.captures[1]) - dimension[2] + 1
        v[1, col_num] = Cell(ws.book, cell)
    end
    v
end
function extract_dimension(xml)
    dim = Iterators.filter(x -> nodename(x) == "dimension", eachnode(xml)) |> collect
    if isempty(dim)
        throw(ParseError("Dimension information is missing, open and resaving .xlsx from Office will solve this issue"))
    end
    x = dim[1]["ref"]
    !contains(x, ":") && (x = ("A1:" * x))

    convert_ref_to_row_col(x)
end

"""
    col_number(col::AbstractString)
convert Excel column name(A ~ XFD) to column number(1~16384)
"""
function col_number(col::AbstractString)
    r = 0
    for c in uppercase(col)
        r = (r * 26) + (c - 'A' + 1)
    end
    return r
end

"""
    convert_ref_to_row_col(range::AbstractString)

converts 'A1' cell notation to 'R1C1' notation
"""
function convert_ref_to_row_col(range::AbstractString)
    # r = r"('?[^']+'?|[^!]+)!([A-Za-z]*)(\d*)(:([A-Za-z]*)(\d*))?"
    r = r"([A-Za-z]*)(\d*)"
    m = match.(r, split(range, ":"))
    m[1] == nothing && error("Invalid Excel range specified.")

    startrow = parse(Int, m[1].captures[2])
    startcol = col_number(m[1].captures[1])

    if length(m) == 1
        endrow = startrow
        endcol = startcol
    else
        endrow = parse(Int, m[2].captures[2])
        endcol = col_number(m[2].captures[1])
    end
    if (startrow > endrow ) || (startcol > endcol)
        error("Please provide rectangular region from top left to bottom right corner")
    end
    return startrow, startcol, endrow, endcol
end
function convert_ref_to_sheet_row_col(range::AbstractString)
    s = split(range, "!")
    return s[1], convert_ref_to_row_col(s[2])...
end

##############################################################################
##
## Basic properties of a WorkSheet
##
##############################################################################
Base.size(a::WorkSheet) = size(a.data)
Base.size(a::WorkSheet, d) = size(a.data, d)
Base.length(a::WorkSheet) = length(a.data)

Base.getindex(ws::WorkSheet, inds...) = getindex(ws.data, inds...)
function Base.getindex(ws::WorkSheet, range::AbstractString)
    rg = convert_ref_to_row_col(range)
    getindex(ws.data, rg[1]:rg[3], rg[2]:rg[4])
end

sheetname(ws::WorkSheet) = ws.name


text:
@testset "419.battleships-in-a-board.jl" begin
    @test count_battleships(['X' '.' '.' 'X'
                             '.' '.' '.' 'X'
                             '.' '.' '.' 'X']) == 2
    @test count_battleships(['.' '.' '.' 'X'
                             'X' 'X' '.' 'X'
                             '.' '.' '.' 'X']) == 2
end


text:
"""
    PyInternedString(x::String)

Convert `x` to an interned Python string.

This can provide a performance boost when using strings to index dictionaries or get attributes.

See also [`@pystr_str`](@ref).
"""
mutable struct PyInternedString
    ref::PyRef
    val::String
    PyInternedString(x::String) = new(PyRef(), x)
end
export PyInternedString

ispyreftype(::Type{PyInternedString}) = true
pyptr(x::PyInternedString) = begin
    ptr = x.ref.ptr
    if isnull(ptr)
        s = Ref{CPyPtr}()
        s[] = C.PyUnicode_From(x.val)
        isnull(s[]) && return ptr
        C.PyUnicode_InternInPlace(s)
        ptr = x.ref.ptr = s[]
    end
    ptr
end
Base.unsafe_convert(::Type{CPyPtr}, x::PyInternedString) = checknull(pyptr(x))

"""
    pystr"..." :: PyInternedString

Literal syntax for an interned Python string.
"""
macro pystr_str(s::String)
    PyInternedString(s)
end
export @pystr_str


text:
# Canonical form of multivariate normal

### Generic types

immutable MvNormalCanon{T<:Real,P<:AbstractPDMat,V<:Union{Vector,ZeroVector}} <: AbstractMvNormal
    μ::V    # the mean vector
    h::V    # potential vector, i.e. inv(Σ) * μ
    J::P    # precision matrix, i.e. inv(Σ)
end

const FullNormalCanon = MvNormalCanon{Float64, PDMat{Float64,Matrix{Float64}},Vector{Float64}}
const DiagNormalCanon = MvNormalCanon{Float64,PDiagMat{Float64,Vector{Float64}},Vector{Float64}}
const IsoNormalCanon  = MvNormalCanon{Float64,ScalMat{Float64},Vector{Float64}}

const ZeroMeanFullNormalCanon = MvNormalCanon{Float64,PDMat{Float64,Matrix{Float64}},ZeroVector{Float64}}
const ZeroMeanDiagNormalCanon = MvNormalCanon{Float64,PDiagMat{Float64,Vector{Float64}},ZeroVector{Float64}}
const ZeroMeanIsoNormalCanon  = MvNormalCanon{Float64,ScalMat{Float64},ZeroVector{Float64}}

### Constructors

function MvNormalCanon{T<:Real}(μ::Vector{T}, h::Vector{T}, J::AbstractPDMat{T})
    length(μ) == length(h) == dim(J) || throw(DimensionMismatch("Inconsistent argument dimensions"))
    MvNormalCanon{T,typeof(J),typeof(μ)}(μ, h, J)
end

function MvNormalCanon{T<:Real, P<:AbstractPDMat}(μ::Vector{T}, h::Vector{T}, J::P)
    R = promote_type(T, eltype(J))
    MvNormalCanon(convert(AbstractArray{R}, μ), convert(AbstractArray{R}, h), convert(AbstractArray{R}, J))
end

function MvNormalCanon{T<:Real, S<:Real, P<:AbstractPDMat}(μ::Vector{T}, h::Vector{S}, J::P)
    R = Base.promote_eltype(μ, h, J)
    MvNormalCanon(convert(AbstractArray{R}, μ), convert(AbstractArray{R}, h), convert(AbstractArray{R}, J))
end

function MvNormalCanon{P<:AbstractPDMat}(J::P)
    z = ZeroVector(eltype(J), dim(J))
    MvNormalCanon{eltype(J),P,ZeroVector{eltype(J)}}(z, z, J)
end

function MvNormalCanon{T<:Real, P<:AbstractPDMat}(h::Vector{T}, J::P)
    length(h) == dim(J) || throw(DimensionMismatch("Inconsistent argument dimensions"))
    R = Base.promote_eltype(h, J)
    hh, JJ = convert(AbstractArray{R}, h), convert(AbstractArray{R}, J)
    MvNormalCanon{eltype(hh),typeof(JJ),typeof(hh)}(JJ \ hh, hh, JJ)
end

MvNormalCanon{T<:Real}(h::Vector{T}, J::Matrix{T}) = MvNormalCanon(h, PDMat(J))
MvNormalCanon{T<:Real}(h::Vector{T}, prec::Vector{T}) = MvNormalCanon(h, PDiagMat(prec))
MvNormalCanon{T<:Real}(h::Vector{T}, prec::T) = MvNormalCanon(h, ScalMat(length(h), prec))

function MvNormalCanon{T<:Real, S<:Real}(h::Vector{T}, J::VecOrMat{S})
    R = Base.promote_eltype(h, J)
    MvNormalCanon(convert(AbstractArray{R}, h), convert(AbstractArray{R}, J))
end
function MvNormalCanon{T<:Real, S<:Real}(h::Vector{T}, prec::S)
    R = Base.promote_eltype(h, prec)
    MvNormalCanon(convert(AbstractArray{R}, h), R(prec))
end

MvNormalCanon(J::Matrix) = MvNormalCanon(PDMat(J))
MvNormalCanon(prec::Vector) = MvNormalCanon(PDiagMat(prec))
MvNormalCanon(d::Int, prec) = MvNormalCanon(ScalMat(d, prec))

### Show

distrname(d::IsoNormalCanon) = "IsoNormalCanon"
distrname(d::DiagNormalCanon) = "DiagNormalCanon"
distrname(d::FullNormalCanon) = "FullNormalCanon"

distrname(d::ZeroMeanIsoNormalCanon) = "ZeroMeanIsoNormalCanon"
distrname(d::ZeroMeanDiagNormalCanon) = "ZeroMeanDiagormalCanon"
distrname(d::ZeroMeanFullNormalCanon) = "ZeroMeanFullNormalCanon"

### Conversion
function convert{T<:Real}(::Type{MvNormalCanon{T}}, d::MvNormalCanon)
    MvNormalCanon(convert(AbstractArray{T}, d.μ), convert(AbstractArray{T}, d.h), convert(AbstractArray{T}, d.J))
end
function convert{T<:Real,V<:Union{Vector, ZeroVector}}(::Type{MvNormalCanon{T}}, μ::V, h::V, J::AbstractPDMat)
    MvNormalCanon(convert(AbstractArray{T}, μ), convert(AbstractArray{T}, h), convert(AbstractArray{T}, J))
end

### conversion between conventional form and canonical form

meanform(d::MvNormalCanon) = MvNormal(d.μ, inv(d.J))
# meanform{C, T<:Real}(d::MvNormalCanon{T,C,Vector{T}}) = MvNormal(d.μ, inv(d.J))
# meanform{C, T<:Real}(d::MvNormalCanon{T,C,ZeroVector{T}}) = MvNormal(inv(d.J))

canonform{C, T<:Real}(d::MvNormal{T,C,Vector{T}}) = (J = inv(d.Σ); MvNormalCanon(d.μ, J * d.μ, J))
canonform{C, T<:Real}(d::MvNormal{T,C,ZeroVector{T}}) = MvNormalCanon(inv(d.Σ))

### Basic statistics

length(d::MvNormalCanon) = length(d.μ)
mean(d::MvNormalCanon) = convert(Vector{eltype(d.μ)}, d.μ)
params(d::MvNormalCanon) = (d.μ, d.h, d.J)
@inline partype{T<:Real}(d::MvNormalCanon{T}) = T

var(d::MvNormalCanon) = diag(inv(d.J))
cov(d::MvNormalCanon) = full(inv(d.J))
invcov(d::MvNormalCanon) = full(d.J)
logdetcov(d::MvNormalCanon) = -logdet(d.J)

### Evaluation

sqmahal(d::MvNormalCanon, x::AbstractVector) = quad(d.J, x - d.μ)
sqmahal!(r::AbstractVector, d::MvNormalCanon, x::AbstractMatrix) = quad!(r, d.J, x .- d.μ)

# Sampling (for GenericMvNormal)

unwhiten_winv!(J::AbstractPDMat, x::AbstractVecOrMat) = unwhiten!(inv(J), x)
unwhiten_winv!(J::PDiagMat, x::AbstractVecOrMat) = whiten!(J, x)
unwhiten_winv!(J::ScalMat, x::AbstractVecOrMat) = whiten!(J, x)

_rand!(rng::AbstractRNG, d::MvNormalCanon, x::AbstractMatrix) = add!(unwhiten_winv!(d.J, randn!(rng,x)), d.μ)
_rand!(d::MvNormalCanon, x::AbstractMatrix) = _rand!(Base.GLOBAL_RNG, d, x)


text:
type Extrapolation{T,N,ITPT,IT,GT,ET} <: AbstractInterpolationWrapper{T,N,ITPT,IT,GT}
    itp::ITPT
end
Extrapolation{T,ITPT,IT,GT,ET}(::Type{T}, N, itp::ITPT, ::Type{IT}, ::Type{GT}, et::ET) =
    Extrapolation{T,N,ITPT,IT,GT,ET}(itp)

# DimSpec{Flag} is not enough for extrapolation dispatch, since we allow nested tuples
# However, no tuples should be nested deeper than this; the first level is for different
# schemes in different dimensions, and the second level is for different schemes in
# different directions.
typealias ExtrapDimSpec Union{Flag,Tuple{Vararg{Union{Flag,NTuple{2,Flag}}}}}

"""
`extrapolate(itp, scheme)` adds extrapolation behavior to an interpolation object, according to the provided scheme.

The scheme can take any of these values:

* `Throw` - throws a BoundsError for out-of-bounds indices
* `Flat` - for constant extrapolation, taking the closest in-bounds value
* `Linear` - linear extrapolation (the wrapped interpolation object must support gradient)
* `Reflect` - reflecting extrapolation (indices must support `mod`)
* `Periodic` - periodic extrapolation (indices must support `mod`)

You can also combine schemes in tuples. For example, the scheme `(Linear(), Flat())` will use linear extrapolation in the first dimension, and constant in the second.

Finally, you can specify different extrapolation behavior in different direction. `((Linear(),Flat()), Flat())` will extrapolate linearly in the first dimension if the index is too small, but use constant etrapolation if it is too large, and always use constant extrapolation in the second dimension.
"""
extrapolate{T,N,IT,GT,ET<:ExtrapDimSpec}(itp::AbstractInterpolation{T,N,IT,GT}, et::ET) =
    Extrapolation(T,N,itp,IT,GT,et)

include("throw.jl")
include("flat.jl")
include("linear.jl")
include("reflect.jl")
include("periodic.jl")

include("extrap_prep.jl")
include("extrap_prep_gradient.jl")

"""
`getindex_impl(::Type{E<:Extrapolation}, xs...)`

Generates an expression to be used
as the function body of the getindex method for the given type of extrapolation
and indices. The heavy lifting is done by the `extrap_prep` function; see
`?extrap_prep` for details.
"""
function getindex_impl{T,N,ITPT,IT,GT,ET}(etp::Type{Extrapolation{T,N,ITPT,IT,GT,ET}}, xs...)
    coords = [Symbol("xs_",d) for d in 1:N]
    quote
        @nexprs $N d->(xs_d = xs[d])
        $(extrap_prep(ET, Val{N}()))
        etp.itp[$(coords...)]
    end
end

@generated function getindex{T,N,ITPT,IT,GT,ET}(etp::Extrapolation{T,N,ITPT,IT,GT,ET}, xs...)
    getindex_impl(etp, xs...)
end

function gradient!_impl{T,N,ITPT,IT,GT,ET}(g, etp::Type{Extrapolation{T,N,ITPT,IT,GT,ET}}, xs...)
    coords = [Symbol("xs_", d) for d in 1:N]
    quote
        @nexprs $N d->(xs_d = xs[d])
        $(extrap_prep(Val{:gradient}(), ET, Val{N}()))
        gradient!(g, etp.itp, $(coords...))
    end
end

@generated function gradient!{T,N,ITPT,IT,GT,ET}(g::AbstractVector, etp::Extrapolation{T,N,ITPT,IT,GT,ET}, xs...)
    gradient!_impl(g, etp, xs...)
end

lbound(etp::Extrapolation, d) = lbound(etp.itp, d)
ubound(etp::Extrapolation, d) = ubound(etp.itp, d)
size(etp::Extrapolation, d) = size(etp.itp, d)

include("filled.jl")


text:
using ITensors

function local_boltzmann_weight(m::String, args...; kwargs...)
  return local_boltzmann_weight(Model(m), args...; kwargs...)
end

f(λ₊, λ₋) = [
  (λ₊ + λ₋)/2 (λ₊ - λ₋)/2
  (λ₊ - λ₋)/2 (λ₊ + λ₋)/2
]

function sqrt_bond_matrix(; β::Real, J::Real=1.0)
  # Alternative method
  #Q = [exp(β * J) exp(-β * J); exp(-β * J) exp(β * J)]
  #return √Q
  λ₊ = √(exp(β * J) + exp(-β * J))
  λ₋ = √(exp(β * J) - exp(-β * J))
  return f(λ₊, λ₋)
end

# The local Boltzmann weight for the Ising
# model in 1 dimension
function local_boltzmann_weight(
  ::Model"ising", ::Val{1}; β::Real, J::Real=1.0, sz::Bool=false
)
  d = 2 # local dimension of the Ising local Boltzmann factor
  s, s′ = Index.((d, d))
  T = ITensor(s, s′)
  for i in 1:d
    T[i, i] = 1.0
  end
  if sz
    T[1, 1] = -T[1, 1]
  end
  s̃, s̃′ = sim.((s, s′))
  T̃ = T * δ(s, s̃) * δ(s′, s̃′)
  sqrtQ = sqrt_bond_matrix(; β=β, J=J)
  @show sqrtQ
  X = itensor(vec(sqrtQ), s̃, s)
  X′ = itensor(vec(sqrtQ), s̃′, s′)
  return array(permute(T̃ * X′ * X, s, s′))
end

# The local Boltzmann weight for the Ising
# model in 2 dimensions
function local_boltzmann_weight(
  ::Model"ising", ::Val{2}; β::Real, J::Real=1.0, sz::Bool=false
)
  d = 2 # local dimension of the Ising local Boltzmann factor
  sₕ, sₕ′ = Index.((d, d))
  sᵥ, sᵥ′ = Index.((d, d))
  @assert dim(sₕ) == dim(sᵥ)
  d = dim(sₕ)
  T = ITensor(sₕ, sₕ′, sᵥ, sᵥ′)
  for i in 1:d
    T[i, i, i, i] = 1.0
  end
  if sz
    T[1, 1, 1, 1] = -T[1, 1, 1, 1]
  end
  s̃ₕ, s̃ₕ′, s̃ᵥ, s̃ᵥ′ = sim.((sₕ, sₕ′, sᵥ, sᵥ′))
  T̃ = T * δ(sₕ, s̃ₕ) * δ(sₕ′, s̃ₕ′) * δ(sᵥ, s̃ᵥ) * δ(sᵥ′, s̃ᵥ′)
  X = sqrt_bond_matrix(; β=β, J=J)
  Xₕ = itensor(vec(X), s̃ₕ, sₕ)
  Xₕ′ = itensor(vec(X), s̃ₕ′, sₕ′)
  Xᵥ = itensor(vec(X), s̃ᵥ, sᵥ)
  Xᵥ′ = itensor(vec(X), s̃ᵥ′, sᵥ′)
  return array(permute(T̃ * Xₕ′ * Xᵥ′ * Xₕ * Xᵥ, sₕ, sₕ′, sᵥ, sᵥ′))
end

function mpo_itensor(
  m::Model, pair_sₕ::Pair{<:Index,<:Index}, pair_sᵥ::Pair{<:Index,<:Index}; kwargs...
)
  sₕ, sₕ′ = pair_sₕ
  sᵥ, sᵥ′ = pair_sᵥ
  return itensor(mpo_array(m; kwargs...), sₕ, sₕ′, sᵥ, sᵥ′)
end

critical_point(::Model"ising") = 0.5 * log(√2 + 1)

function free_energy(::Model"ising"; β::Real, J::Real=1.0)
  k = β * J
  c = cosh(2 * k)
  s = sinh(2 * k)
  xmin = 0.0
  xmax = π
  integrand(x) = log(c^2 + √(s^4 + 1 - 2 * s^2 * cos(x)))
  integral, err = quadgk(integrand, xmin, xmax)::Tuple{Float64,Float64}
  return -(log(2) + integral / π) / (2 * β)
end

function magnetization(::Model"ising"; β::Real)
  β > βc && return (1 - sinh(2 * β)^(-4))^(1 / 8)
  return 0.0
end


text:
######### StanSample example  ###########

using StanSample

bernoulli_model = "
data {
  int<lower=1> N;
  int<lower=0,upper=1> y[N];
}
parameters {
  real<lower=0,upper=1> theta;
}
model {
  theta ~ beta(1,1);
  y ~ bernoulli(theta);
}
";

bernoulli_data = Dict("N" => 10, "y" => [0, 1, 0, 1, 0, 0, 0, 0, 0, 1])

# Keep tmpdir identical to prevent re-compilation
stanmodel = SampleModel(
  "bernoulli", bernoulli_model;
  method = StanSample.Sample(adapt=StanSample.Adapt(delta=0.85)))

stan_sample(stanmodel, data=bernoulli_data, n_chains=6, diagnostics=true)

# Fetch the same output in the `sdf` ChainDataFrame
sdf = read_summary(stanmodel)


text:
"""
Correlogram(data::AbstractVector, lag::Int64 = 20, fft::Bool = true)

Correlogram function calculates the autocorrelation function of given data. To use this software, you must input your dataset into a 'data' argument. You have two options to calculate autocorrelation, which use Fourier fast transformation (FFT) and calculate by its definition. We calculate the autocorrelation function by lag if you set 'lag' arguments. If you set 'fft' argument true, we calculate the autocorrelation function by FFT. Otherwise, we calculate them by definition.
"""
function Correlogram(d::AbstractVector, l::Int64 = 20, f::Bool = true ;data::AbstractVector = d, lag::Int64 = l, fft::Bool = f)
    n::Int64 = length(data)
    s::Float64 = zeros(Float64, 2*n-1 )
    s[1:n] .= data
    Fs = real.(ifft(abs2.(fft(s))))
    return Fs
end

max_stars_repo_name: yukki-jpn/JuliaTSA

max_issues_repo_name: yukki-jpn/JuliaTSA

max_forks_repo_name: yukki-jpn/JuliaTSA


text:
# This file is part of the TaylorSeries.jl Julia package, MIT license

# Hash tables for HomogeneousPolynomial and TaylorN

doc"""
    generate_tables(num_vars, order)

Return the hash tables `coeff_table`, `index_table`, `size_table`
and `pos_table`. Internally, these are treated as `const`.

# Hash tables

    coeff_table :: Array{Array{Array{Int64,1},1},1}

The $i+1$-th component contains a vector with the vectors of all the possible
combinations of monomials of a `HomogeneousPolynomial` of order $i$.

    index_table :: Array{Array{Int64,1},1}

The $i+1$-th component contains a vector of (hashed) indices that represent
the distinct monomials of a `HomogeneousPolynomial` of order (degree) $i$.

    size_table :: Array{Int64,1}

The $i+1$-th component contains the number of distinct monomials of the
`HomogeneousPolynomial` of order $i$, equivalent to `length(coeff_table[i])`.

    pos_table :: Array{Dict{Int64,Int64},1}

The $i+1$-th component maps the hash index to the (lexicographic) position
of the corresponding monomial in `coeffs_table`.
"""
function generate_tables(num_vars, order)
    coeff_table = [generate_index_vectors(num_vars, i) for i in 0:order]

    index_table = Vector{Int}[map(x->in_base(order, x), coeffs) for coeffs in coeff_table]

    pos_table = map(make_inverse_dict, index_table)
    size_table = map(length, index_table)

    coeff_table, index_table, size_table, pos_table
end

"""
    generate_index_vectors(num_vars, degree)

Return a vector of index vectors with `num_vars` (number of variables) and
degree.
"""
function generate_index_vectors(num_vars, degree)
    if num_vars == 1
        return Vector{Int}[ [degree] ]
    end

    indices = Vector{Int}[]

    for k in degree:-1:0

        new_indices = [ [k, x...] for x in generate_index_vectors(num_vars-1, degree-k) ]
        append!(indices, new_indices)

    end

    indices
end

function make_forward_dict(v::Vector)
    @compat Dict([i=>x for (i,x) in enumerate(v)])
end

"""
    make_inverse_dict(v)

Return a Dict with the enumeration of `v`: the elements of `v` point to
the corresponding index.

It is used to construct `pos_table` from `index_table`.
"""
function make_inverse_dict(v::Vector)
    @compat Dict([x=>i for (i,x) in enumerate(v)])
end

"""
    in_base(order, v)

Convert vector `v` of non-negative integers to base `order+1`.
"""
function in_base(order, v)
    order = order+1

    result = 0

    for i in v
        result = result*order + i
    end

    result
end

const coeff_table, index_table, size_table, pos_table =
    generate_tables(get_numvars(), get_order())

# Garbage-collect here to free memory
gc();


text:
#
println("Ci) Test of the DecayYield module with ASF from an internally generated multiplet.")
#
setDefaults("print summary: open", "zzz-DecayYield.sum")
wa = Atomic.Computation(Atomic.Computation(), name="xx", grid=JAC.Radial.Grid(false), nuclearModel=Nuclear.Model(12.),
                        properties=[Yields()],
                        configs=[Configuration("1s 2s^2 2p^6")],
                        yieldSettings=DecayYield.Settings("SCA", true, false, Int64[]) )

wb = perform(wa)
setDefaults("print summary: close", "")


text:
# Richardson function
function numdiff(f,x::Number,h::Float64)
    D0 = (f(x+h)-f(x-h))/(2*h);
    D1 = ( f(x+(h/2)) - f(x-(h/2)) )/(h);
    TV = D1 + (D1-D0)/3
    return TV
end

# Richardson function
function numdiff(f,x::Number,h::Int64)
    D0 = (f(x+h)-f(x-h))/(2*h);
    D1 = ( f(x+(h/2)) - f(x-(h/2)) )/(h);
    TV = D1 + (D1-D0)/3
    return TV
end

# Richardson discrete of type 1 (We get an exact value in x vector in which we want to differentiate)
function numdiff(x::Array{Float64,1}, y::Array{Float64,1}, val) #We get a x array, a y array and a val in x for which we want to get its derivative
    h = abs(x[2] - x[1]);
    ind = findall(p->p==val, x)[1]
    D0 = (y[ind+2]-y[ind-2])/(4*h);
    D1 = (y[ind+1]-y[ind-1])/(2*h);
    TV = D1 + (D1-D0)/3
    return TV
end

# Richardson getting the whole bunch i.e. CDD of O(h^4) residues

#=
function numdiff(x::Array{Float64,1}, y::Array{Float64,1}) #We get a x array, a y array and a val in x for which we want to get its derivative
    h = abs(x[2] - x[1]);

    return TV
end
=#

# Forward func of linear order
function fdiff(f,x,h)
    d = (f(x+h)-f(x))/h;
    return d
end

# Forward discrete of type 1 (We get an exact value in x vector in which we want to differentiate)
function fdiff(x::Array{Float64,1}, y::Array{Float64,1},val)
    h = abs( x[2] - x[1] );
    ind = findall(p->p==val, x)[1]
    d = (y[ind+1] - y[ind])/h
    return d
end

# Forward discrete, with the whole bunch (MATLAB-like, with the whole vector)
function fdiff(x::Array{Float64,1}, y::Array{Float64,1})
    h = abs( x[2] - x[1] );
    d = (y[2:end] - y[1:end-1])/h
    return d
end

# Backwards func
function bdiff(f,x,h)
    d = (f(x)-f(x-h))/h;
    return d
end

# Backwards discrete of type 1 (We get an exact value in x vector in which we want to differentiate)
function bdiff(x::Array{Float64,1}, y::Array{Float64,1},val)
    h = abs( x[2] - x[1] );
    ind = findall(p->p==val, x)[1]
    d = (y[ind] - y[ind-1])/h
    return d
end

# Backwards discrete, with the whole bunch (MATLAB-like, with the whole vector)
function bdiff(x::Array{Float64,1}, y::Array{Float64,1})
    h = abs( x[2] - x[1] );
    d = (y[2:end] - y[1:end-1])/h
    return d
end


text:
struct Rule
    name::AbstractString
    ranges::AbstractVector{AbstractRange{Int}}
end

function parserule(line::AbstractString)
    m = match(r"^([^:]+): ([0-9]+)-([0-9]+) or ([0-9]+)-([0-9]+)$", line)
    name = m.captures[1]
    range1_start = parse(Int, m.captures[2])
    range1_end = parse(Int, m.captures[3])
    range2_start = parse(Int, m.captures[4])
    range2_end = parse(Int, m.captures[5])
    return Rule(name, [range1_start:range1_end, range2_start:range2_end])
end

function getinput(filename)
    contents = read(filename, String)
    parts = split(contents, "\n\n")
    rules = [parserule(line) for line ∈ split(parts[1], "\n")]
    my_ticket_line = split(parts[2], "\n")[2]
    my_ticket = parse.(Int, split(my_ticket_line, ","))
    nearby_tickets_lines = split(parts[3], "\n")[2:end]
    nearby_tickets = map(line -> parse.(Int, split(line, ",")), nearby_tickets_lines)
    return (rules, my_ticket, nearby_tickets)
end

meetsrule(rule::Rule, value::Int) = any(range -> value ∈ range, rule.ranges)

meetsrules(rules::AbstractVector{Rule}, value) = any(rule -> meetsrule(rule, value), rules)

function day1(filename="day16input.txt")
    rules, my_ticket, nearby_tickets = getinput(filename)
    invalid = Int[]
    for t ∈ nearby_tickets
        append!(invalid, filter(value -> !meetsrules(rules, value), t))
    end
    sum(invalid)
end

function allvalid(rules::AbstractVector{Rule}, ticket)
    all(value -> meetsrules(rules, value), ticket)
end

function possible_field_names(rules, value)
    possible = Set{String}()
    for rule ∈ rules
        if meetsrule(rule, value)
            push!(possible, rule.name)
        end
    end
    return possible
end

function map_field_number_to_possible_names(rules, tickets)
    possible_names = Dict{Int,Set{String}}()
    for ticket ∈ tickets
        for i ∈ 1:length(ticket)
            if i ∈ keys(possible_names)
                intersect!(possible_names[i], possible_field_names(rules, ticket[i]))
            else
                possible_names[i] = possible_field_names(rules, ticket[i])
            end
        end
    end
    return possible_names
end

function remove_field_name!(possible_names, name)
    for i ∈ keys(possible_names)
        if name ∈ possible_names[i]
            pop!(possible_names[i], name)
        end
    end
end

function find_mapping(rules, tickets)
    possible_names = map_field_number_to_possible_names(rules, tickets)
    unmapped = Set(1:20)
    mapping = similar(1:20, Union{String,Nothing})
    fill!(mapping, nothing)
    changed = true
    while changed
        changed = false
        for i ∈ 1:20
            if mapping[i] !== nothing
                continue
            elseif length(possible_names[i]) == 1
                mapping[i] = only(possible_names[i])
                remove_field_name!(possible_names, mapping[i])
                changed = true
            end
        end
    end
    return Dict(name=>i for (i, name) ∈ enumerate(mapping))
end

function day2(filename="day16input.txt")
    rules, my_ticket, nearby_tickets = getinput(filename)
    valid_tickets = filter(ticket -> allvalid(rules, ticket), nearby_tickets)
    println("Total tickets: ", length(nearby_tickets))
    println("Valid nearby tickets: ", length(valid_tickets))
    possible_fields = map_field_number_to_possible_names(rules, vcat(valid_tickets, [my_ticket]))
    mapping = find_mapping(rules, vcat(valid_tickets, [my_ticket]))
    departure_names = collect(filter(startswith("departure"), keys(mapping)))
    indices = map(s->mapping[s], departure_names)
    return prod(my_ticket[indices])
end

day1()
day2()


text:
Pkg.update()
Pkg.add("DataFrames")
x = DataArray([1.1, 2.2, 3.3, 4.4, 5.5, 6.6])
x[1] = NA
true || x
mean(x)
mean(x[2:6])

max_stars_repo_path: Chapter 2/1.jl

max_stars_repo_name: PacktPublishing/Julia-for-data-science

max_issues_repo_path: Chapter 2/1.jl

max_issues_repo_name: PacktPublishing/Julia-for-data-science

max_forks_repo_path: Chapter 2/1.jl

max_forks_repo_name: PacktPublishing/Julia-for-data-science