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

"""
    add_tags(load_balancer_names, tags)
    add_tags(load_balancer_names, tags, params::Dict{String,<:Any})

Adds the specified tags to the specified load balancer. Each load balancer can have a
maximum of 10 tags. Each tag consists of a key and an optional value. If a tag with the
same key is already associated with the load balancer, AddTags updates its value. For more
information, see Tag Your Classic Load Balancer in the Classic Load Balancers Guide.

# Arguments
- `load_balancer_names`: The name of the load balancer. You can specify one load balancer
  only.
- `tags`: The tags.

"""
add_tags(LoadBalancerNames, Tags; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing("AddTags", Dict{String, Any}("LoadBalancerNames"=>LoadBalancerNames, "Tags"=>Tags); aws_config=aws_config)
add_tags(LoadBalancerNames, Tags, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing("AddTags", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("LoadBalancerNames"=>LoadBalancerNames, "Tags"=>Tags), params)); aws_config=aws_config)

"""
    apply_security_groups_to_load_balancer(load_balancer_name, security_groups)
    apply_security_groups_to_load_balancer(load_balancer_name, security_groups, params::Dict{String,<:Any})

Associates one or more security groups with your load balancer in a virtual private cloud
(VPC). The specified security groups override the previously associated security groups.
For more information, see Security Groups for Load Balancers in a VPC in the Classic Load
Balancers Guide.

# Arguments
- `load_balancer_name`: The name of the load balancer.
- `security_groups`: The IDs of the security groups to associate with the load balancer.
  Note that you cannot specify the name of the security group.

"""
apply_security_groups_to_load_balancer(LoadBalancerName, SecurityGroups; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing("ApplySecurityGroupsToLoadBalancer", Dict{String, Any}("LoadBalancerName"=>LoadBalancerName, "SecurityGroups"=>SecurityGroups); aws_config=aws_config)
apply_security_groups_to_load_balancer(LoadBalancerName, SecurityGroups, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing("ApplySecurityGroupsToLoadBalancer", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("LoadBalancerName"=>LoadBalancerName, "SecurityGroups"=>SecurityGroups), params)); aws_config=aws_config)

"""
    attach_load_balancer_to_subnets(load_balancer_name, subnets)
    attach_load_balancer_to_subnets(load_balancer_name, subnets, params::Dict{String,<:Any})

Adds one or more subnets to the set of configured subnets for the specified load balancer.
The load balancer evenly distributes requests across all registered subnets. For more
information, see Add or Remove Subnets for Your Load Balancer in a VPC in the Classic Load
Balancers Guide.

# Arguments
- `load_balancer_name`: The name of the load balancer.
- `subnets`: The IDs of the subnets to add. You can add only one subnet per Availability
  Zone.

"""
attach_load_balancer_to_subnets(LoadBalancerName, Subnets; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing("AttachLoadBalancerToSubnets", Dict{String, Any}("LoadBalancerName"=>LoadBalancerName, "Subnets"=>Subnets); aws_config=aws_config)
attach_load_balancer_to_subnets(LoadBalancerName, Subnets, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing("AttachLoadBalancerToSubnets", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("LoadBalancerName"=>LoadBalancerName, "Subnets"=>Subnets), params)); aws_config=aws_config)

"""
    configure_health_check(health_check, load_balancer_name)
    configure_health_check(health_check, load_balancer_name, params::Dict{String,<:Any})

Specifies the health check settings to use when evaluating the health state of your EC2
instances. For more information, see Configure Health Checks for Your Load Balancer in the
Classic Load Balancers Guide.

# Arguments
- `health_check`: The configuration information.
- `load_balancer_name`: The name of the load balancer.

"""
configure_health_check(HealthCheck, LoadBalancerName; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing("ConfigureHealthCheck", Dict{String, Any}("HealthCheck"=>HealthCheck, "LoadBalancerName"=>LoadBalancerName); aws_config=aws_config)
configure_health_check(HealthCheck, LoadBalancerName, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing("ConfigureHealthCheck", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("HealthCheck"=>HealthCheck, "LoadBalancerName"=>LoadBalancerName), params)); aws_config=aws_config)

"""
    create_app_cookie_stickiness_policy(cookie_name, load_balancer_name, policy_name)
    create_app_cookie_stickiness_policy(cookie_name, load_balancer_name, policy_name, params::Dict{String,<:Any})

Generates a stickiness policy with sticky session lifetimes that follow that of an
application-generated cookie. This policy can be associated only with HTTP/HTTPS listeners.
This policy is similar to the policy created by CreateLBCookieStickinessPolicy, except that
the lifetime of the special Elastic Load Balancing cookie, AWSELB, follows the lifetime of
the application-generated cookie specified in the policy configuration. The load balancer
only inserts a new stickiness cookie when the application response includes a new
application cookie. If the application cookie is explicitly removed or expires, the session
stops being sticky until a new application cookie is issued. For more information, see
Application-Controlled Session Stickiness in the Classic Load Balancers Guide.

# Arguments
- `cookie_name`: The name of the application cookie used for stickiness.
- `load_balancer_name`: The name of the load balancer.
- `policy_name`: The name of the policy being created. Policy names must consist of
  alphanumeric characters and dashes (-). This name must be unique within the set of policies
  for this load balancer.

"""
create_app_cookie_stickiness_policy(CookieName, LoadBalancerName, PolicyName; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing("CreateAppCookieStickinessPolicy", Dict{String, Any}("CookieName"=>CookieName, "LoadBalancerName"=>LoadBalancerName, "PolicyName"=>PolicyName); aws_config=aws_config)
create_app_cookie_stickiness_policy(CookieName, LoadBalancerName, PolicyName, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing("CreateAppCookieStickinessPolicy", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("CookieName"=>CookieName, "LoadBalancerName"=>LoadBalancerName, "PolicyName"=>PolicyName), params)); aws_config=aws_config)

"""
    create_lbcookie_stickiness_policy(load_balancer_name, policy_name)
    create_lbcookie_stickiness_policy(load_balancer_name, policy_name, params::Dict{String,<:Any})

Generates a stickiness policy with sticky session lifetimes controlled by the lifetime of
the browser (user-agent) or a specified expiration period. This policy can be associated
only with HTTP/HTTPS listeners. When a load balancer implements this policy, the load
balancer uses a special cookie to track the instance for each request. When the load
balancer receives a request, it first checks to see if this cookie is present in the
request. If so, the load balancer sends the request to the application server specified in
the cookie. If not, the load balancer sends the request to a server that is chosen based on
the existing load-balancing algorithm. A cookie is inserted into the response for binding
subsequent requests from the same user to that server. The validity of the cookie is based
on the cookie expiration time, which is specified in the policy configuration. For more
information, see Duration-Based Session Stickiness in the Classic Load Balancers Guide.

# Arguments
- `load_balancer_name`: The name of the load balancer.
- `policy_name`: The name of the policy being created. Policy names must consist of
  alphanumeric characters and dashes (-). This name must be unique within the set of policies
  for this load balancer.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"CookieExpirationPeriod"`: The time period, in seconds, after which the cookie should be
  considered stale. If you do not specify this parameter, the default value is 0, which
  indicates that the sticky session should last for the duration of the browser session.
"""
create_lbcookie_stickiness_policy(LoadBalancerName, PolicyName; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing("CreateLBCookieStickinessPolicy", Dict{String, Any}("LoadBalancerName"=>LoadBalancerName, "PolicyName"=>PolicyName); aws_config=aws_config)
create_lbcookie_stickiness_policy(LoadBalancerName, PolicyName, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing("CreateLBCookieStickinessPolicy", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("LoadBalancerName"=>LoadBalancerName, "PolicyName"=>PolicyName), params)); aws_config=aws_config)

"""
    create_load_balancer(listeners, load_balancer_name)
    create_load_balancer(listeners, load_balancer_name, params::Dict{String,<:Any})

Creates a Classic Load Balancer. You can add listeners, security groups, subnets, and tags
when you create your load balancer, or you can add them later using
CreateLoadBalancerListeners, ApplySecurityGroupsToLoadBalancer,
AttachLoadBalancerToSubnets, and AddTags. To describe your current load balancers, see
DescribeLoadBalancers. When you are finished with a load balancer, you can delete it using
DeleteLoadBalancer. You can create up to 20 load balancers per region per account. You can
request an increase for the number of load balancers for your account. For more
information, see Limits for Your Classic Load Balancer in the Classic Load Balancers Guide.

# Arguments
- `listeners`: The listeners. For more information, see Listeners for Your Classic Load
  Balancer in the Classic Load Balancers Guide.
- `load_balancer_name`: The name of the load balancer. This name must be unique within your
  set of load balancers for the region, must have a maximum of 32 characters, must contain
  only alphanumeric characters or hyphens, and cannot begin or end with a hyphen.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"AvailabilityZones"`: One or more Availability Zones from the same region as the load
  balancer. You must specify at least one Availability Zone. You can add more Availability
  Zones after you create the load balancer using EnableAvailabilityZonesForLoadBalancer.
- `"Scheme"`: The type of a load balancer. Valid only for load balancers in a VPC. By
  default, Elastic Load Balancing creates an Internet-facing load balancer with a DNS name
  that resolves to public IP addresses. For more information about Internet-facing and
  Internal load balancers, see Load Balancer Scheme in the Elastic Load Balancing User Guide.
  Specify internal to create a load balancer with a DNS name that resolves to private IP
  addresses.
- `"SecurityGroups"`: The IDs of the security groups to assign to the load balancer.
- `"Subnets"`: The IDs of the subnets in your VPC to attach to the load balancer. Specify
  one subnet per Availability Zone specified in AvailabilityZones.
- `"Tags"`: A list of tags to assign to the load balancer. For more information about
  tagging your load balancer, see Tag Your Classic Load Balancer in the Classic Load
  Balancers Guide.
"""
create_load_balancer(Listeners, LoadBalancerName; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing("CreateLoadBalancer", Dict{String, Any}("Listeners"=>Listeners, "LoadBalancerName"=>LoadBalancerName); aws_config=aws_config)
create_load_balancer(Listeners, LoadBalancerName, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing("CreateLoadBalancer", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Listeners"=>Listeners, "LoadBalancerName"=>LoadBalancerName), params)); aws_config=aws_config)

"""
    create_load_balancer_listeners(listeners, load_balancer_name)
    create_load_balancer_listeners(listeners, load_balancer_name, params::Dict{String,<:Any})

Creates one or more listeners for the specified load balancer. If a listener with the
specified port does not already exist, it is created; otherwise, the properties of the new
listener must match the properties of the existing listener. For more information, see
Listeners for Your Classic Load Balancer in the Classic Load Balancers Guide.

# Arguments
- `listeners`: The listeners.
- `load_balancer_name`: The name of the load balancer.

"""
create_load_balancer_listeners(Listeners, LoadBalancerName; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing("CreateLoadBalancerListeners", Dict{String, Any}("Listeners"=>Listeners, "LoadBalancerName"=>LoadBalancerName); aws_config=aws_config)
create_load_balancer_listeners(Listeners, LoadBalancerName, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing("CreateLoadBalancerListeners", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Listeners"=>Listeners, "LoadBalancerName"=>LoadBalancerName), params)); aws_config=aws_config)

"""
    create_load_balancer_policy(load_balancer_name, policy_name, policy_type_name)
    create_load_balancer_policy(load_balancer_name, policy_name, policy_type_name, params::Dict{String,<:Any})

Creates a policy with the specified attributes for the specified load balancer. Policies
are settings that are saved for your load balancer and that can be applied to the listener
or the application server, depending on the policy type.

# Arguments
- `load_balancer_name`: The name of the load balancer.
- `policy_name`: The name of the load balancer policy to be created. This name must be
  unique within the set of policies for this load balancer.
- `policy_type_name`: The name of the base policy type. To get the list of policy types,
  use DescribeLoadBalancerPolicyTypes.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"PolicyAttributes"`: The policy attributes.
"""
create_load_balancer_policy(LoadBalancerName, PolicyName, PolicyTypeName; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing("CreateLoadBalancerPolicy", Dict{String, Any}("LoadBalancerName"=>LoadBalancerName, "PolicyName"=>PolicyName, "PolicyTypeName"=>PolicyTypeName); aws_config=aws_config)
create_load_balancer_policy(LoadBalancerName, PolicyName, PolicyTypeName, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing("CreateLoadBalancerPolicy", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("LoadBalancerName"=>LoadBalancerName, "PolicyName"=>PolicyName, "PolicyTypeName"=>PolicyTypeName), params)); aws_config=aws_config)

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

Deletes the specified load balancer. If you are attempting to recreate a load balancer, you
must reconfigure all settings. The DNS name associated with a deleted load balancer are no
longer usable. The name and associated DNS record of the deleted load balancer no longer
exist and traffic sent to any of its IP addresses is no longer delivered to your instances.
If the load balancer does not exist or has already been deleted, the call to
DeleteLoadBalancer still succeeds.

# Arguments
- `load_balancer_name`: The name of the load balancer.

"""
delete_load_balancer(LoadBalancerName; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing("DeleteLoadBalancer", Dict{String, Any}("LoadBalancerName"=>LoadBalancerName); aws_config=aws_config)
delete_load_balancer(LoadBalancerName, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing("DeleteLoadBalancer", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("LoadBalancerName"=>LoadBalancerName), params)); aws_config=aws_config)

"""
    delete_load_balancer_listeners(load_balancer_name, load_balancer_ports)
    delete_load_balancer_listeners(load_balancer_name, load_balancer_ports, params::Dict{String,<:Any})

Deletes the specified listeners from the specified load balancer.

# Arguments
- `load_balancer_name`: The name of the load balancer.
- `load_balancer_ports`: The client port numbers of the listeners.

"""
delete_load_balancer_listeners(LoadBalancerName, LoadBalancerPorts; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing("DeleteLoadBalancerListeners", Dict{String, Any}("LoadBalancerName"=>LoadBalancerName, "LoadBalancerPorts"=>LoadBalancerPorts); aws_config=aws_config)
delete_load_balancer_listeners(LoadBalancerName, LoadBalancerPorts, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing("DeleteLoadBalancerListeners", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("LoadBalancerName"=>LoadBalancerName, "LoadBalancerPorts"=>LoadBalancerPorts), params)); aws_config=aws_config)

"""
    delete_load_balancer_policy(load_balancer_name, policy_name)
    delete_load_balancer_policy(load_balancer_name, policy_name, params::Dict{String,<:Any})

Deletes the specified policy from the specified load balancer. This policy must not be
enabled for any listeners.

# Arguments
- `load_balancer_name`: The name of the load balancer.
- `policy_name`: The name of the policy.

"""
delete_load_balancer_policy(LoadBalancerName, PolicyName; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing("DeleteLoadBalancerPolicy", Dict{String, Any}("LoadBalancerName"=>LoadBalancerName, "PolicyName"=>PolicyName); aws_config=aws_config)
delete_load_balancer_policy(LoadBalancerName, PolicyName, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing("DeleteLoadBalancerPolicy", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("LoadBalancerName"=>LoadBalancerName, "PolicyName"=>PolicyName), params)); aws_config=aws_config)

"""
    deregister_instances_from_load_balancer(instances, load_balancer_name)
    deregister_instances_from_load_balancer(instances, load_balancer_name, params::Dict{String,<:Any})

Deregisters the specified instances from the specified load balancer. After the instance is
deregistered, it no longer receives traffic from the load balancer. You can use
DescribeLoadBalancers to verify that the instance is deregistered from the load balancer.
For more information, see Register or De-Register EC2 Instances in the Classic Load
Balancers Guide.

# Arguments
- `instances`: The IDs of the instances.
- `load_balancer_name`: The name of the load balancer.

"""
deregister_instances_from_load_balancer(Instances, LoadBalancerName; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing("DeregisterInstancesFromLoadBalancer", Dict{String, Any}("Instances"=>Instances, "LoadBalancerName"=>LoadBalancerName); aws_config=aws_config)
deregister_instances_from_load_balancer(Instances, LoadBalancerName, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing("DeregisterInstancesFromLoadBalancer", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Instances"=>Instances, "LoadBalancerName"=>LoadBalancerName), params)); aws_config=aws_config)

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

Describes the current Elastic Load Balancing resource limits for your AWS account. For more
information, see Limits for Your Classic Load Balancer in the Classic Load Balancers Guide.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Marker"`: The marker for the next set of results. (You received this marker from a
  previous call.)
- `"PageSize"`: The maximum number of results to return with this call.
"""
describe_account_limits(; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing("DescribeAccountLimits"; aws_config=aws_config)
describe_account_limits(params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing("DescribeAccountLimits", params; aws_config=aws_config)

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

Describes the state of the specified instances with respect to the specified load balancer.
If no instances are specified, the call describes the state of all instances that are
currently registered with the load balancer. If instances are specified, their state is
returned even if they are no longer registered with the load balancer. The state of
terminated instances is not returned.

# Arguments
- `load_balancer_name`: The name of the load balancer.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Instances"`: The IDs of the instances.
"""
describe_instance_health(LoadBalancerName; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing("DescribeInstanceHealth", Dict{String, Any}("LoadBalancerName"=>LoadBalancerName); aws_config=aws_config)
describe_instance_health(LoadBalancerName, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing("DescribeInstanceHealth", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("LoadBalancerName"=>LoadBalancerName), params)); aws_config=aws_config)

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

Describes the attributes for the specified load balancer.

# Arguments
- `load_balancer_name`: The name of the load balancer.

"""
describe_load_balancer_attributes(LoadBalancerName; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing("DescribeLoadBalancerAttributes", Dict{String, Any}("LoadBalancerName"=>LoadBalancerName); aws_config=aws_config)
describe_load_balancer_attributes(LoadBalancerName, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing("DescribeLoadBalancerAttributes", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("LoadBalancerName"=>LoadBalancerName), params)); aws_config=aws_config)

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

Describes the specified policies. If you specify a load balancer name, the action returns
the descriptions of all policies created for the load balancer. If you specify a policy
name associated with your load balancer, the action returns the description of that policy.
If you don't specify a load balancer name, the action returns descriptions of the specified
sample policies, or descriptions of all sample policies. The names of the sample policies
have the ELBSample- prefix.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"LoadBalancerName"`: The name of the load balancer.
- `"PolicyNames"`: The names of the policies.
"""
describe_load_balancer_policies(; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing("DescribeLoadBalancerPolicies"; aws_config=aws_config)
describe_load_balancer_policies(params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing("DescribeLoadBalancerPolicies", params; aws_config=aws_config)

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

Describes the specified load balancer policy types or all load balancer policy types. The
description of each type indicates how it can be used. For example, some policies can be
used only with layer 7 listeners, some policies can be used only with layer 4 listeners,
and some policies can be used only with your EC2 instances. You can use
CreateLoadBalancerPolicy to create a policy configuration for any of these policy types.
Then, depending on the policy type, use either SetLoadBalancerPoliciesOfListener or
SetLoadBalancerPoliciesForBackendServer to set the policy.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"PolicyTypeNames"`: The names of the policy types. If no names are specified, describes
  all policy types defined by Elastic Load Balancing.
"""
describe_load_balancer_policy_types(; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing("DescribeLoadBalancerPolicyTypes"; aws_config=aws_config)
describe_load_balancer_policy_types(params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing("DescribeLoadBalancerPolicyTypes", params; aws_config=aws_config)

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

Describes the specified the load balancers. If no load balancers are specified, the call
describes all of your load balancers.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"LoadBalancerNames"`: The names of the load balancers.
- `"Marker"`: The marker for the next set of results. (You received this marker from a
  previous call.)
- `"PageSize"`: The maximum number of results to return with this call (a number from 1 to
  400). The default is 400.
"""
describe_load_balancers(; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing("DescribeLoadBalancers"; aws_config=aws_config)
describe_load_balancers(params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing("DescribeLoadBalancers", params; aws_config=aws_config)

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

Describes the tags associated with the specified load balancers.

# Arguments
- `load_balancer_names`: The names of the load balancers.

"""
describe_tags(LoadBalancerNames; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing("DescribeTags", Dict{String, Any}("LoadBalancerNames"=>LoadBalancerNames); aws_config=aws_config)
describe_tags(LoadBalancerNames, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing("DescribeTags", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("LoadBalancerNames"=>LoadBalancerNames), params)); aws_config=aws_config)

"""
    detach_load_balancer_from_subnets(load_balancer_name, subnets)
    detach_load_balancer_from_subnets(load_balancer_name, subnets, params::Dict{String,<:Any})

Removes the specified subnets from the set of configured subnets for the load balancer.
After a subnet is removed, all EC2 instances registered with the load balancer in the
removed subnet go into the OutOfService state. Then, the load balancer balances the traffic
among the remaining routable subnets.

# Arguments
- `load_balancer_name`: The name of the load balancer.
- `subnets`: The IDs of the subnets.

"""
detach_load_balancer_from_subnets(LoadBalancerName, Subnets; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing("DetachLoadBalancerFromSubnets", Dict{String, Any}("LoadBalancerName"=>LoadBalancerName, "Subnets"=>Subnets); aws_config=aws_config)
detach_load_balancer_from_subnets(LoadBalancerName, Subnets, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing("DetachLoadBalancerFromSubnets", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("LoadBalancerName"=>LoadBalancerName, "Subnets"=>Subnets), params)); aws_config=aws_config)

"""
    disable_availability_zones_for_load_balancer(availability_zones, load_balancer_name)
    disable_availability_zones_for_load_balancer(availability_zones, load_balancer_name, params::Dict{String,<:Any})

Removes the specified Availability Zones from the set of Availability Zones for the
specified load balancer in EC2-Classic or a default VPC. For load balancers in a
non-default VPC, use DetachLoadBalancerFromSubnets. There must be at least one Availability
Zone registered with a load balancer at all times. After an Availability Zone is removed,
all instances registered with the load balancer that are in the removed Availability Zone
go into the OutOfService state. Then, the load balancer attempts to equally balance the
traffic among its remaining Availability Zones. For more information, see Add or Remove
Availability Zones in the Classic Load Balancers Guide.

# Arguments
- `availability_zones`: The Availability Zones.
- `load_balancer_name`: The name of the load balancer.

"""
disable_availability_zones_for_load_balancer(AvailabilityZones, LoadBalancerName; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing("DisableAvailabilityZonesForLoadBalancer", Dict{String, Any}("AvailabilityZones"=>AvailabilityZones, "LoadBalancerName"=>LoadBalancerName); aws_config=aws_config)
disable_availability_zones_for_load_balancer(AvailabilityZones, LoadBalancerName, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing("DisableAvailabilityZonesForLoadBalancer", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("AvailabilityZones"=>AvailabilityZones, "LoadBalancerName"=>LoadBalancerName), params)); aws_config=aws_config)

"""
    enable_availability_zones_for_load_balancer(availability_zones, load_balancer_name)
    enable_availability_zones_for_load_balancer(availability_zones, load_balancer_name, params::Dict{String,<:Any})

Adds the specified Availability Zones to the set of Availability Zones for the specified
load balancer in EC2-Classic or a default VPC. For load balancers in a non-default VPC, use
AttachLoadBalancerToSubnets. The load balancer evenly distributes requests across all its
registered Availability Zones that contain instances. For more information, see Add or
Remove Availability Zones in the Classic Load Balancers Guide.

# Arguments
- `availability_zones`: The Availability Zones. These must be in the same region as the
  load balancer.
- `load_balancer_name`: The name of the load balancer.

"""
enable_availability_zones_for_load_balancer(AvailabilityZones, LoadBalancerName; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing("EnableAvailabilityZonesForLoadBalancer", Dict{String, Any}("AvailabilityZones"=>AvailabilityZones, "LoadBalancerName"=>LoadBalancerName); aws_config=aws_config)
enable_availability_zones_for_load_balancer(AvailabilityZones, LoadBalancerName, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing("EnableAvailabilityZonesForLoadBalancer", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("AvailabilityZones"=>AvailabilityZones, "LoadBalancerName"=>LoadBalancerName), params)); aws_config=aws_config)

"""
    modify_load_balancer_attributes(load_balancer_attributes, load_balancer_name)
    modify_load_balancer_attributes(load_balancer_attributes, load_balancer_name, params::Dict{String,<:Any})

Modifies the attributes of the specified load balancer. You can modify the load balancer
attributes, such as AccessLogs, ConnectionDraining, and CrossZoneLoadBalancing by either
enabling or disabling them. Or, you can modify the load balancer attribute
ConnectionSettings by specifying an idle connection timeout value for your load balancer.
For more information, see the following in the Classic Load Balancers Guide:    Cross-Zone
Load Balancing     Connection Draining     Access Logs     Idle Connection Timeout

# Arguments
- `load_balancer_attributes`: The attributes for the load balancer.
- `load_balancer_name`: The name of the load balancer.

"""
modify_load_balancer_attributes(LoadBalancerAttributes, LoadBalancerName; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing("ModifyLoadBalancerAttributes", Dict{String, Any}("LoadBalancerAttributes"=>LoadBalancerAttributes, "LoadBalancerName"=>LoadBalancerName); aws_config=aws_config)
modify_load_balancer_attributes(LoadBalancerAttributes, LoadBalancerName, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing("ModifyLoadBalancerAttributes", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("LoadBalancerAttributes"=>LoadBalancerAttributes, "LoadBalancerName"=>LoadBalancerName), params)); aws_config=aws_config)

"""
    register_instances_with_load_balancer(instances, load_balancer_name)
    register_instances_with_load_balancer(instances, load_balancer_name, params::Dict{String,<:Any})

Adds the specified instances to the specified load balancer. The instance must be a running
instance in the same network as the load balancer (EC2-Classic or the same VPC). If you
have EC2-Classic instances and a load balancer in a VPC with ClassicLink enabled, you can
link the EC2-Classic instances to that VPC and then register the linked EC2-Classic
instances with the load balancer in the VPC. Note that RegisterInstanceWithLoadBalancer
completes when the request has been registered. Instance registration takes a little time
to complete. To check the state of the registered instances, use DescribeLoadBalancers or
DescribeInstanceHealth. After the instance is registered, it starts receiving traffic and
requests from the load balancer. Any instance that is not in one of the Availability Zones
registered for the load balancer is moved to the OutOfService state. If an Availability
Zone is added to the load balancer later, any instances registered with the load balancer
move to the InService state. To deregister instances from a load balancer, use
DeregisterInstancesFromLoadBalancer. For more information, see Register or De-Register EC2
Instances in the Classic Load Balancers Guide.

# Arguments
- `instances`: The IDs of the instances.
- `load_balancer_name`: The name of the load balancer.

"""
register_instances_with_load_balancer(Instances, LoadBalancerName; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing("RegisterInstancesWithLoadBalancer", Dict{String, Any}("Instances"=>Instances, "LoadBalancerName"=>LoadBalancerName); aws_config=aws_config)
register_instances_with_load_balancer(Instances, LoadBalancerName, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing("RegisterInstancesWithLoadBalancer", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Instances"=>Instances, "LoadBalancerName"=>LoadBalancerName), params)); aws_config=aws_config)

"""
    remove_tags(load_balancer_names, tags)
    remove_tags(load_balancer_names, tags, params::Dict{String,<:Any})

Removes one or more tags from the specified load balancer.

# Arguments
- `load_balancer_names`: The name of the load balancer. You can specify a maximum of one
  load balancer name.
- `tags`: The list of tag keys to remove.

"""
remove_tags(LoadBalancerNames, Tags; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing("RemoveTags", Dict{String, Any}("LoadBalancerNames"=>LoadBalancerNames, "Tags"=>Tags); aws_config=aws_config)
remove_tags(LoadBalancerNames, Tags, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing("RemoveTags", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("LoadBalancerNames"=>LoadBalancerNames, "Tags"=>Tags), params)); aws_config=aws_config)

"""
    set_load_balancer_listener_sslcertificate(load_balancer_name, load_balancer_port, sslcertificate_id)
    set_load_balancer_listener_sslcertificate(load_balancer_name, load_balancer_port, sslcertificate_id, params::Dict{String,<:Any})

Sets the certificate that terminates the specified listener's SSL connections. The
specified certificate replaces any prior certificate that was used on the same load
balancer and port. For more information about updating your SSL certificate, see Replace
the SSL Certificate for Your Load Balancer in the Classic Load Balancers Guide.

# Arguments
- `load_balancer_name`: The name of the load balancer.
- `load_balancer_port`: The port that uses the specified SSL certificate.
- `sslcertificate_id`: The Amazon Resource Name (ARN) of the SSL certificate.

"""
set_load_balancer_listener_sslcertificate(LoadBalancerName, LoadBalancerPort, SSLCertificateId; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing("SetLoadBalancerListenerSSLCertificate", Dict{String, Any}("LoadBalancerName"=>LoadBalancerName, "LoadBalancerPort"=>LoadBalancerPort, "SSLCertificateId"=>SSLCertificateId); aws_config=aws_config)
set_load_balancer_listener_sslcertificate(LoadBalancerName, LoadBalancerPort, SSLCertificateId, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing("SetLoadBalancerListenerSSLCertificate", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("LoadBalancerName"=>LoadBalancerName, "LoadBalancerPort"=>LoadBalancerPort, "SSLCertificateId"=>SSLCertificateId), params)); aws_config=aws_config)

"""
    set_load_balancer_policies_for_backend_server(instance_port, load_balancer_name, policy_names)
    set_load_balancer_policies_for_backend_server(instance_port, load_balancer_name, policy_names, params::Dict{String,<:Any})

Replaces the set of policies associated with the specified port on which the EC2 instance
is listening with a new set of policies. At this time, only the back-end server
authentication policy type can be applied to the instance ports; this policy type is
composed of multiple public key policies. Each time you use
SetLoadBalancerPoliciesForBackendServer to enable the policies, use the PolicyNames
parameter to list the policies that you want to enable. You can use DescribeLoadBalancers
or DescribeLoadBalancerPolicies to verify that the policy is associated with the EC2
instance. For more information about enabling back-end instance authentication, see
Configure Back-end Instance Authentication in the Classic Load Balancers Guide. For more
information about Proxy Protocol, see Configure Proxy Protocol Support in the Classic Load
Balancers Guide.

# Arguments
- `instance_port`: The port number associated with the EC2 instance.
- `load_balancer_name`: The name of the load balancer.
- `policy_names`: The names of the policies. If the list is empty, then all current polices
  are removed from the EC2 instance.

"""
set_load_balancer_policies_for_backend_server(InstancePort, LoadBalancerName, PolicyNames; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing("SetLoadBalancerPoliciesForBackendServer", Dict{String, Any}("InstancePort"=>InstancePort, "LoadBalancerName"=>LoadBalancerName, "PolicyNames"=>PolicyNames); aws_config=aws_config)
set_load_balancer_policies_for_backend_server(InstancePort, LoadBalancerName, PolicyNames, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing("SetLoadBalancerPoliciesForBackendServer", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("InstancePort"=>InstancePort, "LoadBalancerName"=>LoadBalancerName, "PolicyNames"=>PolicyNames), params)); aws_config=aws_config)

"""
    set_load_balancer_policies_of_listener(load_balancer_name, load_balancer_port, policy_names)
    set_load_balancer_policies_of_listener(load_balancer_name, load_balancer_port, policy_names, params::Dict{String,<:Any})

Replaces the current set of policies for the specified load balancer port with the
specified set of policies. To enable back-end server authentication, use
SetLoadBalancerPoliciesForBackendServer. For more information about setting policies, see
Update the SSL Negotiation Configuration, Duration-Based Session Stickiness, and
Application-Controlled Session Stickiness in the Classic Load Balancers Guide.

# Arguments
- `load_balancer_name`: The name of the load balancer.
- `load_balancer_port`: The external port of the load balancer.
- `policy_names`: The names of the policies. This list must include all policies to be
  enabled. If you omit a policy that is currently enabled, it is disabled. If the list is
  empty, all current policies are disabled.

"""
set_load_balancer_policies_of_listener(LoadBalancerName, LoadBalancerPort, PolicyNames; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing("SetLoadBalancerPoliciesOfListener", Dict{String, Any}("LoadBalancerName"=>LoadBalancerName, "LoadBalancerPort"=>LoadBalancerPort, "PolicyNames"=>PolicyNames); aws_config=aws_config)
set_load_balancer_policies_of_listener(LoadBalancerName, LoadBalancerPort, PolicyNames, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing("SetLoadBalancerPoliciesOfListener", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("LoadBalancerName"=>LoadBalancerName, "LoadBalancerPort"=>LoadBalancerPort, "PolicyNames"=>PolicyNames), params)); aws_config=aws_config)


text:
using DataCollection
using Test

using DataFrames
import DataStructures: SortedDict

#####
##### Test behavior of `lower`.
#####

@testset "Testing Helper Functions" begin
    @test DataCollection.lower(1) === 1

    # Functions
    @test DataCollection.lower(identity) == "identity"
    @test DataCollection.lower(cos) == "cos"
    @test DataCollection.lower([1,2,3]) == [1,2,3]
    @test DataCollection.lower([1, identity, cos, 4]) == [1, "identity", "cos", 4]
end

struct ParametersA <: AbstractParameters
    a::Int
    b::Int
end

struct ParametersB <: AbstractParameters
    c::Int
    d::Int
end

struct ParametersC <: AbstractParameters
    e::Int
    f::Int
end

struct ParametersError <: AbstractParameters
    e::Int
    # Repeat `a` so we can test errors during merging
    a::Int
end

struct DataA <: AbstractData
    data::Int
end

@testset "Testing Parameters" begin
    x = ParametersA(1,2)
    @test DataCollection.lower(x) == SortedDict(:a => 1, :b => 2)
    @test DataCollection.dict(x) == SortedDict(:a => 1, :b => 2)

    y = ParametersB(3,4)
    expected = SortedDict(
        :a => 1,
        :b => 2,
        :c => 3,
        :d => 4,
    )
    @test DataCollection._lower(x,y) == expected

    z = ParametersError(5,6)
    @test_throws ErrorException DataCollection._lower(x,y,z)

    # DataFrames schenanigans
    df = DataFrame()

    x = ParametersA(1, 2)
    y = ParametersB(3, 4)
    _y = ParametersB(4, 4)
    d = DataA(10)

    # Create a row for these parameters and data
    addrow!(df, d, x, y)
    @test nrow(df) == 1
    @test DataCollection.hasrow(df, x, y)

    # Ensure that we don't get false positives
    @test !DataCollection.hasrow(df, x, _y)

    # Get this row and make sure the data propogated properly.
    row = df[1, :]
    @test row.data == d.data

    # Try updating.
    @test_throws ErrorException addrow!(df, d, x, y)
    d2 = DataA(20)
    addrow!(df, d2, x, y; force = true)
    row = df[1, :]
    @test row.data == 20

    # Now, add another row
    x2 = ParametersA(10, 20)
    y2 = ParametersB(30, 40)
    addrow!(df, d2, x2, y2)
    @test nrow(df) == 2
    @test DataCollection.hasrow(df, x2, y2)
    @test DataCollection.hasrow(df, x, y)

    # Add something with different parameters.
    # Make sure we get an error if we don't pass `cols = :union`
    z = ParametersC(1,2)
    @test_throws ArgumentError addrow!(df, d, z)
    addrow!(df, d, z; cols = :union)

    @test nrow(df) == 3

    # We should still have the rows we added earlier
    @test DataCollection.hasrow(df, x2, y2)
    @test DataCollection.hasrow(df, x, y)
    @test DataCollection.hasrow(df, z)
end

ext: jl


text:
export symmetric_analytical_jacobian_strength!,
       symmetric_analytical_jacobian_strength,
       symmetric_analytical_jacobian_position!,
       symmetric_analytical_jacobian_position,
       symmetric_analytical_jacobian_pressure

# Version for point singularities
"""
Returns the Jacobian of the pressure computed from the unsteady Bernoulli equation with respect to the position and conjugate position of the singularities.
Note that we multiply the strength `point.S` of a singularity by -i to move from the convention Γ+iQ (used in PotentialFlow.jl) to Q-iΓ.
"""
function symmetric_analytical_jacobian_position!(dpdz, dpdzstar, Css, Cts, wtarget, target::Vector{Float64}, source::T,
	                                   idx::Union{Int64, Vector{Int64}, UnitRange{Int64}}, t;
                                       iscauchystored::Bool = false) where T <: Vector{PotentialFlow.Points.Point{Float64, Float64}}
	Nx = size(source, 1)
	@assert mod(Nx, 2) == 0
	halfNx = Nx÷2
	Ny = size(target, 1)

	cst = inv(2*π)

	# @assert size(dpdz) == (Ny, Nx) && size(dpdzstar) == (Ny, Nx) && size(Css) == (Nx, Nx) && size(Cts) == (Ny, Nx) && size(wtarget) == (Ny,)

	fill!(dpdz, complex(0.0)); fill!(dpdzstar, complex(0.0))

	if iscauchystored == false
	   fill!(Css, complex(0.0)); fill!(Cts, complex(0.0))

	   # the induced velocity is real along the real ais for a symmetric vorticity distribution
	   fill!(wtarget, 0.0)

	   # Construct the Cauchy matrix to store 1/(zJ-zK) in Css
	   for K=1:halfNx
	       zK = source[K].z
	       # exploit anti-symmetry of the velocity kernel
	       for J=K:halfNx
	           zJ = source[J].z
	           if K == J
	               tmpAJK = 0.0*im
				   tmpBJK = -0.5*im/imag(zJ)
				   tmpCJK = -tmpBJK
	               tmpDJK = 0.0*im
	           else
	               tmpAJK = inv(zJ - zK)
				   tmpBJK = inv(zJ - conj(zK))
				   tmpCJK = conj(tmpBJK)
				   tmpDJK = conj(tmpAJK)
	           end

	           # 	    | K | K̄ |
	           # | J |    A   B
	           # | J̄ |    C   D
	           # Fill top diagonal block
	           Css[J,K] =  tmpAJK
	           Css[K,J] = -tmpAJK

	           # Top right off-diagonal block
	           Css[J,halfNx+K] =  tmpBJK
	           Css[K,halfNx+J] = -tmpCJK

	           # Lower right off-diagonal block
	           Css[halfNx+J,K] =  tmpCJK
	           Css[halfNx+K,J] = -tmpBJK

	           # Lower diagonal block
	           Css[halfNx+J,halfNx+K] =  tmpDJK
	           Css[halfNx+K,halfNx+J] = -tmpDJK
	       end
	   end

		# Construct the Cauchy matrix to store 1/(z-zJ) and the total induced velocity in Cts and wtarget
			@inbounds for J=1:halfNx
				zJ = source[J].z
				SJ = -im*source[J].S
				for i=1:Ny
					xi = target[i]
					tmpiJ = inv(xi - zJ)
					Cts[i,J] = tmpiJ
					Cts[i,halfNx+J] = conj(tmpiJ) #as xi is real
					wtarget[i] +=  real(Cts[i,J]*SJ)# + Cts[i,halfNx+J]*conj(SJ))
			end
		end
		wtarget .*= 2*cst
	end

	# Evaluate ∂(-0.5v^2)/∂zL, ∂(-0.5v^2)/∂z̄L
	@inbounds for L in idx #1:Nx
	   zL = source[L].z
	   SL = -im*source[L].S
	   for i=1:Ny
	       wt = wtarget[i]
		   # wt is real for a symmetric vortex configuration evaluated on the real axis.
	       dpdz[i,L] = -0.5*wt*SL*cst*Cts[i,L]^2
	       # dpdzstar[i,L] = conj(dpdz[i,L])
	   end
	end

	# Evaluate ∂(-∂ϕ/∂t)/∂zL, ∂(-∂ϕ/∂t)/∂z̄L
	@inbounds for L in idx #1:Nx
		SL = -im*source[L].S
		for K=1:Nx
			SK = -im*source[K].S
			for i=1:Ny
				term1 = 0.5*cst^2*SL*conj(SK)*(Cts[i,L])^2*conj(Css[L,K])
				term1 += 0.5*cst^2*conj(SL)*SK*conj(Cts[i,L])*(-Css[L,K]^2)
				dpdz[i,L] += term1
				# dpdzstar[i,L] += conj(term1)
			end
		end
		for J=1:Nx
			SJ = -im*source[J].S
			for i=1:Ny
			   term2 = 0.5*cst^2*conj(SJ)*SL*conj(Cts[i,J])*(Css[J,L])^2
			   dpdz[i,L] += term2
			   # dpdzstar[i,L] += conj(term2)
			end
		end
	end
	dpdzstar .= conj(dpdz)
	nothing
end

###############################################################################################
##################################### BLOBS ###################################################
###############################################################################################

# Version for regularized point singularities (aka blobs)
"""
Returns the Jacobian of the pressure computed from the unsteady Bernoulli equation with respect to the position and conjugate position of the singularities.
Note that we multiply the strength `point.S` of a singularity by -i to move from the convention Γ+iQ (used in PotentialFlow.jl) to Q-iΓ.
"""
function symmetric_analytical_jacobian_position!(dpdz, dpdzstar, Css, ∂Css, Cts, Ctsblob, ∂Ctsblob, wtarget, target::Vector{Float64}, source::T,
									             idx::Union{Int64, Vector{Int64}, UnitRange{Int64}}, t;
                                                 iscauchystored::Bool = false) where T <: Vector{PotentialFlow.Blobs.Blob{Float64, Float64}}
	Ny = size(target, 1)
	Nx = size(source, 1)

	halfNx = Nx÷2

	δ = source[1].δ

	cst = inv(2*π)

	# @assert size(dpdz) == (Ny, Nx) && size(dpdzstar) == (Ny, Nx) && size(Css) == (Nx, Nx) && size(Cts) == (Ny, Nx) && size(wtarget) == (Ny,)

	fill!(dpdz, complex(0.0)); fill!(dpdzstar, complex(0.0))

	if iscauchystored == false
	   fill!(Css, complex(0.0));
	   fill!(∂Css, 0.0);
	   fill!(Cts, complex(0.0));
	   fill!(Ctsblob, complex(0.0));
	   fill!(∂Ctsblob, 0.0)

	   fill!(wtarget, 0.0)

	   # Construct the Cauchy matrix to store 1/(zJ-zK) in Css
	   for K=1:halfNx
		   zK = source[K].z
		   # exploit anti-symmetry of the velocity kernel
		   for J=K:halfNx
			   zJ = source[J].z

			   ΔdiagJK = conj(zJ - zK)
			   ΔoffJK =  conj(zJ) - zK

			   tmpdiagJK  = abs2(ΔdiagJK) + δ^2
			   tmpoffJK  = abs2(ΔoffJK) + δ^2
			   tmpAJK = ΔdiagJK/tmpdiagJK
			   tmpBJK = ΔoffJK/tmpoffJK
			   tmpCJK = conj(tmpBJK)
			   tmpDJK = conj(tmpAJK)

			   if J == K
				   tmp∂AJK = 0.0
				   tmp∂DJK = 0.0
			   else
				   tmp∂AJK = -(δ/tmpdiagJK)^2
				   tmp∂DJK = tmp∂AJK
		   	   end

			   tmp∂BJK = -(δ/tmpoffJK)^2
			   tmp∂CJK = tmp∂BJK

			   # 	    | K | K̄ |
			   # | J |    A   B
			   # | J̄ |    C   D
			   # Fill top diagonal block
			   Css[J,K] =  tmpAJK
			   Css[K,J] = -tmpAJK

			   ∂Css[J,K] =  tmp∂AJK
			   ∂Css[K,J] =  tmp∂AJK

			   # Top right off-diagonal block
			   Css[J,halfNx+K] =  tmpBJK
			   Css[K,halfNx+J] = -tmpCJK

			   ∂Css[J,halfNx+K] =  tmp∂BJK
			   ∂Css[K,halfNx+J] =  tmp∂BJK

			   # Lower right off-diagonal block
			   Css[halfNx+J,K] =  tmpCJK
			   Css[halfNx+K,J] = -tmpBJK

			   ∂Css[halfNx+J,K] =  tmp∂CJK
			   ∂Css[halfNx+K,J] =  tmp∂CJK

			   # Lower diagonal block
			   Css[halfNx+J,halfNx+K] =  tmpDJK
			   Css[halfNx+K,halfNx+J] = -tmpDJK

			   ∂Css[halfNx+J,halfNx+K] =  tmp∂DJK
			   ∂Css[halfNx+K,halfNx+J] =  tmp∂DJK
		   end
	   end

	   # Construct the Cauchy matrix to store (z̄-z̄J)/(|z-zJ|^2 + δ^2) and the total induced velocity in Cts and wtarget
	   @inbounds for J=1:halfNx
	       zJ = source[J].z
	       ΓJ = source[J].S
	       for i=1:Ny
	           xi = target[i]
			   ΔiJ = xi - zJ
			   tmpregiJ = abs2(ΔiJ) + δ^2
			   tmp1iJ = inv(ΔiJ)
			   tmp2iJ = conj(ΔiJ)/tmpregiJ

			   Cts[i,J] = tmp1iJ
			   Cts[i,halfNx+J] = conj(Cts[i,J])

	           Ctsblob[i,J] = tmp2iJ
			   Ctsblob[i,halfNx+J] = conj(Ctsblob[i,J])

			   ∂Ctsblob[i,J] = -(δ/tmpregiJ)^2
			   ∂Ctsblob[i,halfNx+J] = ∂Ctsblob[i,J]

	           wtarget[i] += ΓJ*imag(Ctsblob[i,J])
	       end
	   end
	   wtarget .*= (1/π)
	end

	# Evaluate ∂(-∂ϕ/∂t)/∂zL, ∂(-∂ϕ/∂t)/∂z̄L
	@inbounds for L in idx #1:Nx
		SL = -im*source[L].S
		term1 = 0.0*im
		term2 = 0.0*im
		term3 = 0.0*im
		term4 = 0.0*im
		tmp = 0.0*im
		tmp2 = 0.0*im

		# Terms in δJL
		for K=1:Nx
			SK = -im*source[K].S
			tmp = SK*Css[L,K]
			tmp2 = conj(SK*∂Css[L,K])
			term1 += tmp
			term2 -= tmp2
			term3 -= tmp*Css[L,K]
			# if K !=L
			# 	for i=1:Ny
			# 		# We have ∂Css[K,L] = ∂Css[L,K]
			# 		dpdz[i,L] += SK*conj(SL)*Cts[i,K]*∂Css[K,L]
			# 	end
			# end
		end

		for i=1:Ny
			tmp = SL*Cts[i,L]
			dpdz[i,L] += tmp*(Cts[i,L]*conj(term1)+term2)
			dpdz[i,L] += conj(tmp)*term3
		end

		# Terms in δKL

		for J=1:Nx
			SJ = -im*source[J].S
			for i=1:Ny
	           termKL = SJ*conj(SL)*Cts[i,J]*∂Css[J,L]
			   termKL += conj(SJ)*SL*conj(Cts[i,J])*Css[J,L]^2
	           dpdz[i,L] += termKL

	           # dpdzstar[i,L] += conj(termKL)
		   end
	   end
	end

	Γ = getfield.(source, :S)
	# dpdz[:,idx] .+= conj(Cts) .* (im*Γ') .*  (Css .^2 .* -im*Γ')

	dpdz[:,idx] .*=  0.5*cst^2

	# Evaluate ∂(-0.5v^2)/∂zL, ∂(-0.5v^2)/∂z̄L
	@inbounds for L in idx #1:Nx
	   zL = source[L].z
	   SL = -im*source[L].S
	   for i=1:Ny
		   wt = wtarget[i]
		   # dpdz[i,L] = -0.5*cst*conj(SL)*∂Ctsblob[i,L]*wt
		   # dpdz[i,L] += -0.5*conj(wt)*cst*SL*Ctsblob[i,L]^2
		   # Exploit the fact that w(xi) is real
		   dpdz[i,L] -= 0.5*wt*cst*SL*(Ctsblob[i,L]^2-∂Ctsblob[i,L])
		   # dpdzstar[i,L] = conj(dpdz[i,L])
	   end
	end

	dpdzstar .= conj(dpdz)
	nothing
end

function symmetric_analytical_jacobian_position!(dpdz, dpdzstar, Css, Cts, wtarget, target::Vector{Float64}, source::T, t;
                                                 iscauchystored::Bool = false) where T <:Vector{PotentialFlow.Points.Point{Float64, Float64}}

	symmetric_analytical_jacobian_position!(dpdz, dpdzstar, Css, Cts, wtarget, target, source,
	                                        1:length(source), t; iscauchystored = iscauchystored)
end

function symmetric_analytical_jacobian_position!(dpdz, dpdzstar, Css, ∂Css, Cts, Ctsblob, ∂Ctsblob,
	                                             wtarget, target::Vector{Float64}, source::T, t;
                                                 iscauchystored::Bool = false) where T <:Vector{PotentialFlow.Blobs.Blob{Float64, Float64}}

	symmetric_analytical_jacobian_position!(dpdz, dpdzstar, Css, ∂Css, Cts, Ctsblob, ∂Ctsblob,
		                                    wtarget, target, source,
	                                        1:length(source), t; iscauchystored = iscauchystored)
end

function symmetric_analytical_jacobian_position(target::Vector{Float64}, source,
									            idx::Union{Int64, Vector{Int64}, UnitRange{Int64}}, t)
   Ny = size(target, 1)
   Nx = size(source, 1)
   # Create allocations for the Cauchy matrices
   Css = zeros(ComplexF64, Nx, Nx)
   Cts = zeros(ComplexF64, Ny, Nx)
   wtarget = zeros(Ny)

   dpdz = zeros(ComplexF64, Ny, Nx)
   dpdzstar = zeros(ComplexF64, Ny, Nx)

	if typeof(source)<:Vector{PotentialFlow.Points.Point{Float64, Float64}}
	    symmetric_analytical_jacobian_position!(dpdz, dpdzstar, Css, Cts, wtarget, target, source, idx, t;
	                                  iscauchystored = false)
	elseif typeof(source)<:Vector{PotentialFlow.Blobs.Blob{Float64, Float64}}
		∂Css = zeros(Nx, Nx)
		Ctsblob = zeros(ComplexF64, Ny, Nx)
		∂Ctsblob = zeros(Ny, Nx)
		symmetric_analytical_jacobian_position!(dpdz, dpdzstar, Css, ∂Css, Cts, Ctsblob, ∂Ctsblob, wtarget, target, source, idx, t;
									  iscauchystored = false)
	end

   return dpdz, dpdzstar
end

symmetric_analytical_jacobian_position(target::Vector{Float64}, source, t) = symmetric_analytical_jacobian_position(target, source, 1:length(source), t)

"""
Returns the Jacobian of the pressure computed from the unsteady Bernoulli equation with respect to the strength and conjugate strength of the singularities.
Note that we multiply the strength `point.S` of a singularity by -i to move from the convention Γ+iQ (used in PotentialFlow.jl) to S = Q-iΓ.
"""
function symmetric_analytical_jacobian_strength!(dpdS, dpdSstar, Css, Cts, wtarget, target::Vector{Float64}, source::T,
	                                   idx::Union{Int64, Vector{Int64}, UnitRange{Int64}}, t;
                                       iscauchystored::Bool = false) where T <: Vector{PotentialFlow.Points.Point{Float64, Float64}}
	Ny = size(target, 1)
    Nx = size(source, 1)

	halfNx = Nx÷2

    cst = inv(2*π)

    # @assert size(dpdS) == (Ny, Nx) && size(dpdSstar) == (Ny, Nx) && size(Css) == (Nx, Nx) && size(Cts) == (Ny, Nx) && size(wtarget) == (Ny,)

    fill!(dpdS, complex(0.0)); fill!(dpdSstar, complex(0.0))

    if iscauchystored == false

        fill!(Css, complex(0.0)); fill!(Cts, complex(0.0))

        # Account for the presence of the free-stream
        fill!(wtarget, 0.0)

        # Construct the Cauchy matrix to store 1/(zJ-zK) in Css
		for K=1:halfNx
 	       zK = source[K].z
 	       # exploit anti-symmetry of the velocity kernel
 	       for J=K:halfNx
 	           zJ = source[J].z
 	           if K == J
 	               tmpAJK = 0.0*im
 				   tmpBJK = -0.5*im/imag(zJ)
 				   tmpCJK = -tmpBJK
 	               tmpDJK = 0.0*im
 	           else
 	               tmpAJK = inv(zJ - zK)
 				   tmpBJK = inv(zJ - conj(zK))
 				   tmpCJK = conj(tmpBJK)
 				   tmpDJK = conj(tmpAJK)
 	           end

 	           # 	    | K | K̄ |
 	           # | J |    A   B
 	           # | J̄ |    C   D
 	           # Fill top diagonal block
 	           Css[J,K] =  tmpAJK
 	           Css[K,J] = -tmpAJK

 	           # Top right off-diagonal block
 	           Css[J,halfNx+K] =  tmpBJK
 	           Css[K,halfNx+J] = -tmpCJK

 	           # Lower right off-diagonal block
 	           Css[halfNx+J,K] =  tmpCJK
 	           Css[halfNx+K,J] = -tmpBJK

 	           # Lower diagonal block
 	           Css[halfNx+J,halfNx+K] =  tmpDJK
 	           Css[halfNx+K,halfNx+J] = -tmpDJK
 	       end
 	   end

 		# Construct the Cauchy matrix to store 1/(z-zJ) and the total induced velocity in Cts and wtarget
 			@inbounds for J=1:halfNx
 				zJ = source[J].z
 				SJ = -im*source[J].S
 				for i=1:Ny
 					xi = target[i]
 					tmpiJ = inv(xi - zJ)
 					Cts[i,J] = tmpiJ
 					Cts[i,halfNx+J] = conj(tmpiJ) #as xi is real
 					wtarget[i] +=  real(Cts[i,J]*SJ)# + Cts[i,halfNx+J]*conj(SJ))
 			end
 		end
 		wtarget .*= 2*cst
    end

    # Evaluate ∂(-0.5v^2)/∂SL, ∂(-0.5v^2)/∂S̄L
    for L in idx #1:Nx
        zL = source[L].z
        SL = -im*source[L].S
        for i=1:Ny
            wt = wtarget[i]
            dpdS[i,L] = -0.5*conj(wt)*cst*Cts[i,L]
            # dpdSstar[i,L] = conj(dpdS[i,L])
        end
    end

    # Evaluate ∂(-∂ϕ/∂t)/∂SL, ∂(-∂ϕ/∂t)/∂S̄L
    @inbounds for L in idx #1:Nx
		SL = -im*source[L].S
		for K=1:Nx
			if K != L
				SK = -im*source[K].S
				for i=1:Ny
					term1 = 0.5*cst^2*conj(SK)*Cts[i,L]*conj(Css[L,K])
					dpdS[i,L] += term1
					# dpdSstar[i,L] += conj(term1)
				end
			end
		end

	    for J=1:Nx
			if J != L
		        SJ = -im*source[J].S
	       		for i=1:Ny
	                term2 = 0.5*cst^2*conj(SJ)*conj(Cts[i,J])*Css[J,L]
	                dpdS[i,L] += term2
	                # dpdSstar[i,L] += conj(term2)
	            end
			end
        end
    end
	dpdSstar .= conj(dpdS)
    nothing
end

###############################################################################################
##################################### BLOBS ###################################################
###############################################################################################

function symmetric_analytical_jacobian_strength!(dpdS, dpdSstar, Css, Cts, Ctsblob, wtarget, target::Vector{Float64}, source::T,
	                                   idx::Union{Int64, Vector{Int64}, UnitRange{Int64}}, t;
	                       iscauchystored::Bool = false, issourcefixed::Bool = false) where T <: Vector{PotentialFlow.Blobs.Blob{Float64, Float64}}
	Ny = size(target, 1)
	Nx = size(source, 1)
	@assert mod(Nx, 2) == 0
	halfNx = Nx÷2

	δ = source[1].δ

	cst = inv(2*π)

	# @assert size(dpdS) == (Ny, Nx) && size(dpdSstar) == (Ny, Nx) && size(Css) == (Nx, Nx) && size(Cts) == (Ny, Nx) && size(wtarget) == (Ny,)

	fill!(dpdS, complex(0.0)); fill!(dpdSstar, complex(0.0))

	if iscauchystored == false
		fill!(Css, complex(0.0));
		fill!(Cts, complex(0.0));
		fill!(Ctsblob, complex(0.0));

		fill!(wtarget, 0.0)

		# Construct the Cauchy matrix to store 1/(zJ-zK) in Css
		@inbounds for K=1:halfNx
			# exploit anti-symmetry of the velocity kernel
			for J=K:halfNx
				zK = source[K].z
				zJ = source[J].z

				ΔdiagJK = conj(zJ - zK)
				ΔoffJK =  conj(zJ) - zK

				tmpdiagJK  = abs2(ΔdiagJK) + δ^2
				tmpoffJK  = abs2(ΔoffJK) + δ^2
				tmpAJK = ΔdiagJK/tmpdiagJK
				tmpBJK = ΔoffJK/tmpoffJK
				tmpCJK = conj(tmpBJK)
				tmpDJK = conj(tmpAJK)

				# 	    | K | K̄ |
				# | J |    A   B
				# | J̄ |    C   D
				# Fill top diagonal block
				Css[J,K] =  tmpAJK
				Css[K,J] = -tmpAJK

				# Top right off-diagonal block
				Css[J,halfNx+K] =  tmpBJK
				Css[K,halfNx+J] = -tmpCJK

				# Lower right off-diagonal block
				Css[halfNx+J,K] =  tmpCJK
				Css[halfNx+K,J] = -tmpBJK

				# Lower diagonal block
				Css[halfNx+J,halfNx+K] =  tmpDJK
				Css[halfNx+K,halfNx+J] = -tmpDJK
			end

			# zv .= getfield.(source, :z)
			# Γv .= getfield.(source, :S)
		end

		# Construct the Cauchy matrix to store (z̄-z̄J)/(|z-zJ|^2 + δ^2) and the total induced velocity in Cts and wtarget
		@inbounds for J=1:halfNx
			zJ = source[J].z
			yJ = imag(zJ)
			ΓJ = source[J].S
			for i=1:Ny
				xi = target[i]
				ΔiJ = xi - zJ
				tmpregiJ = abs2(ΔiJ) + δ^2
				tmp1iJ = inv(ΔiJ)
				tmp2iJ = conj(ΔiJ)/tmpregiJ

				Cts[i,J] = tmp1iJ
				Cts[i,halfNx+J] = conj(Cts[i,J])

				Ctsblob[i,J] = tmp2iJ
				Ctsblob[i,halfNx+J] = conj(Ctsblob[i,J])

				wtarget[i] += ΓJ*imag(Ctsblob[i,J])
			end
		end
		wtarget .*= (1/π)
	end

	# Evaluate ∂(-∂ϕ/∂t)/∂SL, ∂(-∂ϕ/∂t)/∂S̄L
	@inbounds for L in idx
		term1 = 0.0*im
		for K=1:Nx
			# if K != L
				# Css[K.L] = 0
				SK = -im*source[K].S
				term1 += conj(SK * Css[L,K])
			# end
		end
		for i=1:Ny
			dpdS[i,L] += Cts[i,L]*term1
		end
	end

	# @inbounds dpdS[:,idx] .+= Cts[:,idx] .* conj(Css[idx,:] * (-im*Γ))'

	Γ = getfield.(source, :S)

	@inbounds dpdS[:,idx] .+= conj(Cts[:,idx])*(im*Γ .* Css[:,idx])

	dpdS .*= 0.5*cst^2

	# Evaluate ∂(-0.5v^2)/∂SL, ∂(-0.5v^2)/∂S̄L
	@inbounds dpdS[:,idx] .+= -0.5*cst*(wtarget .* Ctsblob[:,idx])
	# @inbounds for i=1:Ny
	# 	dpdS[i,:] .= -0.5*cst*wtarget[i]
	# 	for L in idx
	# 		dpdS[i,L] *= Ctsblob[i,L]
	# 		# dpdSstar[i,L] = conj(dpdS[i,L])
	# 	end
	# end

	dpdSstar .= conj(dpdS)
	nothing
end

symmetric_analytical_jacobian_strength!(dpdS, dpdSstar, Css, Cts, Ctsblob, wtarget, target::Vector{Float64}, source, t;
	                          iscauchystored::Bool = false) =
symmetric_analytical_jacobian_strength!(dpdS, dpdSstar, Css, Cts, Ctsblob, wtarget, target, source, 1:length(source), t;
							  iscauchystored = iscauchystored)

symmetric_analytical_jacobian_strength(target::Vector{Float64}, source, t) = symmetric_analytical_jacobian_strength(target, source, 1:length(source), t)

function symmetric_analytical_jacobian_strength(target::Vector{Float64}, source,
	                                  idx::Union{Int64, Vector{Int64}, UnitRange{Int64}}, t)
	Ny = size(target, 1)
	Nx = size(source, 1)
	Css = zeros(ComplexF64, Nx, Nx)
	Cts = zeros(ComplexF64, Ny, Nx)
	wtarget = zeros(Ny)

	dpdS = zeros(ComplexF64, Ny, Nx)
	dpdSstar = zeros(ComplexF64, Ny, Nx)
	if typeof(source)<:Vector{PotentialFlow.Points.Point{Float64, Float64}}
		symmetric_analytical_jacobian_strength!(dpdS, dpdSstar, Css, Cts, wtarget, target, source, idx, t;
	                                            iscauchystored = false)
	elseif typeof(source)<:Vector{PotentialFlow.Blobs.Blob{Float64, Float64}}
		Ctsblob = zeros(ComplexF64, Ny, Nx)
		symmetric_analytical_jacobian_strength!(dpdS, dpdSstar, Css, Cts, Ctsblob, wtarget, target, source, idx, t;
									            iscauchystored = false)
	end

	return dpdS, dpdSstar
end

symmetric_analytical_jacobian_pressure(target, source, t) = symmetric_analytical_jacobian_pressure(target, source, 1:length(source), t)

# Version with allocations for point vortices
function symmetric_analytical_jacobian_pressure(target, source::T, idx::Union{Int64, Vector{Int64}, UnitRange{Int64}}, t) where T <: Vector{PotentialFlow.Points.Point{Float64, Float64}}
	Nv = size(source, 1)
	Nx = 3*Nv
	Ny = size(target, 1)

	J = zeros(Ny, Nx)

	wtarget = zeros(Ny)

	dpd = zeros(ComplexF64, Ny, Nv)
	dpdstar = zeros(ComplexF64, Ny, Nv)

	Css = zeros(ComplexF64, Nv, Nv)
	Cts = zeros(ComplexF64, Ny, Nv)

	symmetric_analytical_jacobian_pressure!(J, wtarget, dpd, dpdstar, Css, Cts, target, source, idx, t)
	return J
end

# Version with allocations for regularized vortices
function symmetric_analytical_jacobian_pressure(target, source::T, idx::Union{Int64, Vector{Int64}, UnitRange{Int64}}, t) where T <: Vector{PotentialFlow.Blobs.Blob{Float64, Float64}}
	Nv = size(source, 1)
	Nx = 3*Nv
	Ny = size(target, 1)

	J = zeros(Ny, Nx)

	wtarget = zeros(Ny)

	dpdz = zeros(ComplexF64, Ny, Nv)
	dpdS = zeros(ComplexF64, Ny, Nv)

	Css = zeros(ComplexF64, Nv, Nv)
	Cts = zeros(ComplexF64, Ny, Nv)

	∂Css = zeros(Nv, Nv)
	Ctsblob = zeros(ComplexF64, Ny, Nv)
	∂Ctsblob = zeros(Ny, Nv)

	symmetric_analytical_jacobian_pressure!(J, wtarget, dpdz, dpdS, Css, Cts, ∂Css, Ctsblob, ∂Ctsblob, target, source, idx, t)
	return J
end

###############################################################################################
##################################### BLOBS ###################################################
###############################################################################################

# In-place version for regularized vortices
function symmetric_analytical_jacobian_pressure!(J, wtarget, dpdz, dpdS, Css, Cts, ∂Css, Ctsblob, ∂Ctsblob, target, source::T, idx::Union{Int64, Vector{Int64}, UnitRange{Int64}}, t) where T <: Vector{PotentialFlow.Blobs.Blob{Float64, Float64}}
	Ny = size(target, 1)
	Nx = size(source, 1)
	@assert mod(Nx, 2) == 0
	halfNx = Nx÷2

	δ = source[1].δ

	cst = inv(2*π)

	# @assert size(dpdS) == (Ny, Nx) && size(dpdSstar) == (Ny, Nx) && size(Css) == (Nx, Nx) && size(Cts) == (Ny, Nx) && size(wtarget) == (Ny,)

	fill!(dpdz, complex(0.0)); fill!(dpdS, complex(0.0))

	fill!(Css, complex(0.0));
	fill!(Cts, complex(0.0));
	fill!(∂Css, complex(0.0));
	fill!(Cts, complex(0.0));
	fill!(Ctsblob, complex(0.0));
	fill!(∂Ctsblob, complex(0.0));
	fill!(wtarget, 0.0)

	# Construct the Cauchy matrix to store 1/(zJ-zK) in Css
	@inbounds for K=1:halfNx
		zK = source[K].z
		# exploit anti-symmetry of the velocity kernel
		for J=K:halfNx
			zJ = source[J].z

			ΔdiagJK = conj(zJ - zK)
			ΔoffJK =  conj(zJ) - zK

			tmpdiagJK  = abs2(ΔdiagJK) + δ^2
			tmpoffJK  = abs2(ΔoffJK) + δ^2
			tmpAJK = ΔdiagJK/tmpdiagJK
			tmpBJK = ΔoffJK/tmpoffJK
			tmpCJK = conj(tmpBJK)
			tmpDJK = conj(tmpAJK)

			if J == K
				tmp∂AJK = 0.0
				tmp∂DJK = 0.0
			else
				tmp∂AJK = -(δ/tmpdiagJK)^2
				tmp∂DJK = tmp∂AJK
			end

			tmp∂BJK = -(δ/tmpoffJK)^2
			tmp∂CJK = tmp∂BJK

			# 	    | K | K̄ |
			# | J |    A   B
			# | J̄ |    C   D
			# Fill top diagonal block
			Css[J,K] =  tmpAJK
			Css[K,J] = -tmpAJK

		   ∂Css[J,K] =  tmp∂AJK
		   ∂Css[K,J] =  tmp∂AJK

			# Top right off-diagonal block
			Css[J,halfNx+K] =  tmpBJK
			Css[K,halfNx+J] = -tmpCJK

		   ∂Css[J,halfNx+K] =  tmp∂BJK
		   ∂Css[K,halfNx+J] =  tmp∂BJK

			# Lower right off-diagonal block
			Css[halfNx+J,K] =  tmpCJK
			Css[halfNx+K,J] = -tmpBJK

		   ∂Css[halfNx+J,K] =  tmp∂CJK
		   ∂Css[halfNx+K,J] =  tmp∂CJK

			# Lower diagonal block
			Css[halfNx+J,halfNx+K] =  tmpDJK
			Css[halfNx+K,halfNx+J] = -tmpDJK

			∂Css[halfNx+J,halfNx+K] =  tmp∂DJK
			∂Css[halfNx+K,halfNx+J] =  tmp∂DJK
		end

		# zv .= getfield.(source, :z)
		# Γv .= getfield.(source, :S)
	end

	# Construct the Cauchy matrix to store (z̄-z̄J)/(|z-zJ|^2 + δ^2) and the total induced velocity in Cts and wtarget
	@inbounds for J=1:halfNx
		zJ = source[J].z
		ΓJ = source[J].S
		for i=1:Ny
			xi = target[i]
			ΔiJ = xi - zJ
			tmpregiJ = abs2(ΔiJ) + δ^2
			tmp1iJ = inv(ΔiJ)
			tmp2iJ = conj(ΔiJ)/tmpregiJ

			Cts[i,J] = tmp1iJ
			Cts[i,halfNx+J] = conj(Cts[i,J])

			Ctsblob[i,J] = tmp2iJ
			Ctsblob[i,halfNx+J] = conj(Ctsblob[i,J])

			∂Ctsblob[i,J] = -(δ/tmpregiJ)^2
			∂Ctsblob[i,halfNx+J] = ∂Ctsblob[i,J]

			wtarget[i] += ΓJ*imag(Ctsblob[i,J])
		end
	end
	wtarget .*= (1/π)

	# Evaluate ∂(-∂ϕ/∂t)/∂zL, ∂(-∂ϕ/∂t)/∂z̄L
	@inbounds for L in idx #1:Nx
		SL = -im*source[L].S
		term1 = 0.0*im
		term2 = 0.0*im
		term3 = 0.0*im
		term4 = 0.0*im
		tmp = 0.0*im
		tmp2 = 0.0*im

		# Terms in δJL
		for K=1:Nx
			SK = -im*source[K].S
			tmp = SK*Css[L,K]
			tmp2 = conj(SK*∂Css[L,K])
			term1 += tmp
			term2 -= tmp2
			term3 -= tmp*Css[L,K]
		end

		for i=1:Ny
			tmp3 = Cts[i,L]*conj(term1)
			dpdS[i,L] += tmp3
			tmp4 = SL*Cts[i,L]
			dpdz[i,L] += tmp4*(tmp3+term2)
			dpdz[i,L] += conj(tmp4)*term3
		end

		# Terms in δKL
		for J=1:Nx
			SJ = -im*source[J].S
			for i=1:Ny
				tmp5 = SJ*Cts[i,J]
				termKL = tmp5*conj(SL)*∂Css[J,L]
				termKL += conj(tmp5)*SL*Css[J,L]^2
				dpdz[i,L] += termKL
		   end
	   end
	end

	Γ = getfield.(source, :S)
	# dpdz[:,idx] .+= conj(Cts) .* (im*Γ') .*  (Css .^2 .* -im*Γ')

	dpdz[:,idx] .*=  0.5*cst^2

	# Evaluate ∂(-0.5v^2)/∂zL, ∂(-0.5v^2)/∂z̄L
	@inbounds for L in idx #1:Nx
	   zL = source[L].z
	   SL = -im*source[L].S
	   for i=1:Ny
		   wt = wtarget[i]
		   # Exploit the fact that w(xi) is real
		   dpdz[i,L] -= 0.5*wt*cst*SL*(Ctsblob[i,L]^2-∂Ctsblob[i,L])
	   end
	end

	# Evaluate ∂(-∂ϕ/∂t)/∂SL, ∂(-∂ϕ/∂t)/∂S̄L
	# @inbounds dpdS[:,idx] .+= Cts[:,idx] .* conj(Css[idx,:] * (-im*Γ))'
	# @show size((im*Γ .* Css[:,idx]))
	# @show size(conj(Cts[:,idx]))

	# @inbounds for i=1:Ny
	# 	for J=1:Nx
	# 		tmp = Cts[i,J]*im*Γ[J]
	# 		for L in idx
	# 			dpdS[i,L] += conj(tmp)*Css[J,L]
	# 		end
	# 	end
	# end
	@inbounds dpdS[:,idx] .+= conj(Cts.*(-im*Γ'))*view(Css,:,idx)

	# @inbounds dpdS[:,idx] .+= (conj(Cts)*(im*Γ .* Css))[:,idx]

	dpdS .*= 0.5*cst^2

	# Evaluate ∂(-0.5v^2)/∂SL, ∂(-0.5v^2)/∂S̄L
	@inbounds dpdS[:,idx] .+= -0.5*cst*(wtarget .* Ctsblob[:,idx])

	@inbounds for L in idx
		J[:, 3*(L-1)+1] .= 2*real.(view(dpdz,:,L))
		J[:, 3*(L-1)+2] .= -2*imag.(view(dpdz,:,L))
		J[:, 3*(L-1)+3] .=  2*imag.(view(dpdS,:,L))
	end

	return J
	# J[:, 1:3:3*(Nv-1)+1] .= 2*real.(dpd[:,1:Nv])

end

# # In-place version for regularized vortices
# function symmetric_analytical_jacobian_pressure!(J, wtarget, dpd, dpdstar, Css, Cts, ∂Css, Ctsblob, ∂Ctsblob, target, source::T, idx::Union{Int64, Vector{Int64}, UnitRange{Int64}}, t) where T <: Vector{PotentialFlow.Blobs.Blob{Float64, Float64}}
#     Nv = size(source, 1)
#     Nx = 3*Nv
#     Ny = size(target, 1)
#
# 	@assert size(J) == (Ny, Nx)
# 	@assert size(wtarget) == (Ny,)
# 	@assert size(dpd) == (Ny, Nv)
# 	@assert size(dpdstar) == (Ny, Nv)
# 	@assert size(Css) == (Nv, Nv)
# 	@assert size(Cts) == (Ny, Nv)
# 	@assert size(∂Css) == (Nv, Nv)
# 	@assert typeof(∂Css) <: Matrix{Float64}
# 	@assert size(Ctsblob) == (Ny, Nv)
# 	@assert typeof(Ctsblob) <: Matrix{ComplexF64}
# 	@assert size(∂Ctsblob) == (Ny, Nv)
# 	@assert typeof(∂Ctsblob) <: Matrix{Float64}
#
# 	fill!(J, 0.0)
# 	fill!(wtarget, 0.0)
# 	fill!(dpd, 0.0*im)
# 	fill!(dpdstar, 0.0*im)
# 	fill!(Css, 0.0*im)
# 	fill!(Cts, 0.0*im)
# 	fill!(∂Css, 0.0)
# 	fill!(Ctsblob, 0.0*im)
# 	fill!(∂Ctsblob, 0.0)
#
#     cst = inv(2*π)
#
#     src = vcat(source...)
# 	δ = src[1].δ
#
# 	# Construct the Cauchy matrix to store 1/(zJ-zK) in Css
# 	@inbounds for K=1:Nv
# 		zK = src[K].z
# 		# exploit anti-symmetry of the velocity kernel
# 		# Diagonal entries are equal to 0
# 		for J=K+1:Nv
# 			zJ = src[J].z
# 			tmp = abs2(zJ - zK) + δ^2
# 			Css[J,K] = conj(zJ - zK)/tmp
# 			Css[K,J] = -Css[J,K]
# 			∂Css[J,K] = -(δ/tmp)^2
# 			∂Css[K,J] =  ∂Css[J,K]
# 		end
# 	end
#
# 	# Construct the Cauchy matrix to store (z̄-z̄J)/(|z-zJ|^2 + δ^2) and the total induced velocity in Cts and wtarget
# 	@inbounds for J=1:Nv
# 		zJ = src[J].z
# 		SJ = -im*src[J].S
# 		for i=1:Ny
# 			zi = target[i]
# 			tmp = abs2(zi - zJ) + δ^2
# 			Cts[i,J] = inv(zi - zJ)
# 			Ctsblob[i,J] = conj(zi - zJ)/tmp
# 			∂Ctsblob[i,J] = -(δ/tmp)^2
# 			wtarget[i] += cst*SJ*Ctsblob[i,J]
# 		end
# 	end
#
# 	symmetric_analytical_jacobian_position!(dpd, dpdstar, Css, ∂Css, Cts, Ctsblob, ∂Ctsblob, wtarget, target, src, idx, t;
# 								  iscauchystored = true)
#
# 	# Fill dpdpx and dpdy
#     J[:, 1:3:3*(Nv-1)+1] .= 2*real.(dpd[:,1:Nv])
#     J[:, 2:3:3*(Nv-1)+2] .= -2*imag.(dpd[:,1:Nv])
#
# 	symmetric_analytical_jacobian_strength!(dpd, dpdstar, Css, Cts, Ctsblob, wtarget, target, src, idx, t;
# 								  iscauchystored = true)
#
#     # Vortices
#     J[:, 3:3:3*(Nv-1)+3] .= 2imag.(dpd[:,1:Nv])
#     return J
# end

# In-place version for point vortices
function symmetric_analytical_jacobian_pressure!(J, wtarget, dpd, dpdstar, Css, Cts, target, source::T, idx::Union{Int64, Vector{Int64}, UnitRange{Int64}}, t) where T <: Vector{PotentialFlow.Points.Point{Float64, Float64}}
	Nv = size(source, 1)
	Nx = 3*Nv
	Ny = size(target, 1)

	@assert size(J) == (Ny, Nx)
	@assert size(wtarget) == (Ny,)
	@assert size(dpd) == (Ny, Nv)
	@assert size(dpdstar) == (Ny, Nv)
	@assert size(Css) == (Nv, Nv)
	@assert size(Cts) == (Ny, Nv)

	fill!(J, 0.0)# Construct the Cauchy matrix to store 1/(zJ-zK) in Css
	@inbounds for K=1:Nv
		zK = src[K].z
		# exploit anti-symmetry of the velocity kernel
		# Diagonal entries are equal to 0
		for J=K+1:Nv
			zJ = src[J].z
			tmp = abs2(zJ - zK) + δ^2
			Css[J,K] = conj(zJ - zK)/tmp
			Css[K,J] = -Css[J,K]
			∂Css[J,K] = -(δ/tmp)^2
			∂Css[K,J] =  ∂Css[J,K]
		end
	end

	# Construct the Cauchy matrix to store (z̄-z̄J)/(|z-zJ|^2 + δ^2) and the total induced velocity in Cts and wtarget
	@inbounds for J=1:Nv
		zJ = src[J].z
		SJ = -im*src[J].S
		for i=1:Ny
			zi = target[i]
			tmp = abs2(zi - zJ) + δ^2
			Cts[i,J] = inv(zi - zJ)
			Ctsblob[i,J] = conj(zi - zJ)/tmp
			∂Ctsblob[i,J] = -(δ/tmp)^2
			wtarget[i] += cst*SJ*Ctsblob[i,J]
		end
	end
	fill!(wtarget, 0.0)
	fill!(dpd, 0.0*im)
	fill!(dpdstar, 0.0*im)
	fill!(Css, 0.0*im)
	fill!(Cts, 0.0*im)

	cst = inv(2*π)

	src = vcat(source...)

	# Construct the Cauchy matrix to store 1/(zJ-zK) in Css

	@inbounds for K=1:Nv
		zK = src[K].z
		# exploit anti-symmetry of the velocity kernel
		# Diagonal entries are equal to 0
		for J=K+1:Nv
			zJ = src[J].z
			Css[J,K] = inv(zJ - zK)
			Css[K,J] = -Css[J,K]
		end
	end

	# Construct the Cauchy matrix to store (z̄-z̄J)/(|z-zJ|^2 + δ^2) and the total induced velocity in Cts and wtarget
	@inbounds for J=1:Nv
		zJ = src[J].z
		SJ = -im*src[J].S
		for i=1:Ny
			zi = target[i]
			Cts[i,J] = inv(zi - zJ)
			wtarget[i] += cst*SJ*Cts[i,J]
		end
	end

	symmetric_analytical_jacobian_position!(dpd, dpdstar, Css, Cts, wtarget, target, src, idx, t;
								  iscauchystored = true)

	# Fill dpdpx and dpdy
	J[:, 1:3:3*(Nv-1)+1] .= 2*real.(dpd[:,1:Nv])
	J[:, 2:3:3*(Nv-1)+2] .= -2*imag.(dpd[:,1:Nv])

	symmetric_analytical_jacobian_strength!(dpd, dpdstar, Css, Cts, wtarget, target, src, idx, t;
								  iscauchystored = true)

	# Vortices
	J[:, 3:3:3*(Nv-1)+3] .= 2imag.(dpd[:,1:Nv])

	return J
end


text:
function rcg()
  LB = -Inf
  UB = Inf

  N = 1:data.n
  master = create_model(TIME_LIM)
  @variable(master, x[k in K, i in N], Bin, container=Array)
  @variable(master, η ≥ LB)
  y = Vector{Vector{VariableRef}}()
  w = Vector{Matrix{VariableRef}}()
  for k in K add_constraints_X(master,x[k,:]) end
  #symmetry breaking constraints
  @constraint(master, [k in 1:(length(K)-1)], sum(i*x[k,i] for i in N) + 1 ≤ sum(i*x[k+1,i] for i in N))
  @objective(master, Min, η)

  incumbent = []
  it = 0
  new_cost = populate_scenarios()[2]
  push!(y, @variable(master, [k in K], base_name="y[$it]", Bin))
  push!(w, @variable(master, [k in K, i in N], base_name="w[$it]", Bin))
  @constraint(master, sum(y[it+1][k] for k in K) == 1)
  @constraint(master, [k in K, i in N], w[it+1][k,i] ≥ x[k,i] + y[it+1][k] -1)
  @constraint(master, [k in K, i in N], w[it+1][k,i] ≤ x[k,i])
  @constraint(master, [k in K, i in N], w[it+1][k,i] ≤ y[it+1][k])
  @constraint(master, η ≥ sum(new_cost[i]*w[it+1][k,i] for k in K, i in N))
  gap = 100
  new_scenario_added = true
  while new_scenario_added && time()-STARTTIME < TIME_LIM
    it += 1

    optimize!(master)
    # the second argument is the cost of the solution for the current set of scenarios. It is only
    # needed when constraint uncertainty arise
    if termination_status(master) == MOI.OPTIMAL
      LB = objective_value(master)
      ξ, objective_slave, feasible = build_and_solve_separation(value.(x),0)
      if length(ξ)>0 && objective_slave < UB
        UB = objective_slave
        incumbent = value.(x)
      end
    else
      break
    end
    gap = 100*round((UB - LB)/abs(UB), digits = 4)
    if gap > ϵ && length(ξ)>0
      (new_cost, new_weight) = add_scenario(ξ)
      push!(y, @variable(master, [k in K], base_name="y[$it]", Bin))
      push!(w, @variable(master, [k in K, i in N], base_name="w[$it]", Bin))
      @constraint(master, sum(y[it+1][k] for k in K) == 1)
      @constraint(master, [k in K, i in N], w[it+1][k,i] ≥ x[k,i] + y[it+1][k] -1)
      @constraint(master, [k in K, i in N], w[it+1][k,i] ≤ x[k,i])
      @constraint(master, [k in K, i in N], w[it+1][k,i] ≤ y[it+1][k])
      @constraint(master, η ≥ sum(new_cost[i]*w[it+1][k,i] for k in K, i in N))
    else new_scenario_added = false
    end
    println("$LB  $UB $gap $it")
  end
  return LB, UB, incumbent, gap, it
end

max_stars_repo_name: mjposs/min-max-min

max_issues_repo_name: mjposs/min-max-min

max_forks_repo_name: mjposs/min-max-min


text:
@testset "Neural Statistician" begin
    Random.seed!(0)
    # create dummy data
    N = 10
    data = [randn(3,rand(Poisson(30))) .+ 5 for i in 1:N]

    # number of neurons
    xdim = 3
    hdim = 8
    vdim = 4
    cdim = 4
    zdim = 2

    # model components
    instance_enc = Chain(Dense(xdim, hdim, swish), Dense(hdim, hdim, swish), Dense(hdim, vdim))

    enc_c = Chain(Dense(vdim,hdim,swish),Dense(hdim,hdim,swish), SplitLayer(hdim, [cdim,cdim], [identity,softplus]))
    enc_c_dist = ConditionalMvNormal(enc_c)

    cond_z = Chain(Dense(cdim,hdim,swish),Dense(hdim,hdim,swish),SplitLayer(hdim, [zdim,zdim], [identity,softplus]))
    cond_z_dist = ConditionalMvNormal(cond_z)

    enc_z = Chain(Dense(cdim+vdim,hdim,swish),Dense(hdim,hdim,swish), SplitLayer(hdim, [zdim,zdim], [identity,softplus]))
    enc_z_dist = ConditionalMvNormal(enc_z)

    dec = Chain(Dense(zdim,hdim,swish),Dense(hdim,hdim,swish), SplitLayer(hdim, [xdim,1], [identity,softplus]))
    dec_dist = ConditionalMvNormal(dec)

    # model initialization
    model = NeuralStatistician(instance_enc, cdim, enc_c_dist, cond_z_dist, enc_z_dist, dec_dist)

    # training init
    params_init = get_params(model)
    ps = Flux.params(model)
    @test length(ps) > 0

    # loss
    # extend kl_divergence from IPMeasures
    using IPMeasures: _kld_gaussian
    (m::KLDivergence)(p::ConditionalDists.BMN, q::ConditionalDists.BMN) = _kld_gaussian(p,q)
    loss(x) = -elbo(model,x)

    ls = mean(loss.(data))
    @test isa(ls, Real)

    # train the model
    opt = ADAM()
    Flux.train!(loss,ps,data,opt)

    # test change of parameters
    @test all(param_change(params_init, model))

    # test loss reduction
    new_ls = mean(loss.(data))
    @test new_ls < ls
end


text:
# Default env constructor
env = Linda.LindaEnv()

# Test param functions
@test Linda.get_param_name(env.verbose) == :verbose
@test Linda.get_param_type(env.verbose) == Int64
@test Linda.get_param_type(env.time_limit) == Float64
@test Linda.get_param_value(env.verbose) == env.verbose.def_val
@test !Linda.test_param_value(env.verbose, -1)

# Test that `getindex(env, ::Type{Val{:###}}` have properly been set
for s in fieldnames(Linda.LindaEnv)
    @test env[Val{s}] == env[s]
end

# Check parameter assignment
env[:verbose] = 1.0
@test env.verbose.val == 1

env[:time_limit] = Int(1)
env[:time_limit] = 1.0
env[:time_limit] = BigFloat(1.0)
@test env.time_limit.val == 1.0

Linda.setparam!(env, verbose=1, time_limit=10)
@test env.verbose.val == 1
@test env.time_limit.val == 10.0

try
    env[:time_limit] = -1.0
catch e
    @test e.msg == "time_limit must be between 0.0 and Inf."
end

Linda.reset!(env)
for s in fieldnames(Linda.LindaEnv)
    p = Core.getfield(env, s)
    @test env[s] == p.def_val
end


text:
using CausalInference
using Graphs
using Test

include("skeleton.jl")
include("dsep.jl")
include("pc.jl")
include("cpdag.jl")
include("combinations.jl")
include("witness.jl")
include("fci.jl")
include("klentropy.jl")
include("backdoor.jl")


text:
@testset ExtendedTestSet "euclidean" begin
    @testset ExtendedTestSet "euclidean" begin
        x = [
            1 1 0 0
            0 1 1 0
            0 1 0 1
            0 1 0 0
        ]
        answer = [
            1.0 1.0 0.0 0.0
            0.0 1.0 1.0 0.0
            0.0 1.0 0.0 1.0
            0.0 1.0 0.0 0.0
        ]
        @test euclidean(x) == answer
    end

    @testset ExtendedTestSet "euclidean" begin
        x = [
            1 1 1 0
            0 1 1 1
            0 1 1 1
            0 1 1 1
        ]
        answer = [
            1.0 1.4142135623730951 1.0 0.0
            0.0 1.0 1.4142135623730951 1.0
            0.0 1.0 2.0 2.0
            0.0 1.0 2.0 3.0
        ]
        @test euclidean(x) ≈ answer
    end

    @testset ExtendedTestSet "euclidean" begin
        x = Bool.([
            1 1 0 0
            0 1 1 0
            0 1 0 1
            0 1 0 0
        ])
        answer = [
            1.0 1.0 0.0 0.0
            0.0 1.0 1.0 0.0
            0.0 1.0 0.0 1.0
            0.0 1.0 0.0 0.0
        ]
        @test euclidean(x) == answer
    end
end


text:
global gsetting, # 泛设置
langs, # 当前语言内容
data, # 当前打开的数据
game, # 当前游戏
lsetting, # 当前游戏设置
ply, # 当前玩家
dim, # 当前维度
saved, # 当前保存数据 saved[维度名]=data
sav, # 当前维度保存数据 sav[区块坐标（64倍数）][相对坐标编码（索引1）]=方块数据（引用）
ltemp, # 临时数据表
curpage, # 当前页名称
window, # 当前窗口
winbox, # window下的box
curui, # 当前打开的GUI板
dcon, # 画板上下文
loadedimgs, # 已加载的图片
after_show=Dict{Symbol,Function}(), # show后调用
curuse # 当前使用的东西


text:
using Delta

featdims  = 64
timesteps = 124
batchsize = 16

# 1. make some pseudo inputs
x = Variable(randn(featdims,timesteps,batchsize));

# 2. make some pseudo seqlabels
seqlabels = Vector(undef,batchsize)
for i=1:batchsize
    seqlabels[i] = [2, 3, 4, 5]
end

# 3. build PlainConv1d layers
c1 = PlainConv1d(featdims,256,8,stride=3)
c2 = PlainConv1d(256,256,3,stride=2)
c3 = PlainConv1d(256,512,3,stride=1)
c4 = PlainConv1d(512,512,3,stride=1)
c5 = PlainConv1d(512,512,3,stride=1)
chain1 = Chain(c1,c2,c3,c4,c5);

# 4. build a structure with recurrent operators
r1 = IndRNN(512,512)
r2 = IndRNN(512,512)
f1 = Linear(512,1400)
chain2 = Chain(r1,r2,f1);

p1 = xparamsof(chain1);
p2 = xparamsof(chain2);

optim1 = Momentum(p1);
optim2 = Momentum(p2);

for i=1:20
    # for non-recurrent layers, we computes all timesteps at once
    y1 = forward(chain1, x);
    # sequential forward propagation
    y2 = PackedSeqForward(chain2, y1);
    # computes ctc loss
    logLikely = CRNN_Batch_CTC_With_Softmax(y2, seqlabels);
    println(logLikely);
    # backward gradients and update! params
    backward();
    update!(optim1,p1,clipvalue=10.0);
    update!(optim2,p2,clipvalue=10.0);
    # zero gradients
    zerograds!(p1);
    zerograds!(p2);
end

max_stars_repo_name: sonosole/Delta

max_issues_repo_name: sonosole/Delta

max_forks_repo_name: sonosole/Delta


text:
require("Ito")
using Base.Test
using Ito.Currencies

# Testing money arithmetic without conversions...

EUR=Currencies.EURCurrency()

m1 = 50000.0 * EUR;
m2 = 100000.0 * EUR;
m3 = 500000.0 * EUR;

Currencies.setConversionType(:NoConversion)

calculated = m1*3.0 + 2.5*m2 - m3/5.0
x = m1.value*3.0 + 2.5*m2.value - m3.value/5.0
expected=Currencies.Money(x, EUR)

@test calculated==expected

# Testing money arithmetic with conversion to base currency...

EUR=Currencies.EURCurrency()
GBP=Currencies.GBPCurrency()
USD=Currencies.USDCurrency()

m1 = 50000.0 * GBP
m2 = 100000.0 * EUR
m3 = 500000.0 * USD

Currencies.clear()

eur_usd=Currencies.ExchangeRate(EUR, USD, 1.2042)
eur_gbp=Currencies.ExchangeRate(EUR, GBP, 0.6612)
Currencies.add(eur_usd)
Currencies.add(eur_gbp)

Currencies.setConversionType(:BaseCurrencyConversion)
Currencies.setStaticBaseCurrency(EUR)

calculated=m1*3.0+2.5*m2-m3/5.0
_round=Currencies.baseCurrency(m1).rounding
x=_round(m1.value*3.0/eur_gbp.rate)+2.5*m2.value-_round(m3.value/(5.0*eur_usd.rate))
expected=Currencies.Money(x, EUR)

Currencies.setConversionType(:NoConversion)

@test calculated==expected

# Testing money arithmetic with automated conversion...

EUR=Currencies.EURCurrency()
GBP=Currencies.GBPCurrency()
USD=Currencies.USDCurrency()

m1 = 50000.0 * GBP
m2 = 100000.0 * EUR
m3 = 500000.0 * USD

Currencies.clear()

eur_usd=Currencies.ExchangeRate(EUR, USD, 1.2042)
eur_gbp=Currencies.ExchangeRate(EUR, GBP, 0.6612)
Currencies.add(eur_usd)
Currencies.add(eur_gbp)

Currencies.setConversionType(:AutomatedConversion)

calculated=(m1*3.0+2.5*m2)-m3/5.0
_round=m1.currency.rounding
x=m1.value*3.0+_round(2.5*m2.value*eur_gbp.rate)-_round((m3.value/5.0)*eur_gbp.rate/eur_usd.rate)
expected=Currencies.Money(x, GBP)

Currencies.setConversionType(:NoConversion)

@test calculated==expected


text:
#=
imresize.jl
Down-sample or up-sample a binary mask;
very specialized versions of `imresize`.
=#

export downsample!, downsample
export upsample!, upsample

"""
    downsample!(y, x, down::NTuple{Int})
Non-allocating version of `y = downsample(x, down)`.
Requires `size(y) = ceil(size(x) / down)`.
"""
function downsample!(
    y::BitArray{D},
    x::Union{BitArray{D}, AbstractArray{Bool,D}},
    down::NTuple{D,Int},
) where {D}
    size(y) == ceil.(Int, size(x) ./ down) || throw(DimensionMismatch())
    p = prod(down)
    for i in CartesianIndices(x)
        j = CartesianIndex( (((Tuple(i) .- 1) .÷ down) .+ 1)... )
        @inbounds y[j] |= x[i]
    end
    return y
end

"""
    y = downsample(x, down::NTuple{Int})
Down-sample a `Bool` array `x` by "max pooling" in all dimensions.
Output size will be `ceil(size(x) / down)`.
Thus, in a typical case where `size(x)` is integer multiple of `down`,
the output size will be `size(x) ÷ down`.
"""
function downsample(
    x::Union{BitArray{D}, AbstractArray{Bool,D}},
    down::NTuple{D,Int},
) where {D}
    y = falses(ceil.(Int, size(x) ./ down))
    return downsample!(y, x, down)
end

"""
    upsample!(y, x, up::NTuple{Int})
Non-allocating version of `y = upsample(x, up)`.
Requires `size(y) = ceil(size(x) * up)`.
"""
function upsample!(
    y::BitArray{D},
    x::Union{BitArray{D}, AbstractArray{Bool,D}},
    up::NTuple{D,Int},
) where {D}
    size(y) == size(x) .* up || throw(DimensionMismatch())
    p = prod(up)
    for j in CartesianIndices(y)
        i = CartesianIndex( (((Tuple(j) .- 1) .÷ up) .+ 1)... )
        @inbounds y[j] |= x[i]
    end
    return y
end

"""
    y = upsample(x, up::NTuple{Int})
Up-sample a `Bool` array `x` by "repeating" in all dimensions.
Output size will be `size(x) * up`.
"""
function upsample(
    x::Union{BitArray{D}, AbstractArray{Bool,D}},
    up::NTuple{D,Int},
) where {D}
    y = falses(size(x) .* up)
    return upsample!(y, x, up)
end


text:
using Test, XPORTA, Polyhedra

@testset "./src/ConvexPolytope/adjacency_decomposition.jl" begin

using BellComm: ConvexPolytope

@testset "ConvexPolytope.rotate_facet()" begin

    F = HalfSpace([-1,0,0], 0)
    G1 = HalfSpace([0,0,-1], 0)
    G2 = HalfSpace([0,0,1], 1)

    xbar = [1,0,0]

    # neighboring facet 1
    @test ConvexPolytope.rotate_facet(F,G1,xbar) == HalfSpace([0,0,-1], 0)
    @test ConvexPolytope.rotate_facet(F,G2,xbar) == HalfSpace([0,-1,0], 0)

end

end


text:
using ValidatedNumerics, SparseArrays
using ..DynamicDefinition, ..BasisDefinition

using LinearAlgebra

import ValidatedNumerics.IntervalArithmetic: mid
import Base: size, eltype
import LinearAlgebra: mul!

"""
Very generic assembler function
"""
function assemble(B::Basis, D::Dynamic, ϵ=2^(-40); T = Float64)
	I = Int64[]
	J = Int64[]
	nzvals = Interval{T}[]
	n = length(B)

	# TODO: reasonable size hint?

	for (i, dual_element) in DualComposedWithDynamic(B, D, ϵ)
		if dual_element != :∅
			for (j, x) in ProjectDualElement(B, dual_element)
				push!(I, i)
				push!(J, mod(j,1:n))
				push!(nzvals, x)
			end
		end
	end

	return sparse(I, J, nzvals, n, n)
end

abstract type DiscretizedOperator end

struct IntegralPreservingDiscretizedOperator{T<:AbstractMatrix} <: DiscretizedOperator
	L:: T
end
IntegralPreservingDiscretizedOperator(L) = IntegralPreservingDiscretizedOperator{typeof(L)}(L)

"""
An operator of the form Q = L + e*w (sparse plus rank-1).
"""
struct NonIntegralPreservingDiscretizedOperator{T<:AbstractMatrix, S<:AbstractVector, U<:AbstractMatrix} <: DiscretizedOperator
	L:: T
	e:: S
	w:: U
end
NonIntegralPreservingDiscretizedOperator(L, e, w) = NonIntegralPreservingDiscretizedOperator{typeof(L), typeof(e), typeof(w)}(L, e, w)

# Some cruft needed for eigs
Base.size(Q::DiscretizedOperator) = size(Q.L)
Base.eltype(Q::DiscretizedOperator) = eltype(Q.L)
LinearAlgebra.issymmetric(Q::IntegralPreservingDiscretizedOperator) = issymmetric(Q.L)
LinearAlgebra.issymmetric(Q::NonIntegralPreservingDiscretizedOperator) = issymmetric(Q.L) && Q.e' == Q.w

opnormbound(N::Type{<:NormKind}, Q::IntegralPreservingDiscretizedOperator) = opnormbound(N, Q.L)

function DiscretizedOperator(B::Basis, D::Dynamic, ϵ=2^(-40); T = Float64)
	L = assemble(B, D, ϵ; T)
	if is_integral_preserving(B)
		return IntegralPreservingDiscretizedOperator(L)
	else
		f = integral_covector(B)
		e = one_vector(B)
		w = f - f*L #will use interval arithmetic when L is an interval matrix
		return NonIntegralPreservingDiscretizedOperator(L, e, w)
	end
end

function opnormbound(N::Type{<:NormKind}, Q::NonIntegralPreservingDiscretizedOperator)
	normL = opnormbound(N, Q.L)
	norme = opnormbound(N, Q.e)
	normw = opnormbound(N, Q.w)
	return normL ⊕₊ norme ⊗₊ normw
end

function IntervalArithmetic.mid(Q::IntegralPreservingDiscretizedOperator)
	return IntegralPreservingDiscretizedOperator(map(mid, Q.L))
end
function IntervalArithmetic.mid(Q::NonIntegralPreservingDiscretizedOperator)
	# we are assuming that e is *not* an interval, for now. Types will break otherwise;
	# this may need to be fixed in an API.
	return NonIntegralPreservingDiscretizedOperator(map(mid, Q.L), Q.e, map(mid, Q.w))
end

function LinearAlgebra.mul!(Y, Q::IntegralPreservingDiscretizedOperator, v::AbstractArray, α, β)
	mul!(Y, Q.L, v, α, β)
end

function LinearAlgebra.mul!(Y, Q::NonIntegralPreservingDiscretizedOperator, v::AbstractArray, α, β)
	mul!(Y, Q.L, v, α, β)
	T = Base.promote_eltype(Q.e, Q.w)
	Y .+= convert(Array{T},Q.e) * (Q.w * v) * α
end

# these should be defined in terms of mul!, but it's simpler for now
function Base.:*(Q::IntegralPreservingDiscretizedOperator, v::Array)
	return Q.L * v
end

function Base.:*(Q::NonIntegralPreservingDiscretizedOperator, v::Array)
	T = Base.promote_eltype(Q.e, Q.w)
	return Q.L * v + convert(Array{T},Q.e) * (Q.w * v)
end

BasisDefinition.is_integral_preserving(Q::NonIntegralPreservingDiscretizedOperator) = false
BasisDefinition.is_integral_preserving(Q::IntegralPreservingDiscretizedOperator) = true

max_stars_repo_name: orkolorko/ResponseManneville

max_issues_repo_name: orkolorko/ResponseManneville

max_forks_repo_name: orkolorko/ResponseManneville


text:
using DynamicalSystems, Base.Test

println("\nTesting discrete system lyapunov exponents...")

@testset "Towel Map" begin
  @testset "lyapunovs" begin
    ds = Systems.towel()
    λ1 = lyapunovs(ds, 1e5)
    @test 0.42 < λ1[1] < 0.44
    @test 0.36 < λ1[2] < 0.38
    @test -3.4 < λ1[3] < -3.2
  end

  @testset "lyapunovs ForwardDiff" begin
    ds = Systems.towel()
    ds = DiscreteDS(ds.state, ds.eom)
    λ1 = lyapunovs(ds, 1e5)
    @test 0.42 < λ1[1] < 0.44
    @test 0.36 < λ1[2] < 0.38
    @test -3.4 < λ1[3] < -3.1
  end

  @testset "lyapunov" begin
    ds1 = Systems.towel()
    ds2 = DiscreteDS(ds1.state, ds1.eom)
    λ1 = lyapunov(ds1, 100000)
    λ2 = lyapunov(ds2, 100000)
    @test 0.42 < λ1[1] < 0.44
    @test 0.42 < λ2[1] < 0.44
    @test isapprox(λ1, λ2; rtol = 1e-3)
  end
end

@testset "Logistic Map" begin
  lg1 = Systems.logistic(0.1, r=4)
  lg2 = DiscreteDS1D(lg1.state, lg1.eom)
  lg3 = Systems.logistic(big(0.1), r=4)
  @test typeof(lg3.state) == BigFloat
  λ1 = lyapunov(lg1, 10000000; Ttr = 100)
  λ2 = lyapunovs(lg2, 10000000; Ttr = 100)
  λ3 = lyapunovs(lg3, 100000; Ttr = 100)
  @test typeof(λ3) == BigFloat
  @test isapprox(λ1, log(2); rtol = 1e-3)
  @test isapprox(λ2, log(2); rtol = 1e-3)
  @test isapprox(λ3, log(2); rtol = 1e-3)
end

@testset "Henon Map" begin
  @testset "lyapunovs" begin
    ds = Systems.henon()
    λ1 = lyapunovs(ds, 1e6)
    @test 0.418 < λ1[1] < 0.422
    @test -1.63 < λ1[2] < -1.61
  end

  @testset "lyapunovs ForwardDiff" begin
    ds = Systems.henon()
    ds = DiscreteDS(ds.state, ds.eom)
    λ1 = lyapunovs(ds, 1e6)
    @test 0.418 < λ1[1] < 0.422
    @test -1.63 < λ1[2] < -1.61
  end

  @testset "lyapunov" begin
    ds1 = Systems.henon()
    ds2 = DiscreteDS(ds1.state, ds1.eom)
    λ1 = lyapunov(ds1, 1000000)
    λ2 = lyapunov(ds2, 1000000)
    @test 0.418 < λ1[1] < 0.422
    @test 0.418 < λ2[1] < 0.422
    @test isapprox(λ1, λ2; rtol = 1e-3)
  end
end


text:
struct NonlocalSystemMatrix{T} <: NoAccessArray{T, 2}
    Ξ       ::PositionVector{T} # soa
    elements::TriangleVector{T} # aso
    params  ::Option{T}
end

@inline function NonlocalSystemMatrix(model::Model{T, Triangle{T}}) where T
    NonlocalSystemMatrix(
        PositionVector([e.center for e in model.elements]),
        TriangleVector(model.elements),
        model.params
    )
end

@inline Base.size(A::NonlocalSystemMatrix{T}) where T = (3 * length(A.Ξ), 3 * length(A.elements))

@inline function Base.show(io::IO, ::MIME"text/plain", A::NonlocalSystemMatrix{T}) where T
    print(io, join(size(A), "×"), " ", typeof(A), "($(repr(A.params)))")
end

function LinearAlgebra.diag(A::NonlocalSystemMatrix{T}, k::Int = 0) where T
    k != 0 && error("diag not defined for k != 0")
    Kʸ = ReYukawaPotentialMatrix{DoubleLayer}(A.Ξ, A.elements, yukawa(A.params))
    V  = LaplacePotentialMatrix{SingleLayer}(A.Ξ, A.elements)
    σ  = T(2π) .* ones(T, size(A.Ξ, 1))
    [ σ .- diag(Kʸ); diag(V) ; σ ]
end

@inline function LinearAlgebra.mul!(
    Y::AbstractArray{T, 1},
    A::NonlocalSystemMatrix{T},
    v::AbstractArray{T, 1}
) where T
    Y .= A * v
end

@inline function Base.:*(A::NonlocalSystemMatrix{T}, x::AbstractArray{T, 1}) where T
    Array(_mul(A.Ξ, A.elements, CuArray(x), A.params))
end

function _mul(
    Ξ       ::PositionVector{T},
    elements::TriangleVector{T},
    x       ::CuVector{T},
    params  ::Option{T}
) where T
    numelem = length(elements)
    cfg = _kcfg(numelem)
    εΩ  = params.εΩ
    εΣ  = params.εΣ
    ε∞  = params.ε∞
    yuk = yukawa(params)

    V  = LaplacePotentialMatrix{SingleLayer}(Ξ, elements)
    Vʸ = ReYukawaPotentialMatrix{SingleLayer}(Ξ, elements, yuk)

    u  = x[1:numelem]
    q  = x[numelem+1:2numelem]
    w  = x[2numelem+1:3numelem]

    ls = V * q
    ys = (εΩ * (1/ε∞ - 1/εΣ)) .* (Vʸ * q)

    ld = CuArray{T}(undef, 3numelem)
    @cuda threads=cfg.threads blocks=cfg.blocks _mul_ld_kernel!(ld, Ξ, elements, x)

    yd = CuArray{T}(undef, numelem)
    @cuda threads=cfg.threads blocks=cfg.blocks _mul_yd_kernel!(yd, Ξ, elements, x, ε∞/εΣ, yuk)

    [
        T(2π) .* u .+ (εΩ/ε∞) .* ls .+ ld[1:numelem] .+ ys .+ yd;
        T(2π) .* u .- ls .+ ld[numelem+1:2numelem];
        T(2π) .* w .+ (εΩ/ε∞) .* ls .+ ld[2numelem+1:end]
    ]
end

struct NonlocalSystemOutputs{T} <: ReadOnlyArray{T, 1}
    β      ::Vector{T}
end

function NonlocalSystemOutputs(
    A   ::NonlocalSystemMatrix{T},
    umol::Vector{T},
    qmol::Vector{T}
) where T
    εΩ   = A.params.εΩ
    εΣ   = A.params.εΣ
    ε∞   = A.params.ε∞
    yuk  = yukawa(A.params)
    Ṽ    = LaplacePotentialMatrix{SingleLayer}(A.Ξ, A.elements)
    W    = LaplacePotentialMatrix{DoubleLayer}(A.Ξ, A.elements)
    ṼʸmṼ = ReYukawaPotentialMatrix{SingleLayer}(A.Ξ, A.elements, yuk)
    WʸmW = ReYukawaPotentialMatrix{DoubleLayer}(A.Ξ, A.elements, yuk)

    NonlocalSystemOutputs(
        W * umol .+ ((1 - εΩ/εΣ) .* (WʸmW * umol)) .- (T(2π) .* umol) .-
        ((εΩ/ε∞) .* (Ṽ * qmol)) .+ ((εΩ * (1/εΣ - 1/ε∞)) .* (ṼʸmṼ * qmol))
    )
end

@inline Base.size(v::NonlocalSystemOutputs{T}) where T = 3 .* Base.size(v.β)

@inline function Base.getindex(v::NonlocalSystemOutputs{T}, i::Int) where T
    @boundscheck checkbounds(v, i)
    @inbounds i ∈ 1:size(v.β, 1) ? Base.getindex(v.β, i) : zero(T)
end

struct NonlocalSystem{T}
    model::Model{T, Triangle{T}}
    A    ::NonlocalSystemMatrix{T}
    b    ::NonlocalSystemOutputs{T}
    umol ::Vector{T}
    qmol ::Vector{T}
end

function NonlocalSystem(model::Model{T, Triangle{T}}) where T
    cuΞ    = PositionVector([e.center for e in model.elements])
    cuelms = TriangleVector(model.elements)

    A    = NonlocalSystemMatrix(cuΞ, cuelms, model.params)
    umol = model.params.εΩ .\   φmol(model, tolerance=_etol(T))
    qmol = model.params.εΩ .\ ∂ₙφmol(model)
    b    = NonlocalSystemOutputs(A, umol, qmol)

    NonlocalSystem(model, A, b, umol, qmol)
end

function solve(sys::NonlocalSystem{T}) where T
    numξ = length(sys.A.Ξ)
    cauchy  = _solve_linear_system(sys.A, sys.b)
    NonlocalBEMResult(
        sys.model,
        view(cauchy, 1:numξ),
        view(cauchy, 1+numξ:2numξ),
        view(cauchy, 1+2numξ:3numξ),
        sys.umol,
        sys.qmol
    )
end

@inline solve(
         ::Type{NonlocalES},
    model::Model{T, Triangle{T}}
) where T = solve(NonlocalSystem(model))