text:
# This file is auto-generated by AWSMetadata.jl
using AWS
using AWS.AWSServices: sns
using AWS.Compat
using AWS.UUIDs
"""
    AddPermission()

Adds a statement to a topic's access control policy, granting access for the specified AWS accounts to the specified actions.

# Required Parameters
- `AWSAccountId`: The AWS account IDs of the users (principals) who will be given access to the specified actions. The users must have AWS accounts, but do not need to be signed up for this service.
- `ActionName`: The action you want to allow for the specified principal(s). Valid values: Any Amazon SNS action name, for example Publish.
- `Label`: A unique identifier for the new policy statement.
- `TopicArn`: The ARN of the topic whose access control policy you wish to modify.

"""

add_permission(AWSAccountId, ActionName, Label, TopicArn; aws_config::AWSConfig=global_aws_config()) = sns("AddPermission", Dict{String, Any}("AWSAccountId"=>AWSAccountId, "ActionName"=>ActionName, "Label"=>Label, "TopicArn"=>TopicArn); aws_config=aws_config)
add_permission(AWSAccountId, ActionName, Label, TopicArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = sns("AddPermission", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("AWSAccountId"=>AWSAccountId, "ActionName"=>ActionName, "Label"=>Label, "TopicArn"=>TopicArn), args)); aws_config=aws_config)

"""
    CheckIfPhoneNumberIsOptedOut()

Accepts a phone number and indicates whether the phone holder has opted out of receiving SMS messages from your account. You cannot send SMS messages to a number that is opted out. To resume sending messages, you can opt in the number by using the OptInPhoneNumber action.

# Required Parameters
- `phoneNumber`: The phone number for which you want to check the opt out status.

"""

check_if_phone_number_is_opted_out(phoneNumber; aws_config::AWSConfig=global_aws_config()) = sns("CheckIfPhoneNumberIsOptedOut", Dict{String, Any}("phoneNumber"=>phoneNumber); aws_config=aws_config)
check_if_phone_number_is_opted_out(phoneNumber, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = sns("CheckIfPhoneNumberIsOptedOut", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("phoneNumber"=>phoneNumber), args)); aws_config=aws_config)

"""
    ConfirmSubscription()

Verifies an endpoint owner's intent to receive messages by validating the token sent to the endpoint by an earlier Subscribe action. If the token is valid, the action creates a new subscription and returns its Amazon Resource Name (ARN). This call requires an AWS signature only when the AuthenticateOnUnsubscribe flag is set to \"true\".

# Required Parameters
- `Token`: Short-lived token sent to an endpoint during the Subscribe action.
- `TopicArn`: The ARN of the topic for which you wish to confirm a subscription.

# Optional Parameters
- `AuthenticateOnUnsubscribe`: Disallows unauthenticated unsubscribes of the subscription. If the value of this parameter is true and the request has an AWS signature, then only the topic owner and the subscription owner can unsubscribe the endpoint. The unsubscribe action requires AWS authentication.
"""

confirm_subscription(Token, TopicArn; aws_config::AWSConfig=global_aws_config()) = sns("ConfirmSubscription", Dict{String, Any}("Token"=>Token, "TopicArn"=>TopicArn); aws_config=aws_config)
confirm_subscription(Token, TopicArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = sns("ConfirmSubscription", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Token"=>Token, "TopicArn"=>TopicArn), args)); aws_config=aws_config)

"""
    CreatePlatformApplication()

Creates a platform application object for one of the supported push notification services, such as APNS and GCM (Firebase Cloud Messaging), to which devices and mobile apps may register. You must specify PlatformPrincipal and PlatformCredential attributes when using the CreatePlatformApplication action.  PlatformPrincipal and PlatformCredential are received from the notification service.   For ADM, PlatformPrincipal is client id and PlatformCredential is client secret.   For Baidu, PlatformPrincipal is API key and PlatformCredential is secret key.   For APNS and APNS_SANDBOX, PlatformPrincipal is SSL certificate and PlatformCredential is private key.   For GCM (Firebase Cloud Messaging), there is no PlatformPrincipal and the PlatformCredential is API key.   For MPNS, PlatformPrincipal is TLS certificate and PlatformCredential is private key.   For WNS, PlatformPrincipal is Package Security Identifier and PlatformCredential is secret key.   You can use the returned PlatformApplicationArn as an attribute for the CreatePlatformEndpoint action.

# Required Parameters
- `Attributes`: For a list of attributes, see SetPlatformApplicationAttributes
- `Name`: Application names must be made up of only uppercase and lowercase ASCII letters, numbers, underscores, hyphens, and periods, and must be between 1 and 256 characters long.
- `Platform`: The following platforms are supported: ADM (Amazon Device Messaging), APNS (Apple Push Notification Service), APNS_SANDBOX, and GCM (Firebase Cloud Messaging).

"""

create_platform_application(Attributes, Name, Platform; aws_config::AWSConfig=global_aws_config()) = sns("CreatePlatformApplication", Dict{String, Any}("Attributes"=>Attributes, "Name"=>Name, "Platform"=>Platform); aws_config=aws_config)
create_platform_application(Attributes, Name, Platform, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = sns("CreatePlatformApplication", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Attributes"=>Attributes, "Name"=>Name, "Platform"=>Platform), args)); aws_config=aws_config)

"""
    CreatePlatformEndpoint()

Creates an endpoint for a device and mobile app on one of the supported push notification services, such as GCM (Firebase Cloud Messaging) and APNS. CreatePlatformEndpoint requires the PlatformApplicationArn that is returned from CreatePlatformApplication. You can use the returned EndpointArn to send a message to a mobile app or by the Subscribe action for subscription to a topic. The CreatePlatformEndpoint action is idempotent, so if the requester already owns an endpoint with the same device token and attributes, that endpoint's ARN is returned without creating a new endpoint. For more information, see Using Amazon SNS Mobile Push Notifications.  When using CreatePlatformEndpoint with Baidu, two attributes must be provided: ChannelId and UserId. The token field must also contain the ChannelId. For more information, see Creating an Amazon SNS Endpoint for Baidu.

# Required Parameters
- `PlatformApplicationArn`: PlatformApplicationArn returned from CreatePlatformApplication is used to create a an endpoint.
- `Token`: Unique identifier created by the notification service for an app on a device. The specific name for Token will vary, depending on which notification service is being used. For example, when using APNS as the notification service, you need the device token. Alternatively, when using GCM (Firebase Cloud Messaging) or ADM, the device token equivalent is called the registration ID.

# Optional Parameters
- `Attributes`: For a list of attributes, see SetEndpointAttributes.
- `CustomUserData`: Arbitrary user data to associate with the endpoint. Amazon SNS does not use this data. The data must be in UTF-8 format and less than 2KB.
"""

create_platform_endpoint(PlatformApplicationArn, Token; aws_config::AWSConfig=global_aws_config()) = sns("CreatePlatformEndpoint", Dict{String, Any}("PlatformApplicationArn"=>PlatformApplicationArn, "Token"=>Token); aws_config=aws_config)
create_platform_endpoint(PlatformApplicationArn, Token, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = sns("CreatePlatformEndpoint", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("PlatformApplicationArn"=>PlatformApplicationArn, "Token"=>Token), args)); aws_config=aws_config)

"""
    CreateTopic()

Creates a topic to which notifications can be published. Users can create at most 100,000 topics. For more information, see https://aws.amazon.com/sns. This action is idempotent, so if the requester already owns a topic with the specified name, that topic's ARN is returned without creating a new topic.

# Required Parameters
- `Name`: The name of the topic you want to create. Constraints: Topic names must be made up of only uppercase and lowercase ASCII letters, numbers, underscores, and hyphens, and must be between 1 and 256 characters long.

# Optional Parameters
- `Attributes`: A map of attributes with their corresponding values. The following lists the names, descriptions, and values of the special request parameters that the CreateTopic action uses:    DeliveryPolicy – The policy that defines how Amazon SNS retries failed deliveries to HTTP/S endpoints.    DisplayName – The display name to use for a topic with SMS subscriptions.    Policy – The policy that defines who can access your topic. By default, only the topic owner can publish or subscribe to the topic.   The following attribute applies only to server-side-encryption:    KmsMasterKeyId - The ID of an AWS-managed customer master key (CMK) for Amazon SNS or a custom CMK. For more information, see Key Terms. For more examples, see KeyId in the AWS Key Management Service API Reference.
- `Tags`: The list of tags to add to a new topic.  To be able to tag a topic on creation, you must have the sns:CreateTopic and sns:TagResource permissions.
"""

create_topic(Name; aws_config::AWSConfig=global_aws_config()) = sns("CreateTopic", Dict{String, Any}("Name"=>Name); aws_config=aws_config)
create_topic(Name, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = sns("CreateTopic", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Name"=>Name), args)); aws_config=aws_config)

"""
    DeleteEndpoint()

Deletes the endpoint for a device and mobile app from Amazon SNS. This action is idempotent. For more information, see Using Amazon SNS Mobile Push Notifications.  When you delete an endpoint that is also subscribed to a topic, then you must also unsubscribe the endpoint from the topic.

# Required Parameters
- `EndpointArn`: EndpointArn of endpoint to delete.

"""

delete_endpoint(EndpointArn; aws_config::AWSConfig=global_aws_config()) = sns("DeleteEndpoint", Dict{String, Any}("EndpointArn"=>EndpointArn); aws_config=aws_config)
delete_endpoint(EndpointArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = sns("DeleteEndpoint", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("EndpointArn"=>EndpointArn), args)); aws_config=aws_config)

"""
    DeletePlatformApplication()

Deletes a platform application object for one of the supported push notification services, such as APNS and GCM (Firebase Cloud Messaging). For more information, see Using Amazon SNS Mobile Push Notifications.

# Required Parameters
- `PlatformApplicationArn`: PlatformApplicationArn of platform application object to delete.

"""

delete_platform_application(PlatformApplicationArn; aws_config::AWSConfig=global_aws_config()) = sns("DeletePlatformApplication", Dict{String, Any}("PlatformApplicationArn"=>PlatformApplicationArn); aws_config=aws_config)
delete_platform_application(PlatformApplicationArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = sns("DeletePlatformApplication", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("PlatformApplicationArn"=>PlatformApplicationArn), args)); aws_config=aws_config)

"""
    DeleteTopic()

Deletes a topic and all its subscriptions. Deleting a topic might prevent some messages previously sent to the topic from being delivered to subscribers. This action is idempotent, so deleting a topic that does not exist does not result in an error.

# Required Parameters
- `TopicArn`: The ARN of the topic you want to delete.

"""

delete_topic(TopicArn; aws_config::AWSConfig=global_aws_config()) = sns("DeleteTopic", Dict{String, Any}("TopicArn"=>TopicArn); aws_config=aws_config)
delete_topic(TopicArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = sns("DeleteTopic", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("TopicArn"=>TopicArn), args)); aws_config=aws_config)

"""
    GetEndpointAttributes()

Retrieves the endpoint attributes for a device on one of the supported push notification services, such as GCM (Firebase Cloud Messaging) and APNS. For more information, see Using Amazon SNS Mobile Push Notifications.

# Required Parameters
- `EndpointArn`: EndpointArn for GetEndpointAttributes input.

"""

get_endpoint_attributes(EndpointArn; aws_config::AWSConfig=global_aws_config()) = sns("GetEndpointAttributes", Dict{String, Any}("EndpointArn"=>EndpointArn); aws_config=aws_config)
get_endpoint_attributes(EndpointArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = sns("GetEndpointAttributes", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("EndpointArn"=>EndpointArn), args)); aws_config=aws_config)

"""
    GetPlatformApplicationAttributes()

Retrieves the attributes of the platform application object for the supported push notification services, such as APNS and GCM (Firebase Cloud Messaging). For more information, see Using Amazon SNS Mobile Push Notifications.

# Required Parameters
- `PlatformApplicationArn`: PlatformApplicationArn for GetPlatformApplicationAttributesInput.

"""

get_platform_application_attributes(PlatformApplicationArn; aws_config::AWSConfig=global_aws_config()) = sns("GetPlatformApplicationAttributes", Dict{String, Any}("PlatformApplicationArn"=>PlatformApplicationArn); aws_config=aws_config)
get_platform_application_attributes(PlatformApplicationArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = sns("GetPlatformApplicationAttributes", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("PlatformApplicationArn"=>PlatformApplicationArn), args)); aws_config=aws_config)

"""
    GetSMSAttributes()

Returns the settings for sending SMS messages from your account. These settings are set with the SetSMSAttributes action.

# Optional Parameters
- `attributes`: A list of the individual attribute names, such as MonthlySpendLimit, for which you want values. For all attribute names, see SetSMSAttributes. If you don't use this parameter, Amazon SNS returns all SMS attributes.
"""

get_smsattributes(; aws_config::AWSConfig=global_aws_config()) = sns("GetSMSAttributes"; aws_config=aws_config)
get_smsattributes(args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = sns("GetSMSAttributes", args; aws_config=aws_config)

"""
    GetSubscriptionAttributes()

Returns all of the properties of a subscription.

# Required Parameters
- `SubscriptionArn`: The ARN of the subscription whose properties you want to get.

"""

get_subscription_attributes(SubscriptionArn; aws_config::AWSConfig=global_aws_config()) = sns("GetSubscriptionAttributes", Dict{String, Any}("SubscriptionArn"=>SubscriptionArn); aws_config=aws_config)
get_subscription_attributes(SubscriptionArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = sns("GetSubscriptionAttributes", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("SubscriptionArn"=>SubscriptionArn), args)); aws_config=aws_config)

"""
    GetTopicAttributes()

Returns all of the properties of a topic. Topic properties returned might differ based on the authorization of the user.

# Required Parameters
- `TopicArn`: The ARN of the topic whose properties you want to get.

"""

get_topic_attributes(TopicArn; aws_config::AWSConfig=global_aws_config()) = sns("GetTopicAttributes", Dict{String, Any}("TopicArn"=>TopicArn); aws_config=aws_config)
get_topic_attributes(TopicArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = sns("GetTopicAttributes", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("TopicArn"=>TopicArn), args)); aws_config=aws_config)

"""
    ListEndpointsByPlatformApplication()

Lists the endpoints and endpoint attributes for devices in a supported push notification service, such as GCM (Firebase Cloud Messaging) and APNS. The results for ListEndpointsByPlatformApplication are paginated and return a limited list of endpoints, up to 100. If additional records are available after the first page results, then a NextToken string will be returned. To receive the next page, you call ListEndpointsByPlatformApplication again using the NextToken string received from the previous call. When there are no more records to return, NextToken will be null. For more information, see Using Amazon SNS Mobile Push Notifications.  This action is throttled at 30 transactions per second (TPS).

# Required Parameters
- `PlatformApplicationArn`: PlatformApplicationArn for ListEndpointsByPlatformApplicationInput action.

# Optional Parameters
- `NextToken`: NextToken string is used when calling ListEndpointsByPlatformApplication action to retrieve additional records that are available after the first page results.
"""

list_endpoints_by_platform_application(PlatformApplicationArn; aws_config::AWSConfig=global_aws_config()) = sns("ListEndpointsByPlatformApplication", Dict{String, Any}("PlatformApplicationArn"=>PlatformApplicationArn); aws_config=aws_config)
list_endpoints_by_platform_application(PlatformApplicationArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = sns("ListEndpointsByPlatformApplication", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("PlatformApplicationArn"=>PlatformApplicationArn), args)); aws_config=aws_config)

"""
    ListPhoneNumbersOptedOut()

Returns a list of phone numbers that are opted out, meaning you cannot send SMS messages to them. The results for ListPhoneNumbersOptedOut are paginated, and each page returns up to 100 phone numbers. If additional phone numbers are available after the first page of results, then a NextToken string will be returned. To receive the next page, you call ListPhoneNumbersOptedOut again using the NextToken string received from the previous call. When there are no more records to return, NextToken will be null.

# Optional Parameters
- `nextToken`: A NextToken string is used when you call the ListPhoneNumbersOptedOut action to retrieve additional records that are available after the first page of results.
"""

list_phone_numbers_opted_out(; aws_config::AWSConfig=global_aws_config()) = sns("ListPhoneNumbersOptedOut"; aws_config=aws_config)
list_phone_numbers_opted_out(args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = sns("ListPhoneNumbersOptedOut", args; aws_config=aws_config)

"""
    ListPlatformApplications()

Lists the platform application objects for the supported push notification services, such as APNS and GCM (Firebase Cloud Messaging). The results for ListPlatformApplications are paginated and return a limited list of applications, up to 100. If additional records are available after the first page results, then a NextToken string will be returned. To receive the next page, you call ListPlatformApplications using the NextToken string received from the previous call. When there are no more records to return, NextToken will be null. For more information, see Using Amazon SNS Mobile Push Notifications.  This action is throttled at 15 transactions per second (TPS).

# Optional Parameters
- `NextToken`: NextToken string is used when calling ListPlatformApplications action to retrieve additional records that are available after the first page results.
"""

list_platform_applications(; aws_config::AWSConfig=global_aws_config()) = sns("ListPlatformApplications"; aws_config=aws_config)
list_platform_applications(args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = sns("ListPlatformApplications", args; aws_config=aws_config)

"""
    ListSubscriptions()

Returns a list of the requester's subscriptions. Each call returns a limited list of subscriptions, up to 100. If there are more subscriptions, a NextToken is also returned. Use the NextToken parameter in a new ListSubscriptions call to get further results. This action is throttled at 30 transactions per second (TPS).

# Optional Parameters
- `NextToken`: Token returned by the previous ListSubscriptions request.
"""

list_subscriptions(; aws_config::AWSConfig=global_aws_config()) = sns("ListSubscriptions"; aws_config=aws_config)
list_subscriptions(args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = sns("ListSubscriptions", args; aws_config=aws_config)

"""
    ListSubscriptionsByTopic()

Returns a list of the subscriptions to a specific topic. Each call returns a limited list of subscriptions, up to 100. If there are more subscriptions, a NextToken is also returned. Use the NextToken parameter in a new ListSubscriptionsByTopic call to get further results. This action is throttled at 30 transactions per second (TPS).

# Required Parameters
- `TopicArn`: The ARN of the topic for which you wish to find subscriptions.

# Optional Parameters
- `NextToken`: Token returned by the previous ListSubscriptionsByTopic request.
"""

list_subscriptions_by_topic(TopicArn; aws_config::AWSConfig=global_aws_config()) = sns("ListSubscriptionsByTopic", Dict{String, Any}("TopicArn"=>TopicArn); aws_config=aws_config)
list_subscriptions_by_topic(TopicArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = sns("ListSubscriptionsByTopic", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("TopicArn"=>TopicArn), args)); aws_config=aws_config)

"""
    ListTagsForResource()

List all tags added to the specified Amazon SNS topic. For an overview, see Amazon SNS Tags in the Amazon Simple Notification Service Developer Guide.

# Required Parameters
- `ResourceArn`: The ARN of the topic for which to list tags.

"""

list_tags_for_resource(ResourceArn; aws_config::AWSConfig=global_aws_config()) = sns("ListTagsForResource", Dict{String, Any}("ResourceArn"=>ResourceArn); aws_config=aws_config)
list_tags_for_resource(ResourceArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = sns("ListTagsForResource", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ResourceArn"=>ResourceArn), args)); aws_config=aws_config)

"""
    ListTopics()

Returns a list of the requester's topics. Each call returns a limited list of topics, up to 100. If there are more topics, a NextToken is also returned. Use the NextToken parameter in a new ListTopics call to get further results. This action is throttled at 30 transactions per second (TPS).

# Optional Parameters
- `NextToken`: Token returned by the previous ListTopics request.
"""

list_topics(; aws_config::AWSConfig=global_aws_config()) = sns("ListTopics"; aws_config=aws_config)
list_topics(args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = sns("ListTopics", args; aws_config=aws_config)

"""
    OptInPhoneNumber()

Use this request to opt in a phone number that is opted out, which enables you to resume sending SMS messages to the number. You can opt in a phone number only once every 30 days.

# Required Parameters
- `phoneNumber`: The phone number to opt in.

"""

opt_in_phone_number(phoneNumber; aws_config::AWSConfig=global_aws_config()) = sns("OptInPhoneNumber", Dict{String, Any}("phoneNumber"=>phoneNumber); aws_config=aws_config)
opt_in_phone_number(phoneNumber, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = sns("OptInPhoneNumber", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("phoneNumber"=>phoneNumber), args)); aws_config=aws_config)

"""
    Publish()

Sends a message to an Amazon SNS topic, a text message (SMS message) directly to a phone number, or a message to a mobile platform endpoint (when you specify the TargetArn). If you send a message to a topic, Amazon SNS delivers the message to each endpoint that is subscribed to the topic. The format of the message depends on the notification protocol for each subscribed endpoint. When a messageId is returned, the message has been saved and Amazon SNS will attempt to deliver it shortly. To use the Publish action for sending a message to a mobile endpoint, such as an app on a Kindle device or mobile phone, you must specify the EndpointArn for the TargetArn parameter. The EndpointArn is returned when making a call with the CreatePlatformEndpoint action.  For more information about formatting messages, see Send Custom Platform-Specific Payloads in Messages to Mobile Devices.   You can publish messages only to topics and endpoints in the same AWS Region.

# Required Parameters
- `Message`: The message you want to send. If you are publishing to a topic and you want to send the same message to all transport protocols, include the text of the message as a String value. If you want to send different messages for each transport protocol, set the value of the MessageStructure parameter to json and use a JSON object for the Message parameter.   Constraints:   With the exception of SMS, messages must be UTF-8 encoded strings and at most 256 KB in size (262,144 bytes, not 262,144 characters).   For SMS, each message can contain up to 140 characters. This character limit depends on the encoding schema. For example, an SMS message can contain 160 GSM characters, 140 ASCII characters, or 70 UCS-2 characters. If you publish a message that exceeds this size limit, Amazon SNS sends the message as multiple messages, each fitting within the size limit. Messages aren't truncated mid-word but are cut off at whole-word boundaries. The total size limit for a single SMS Publish action is 1,600 characters.   JSON-specific constraints:   Keys in the JSON object that correspond to supported transport protocols must have simple JSON string values.   The values will be parsed (unescaped) before they are used in outgoing messages.   Outbound notifications are JSON encoded (meaning that the characters will be reescaped for sending).   Values have a minimum length of 0 (the empty string, \"\", is allowed).   Values have a maximum length bounded by the overall message size (so, including multiple protocols may limit message sizes).   Non-string values will cause the key to be ignored.   Keys that do not correspond to supported transport protocols are ignored.   Duplicate keys are not allowed.   Failure to parse or validate any key or value in the message will cause the Publish call to return an error (no partial delivery).

# Optional Parameters
- `MessageAttributes`: Message attributes for Publish action.
- `MessageStructure`: Set MessageStructure to json if you want to send a different message for each protocol. For example, using one publish action, you can send a short message to your SMS subscribers and a longer message to your email subscribers. If you set MessageStructure to json, the value of the Message parameter must:    be a syntactically valid JSON object; and   contain at least a top-level JSON key of \"default\" with a value that is a string.   You can define other top-level keys that define the message you want to send to a specific transport protocol (e.g., \"http\"). Valid value: json
- `PhoneNumber`: The phone number to which you want to deliver an SMS message. Use E.164 format. If you don't specify a value for the PhoneNumber parameter, you must specify a value for the TargetArn or TopicArn parameters.
- `Subject`: Optional parameter to be used as the \"Subject\" line when the message is delivered to email endpoints. This field will also be included, if present, in the standard JSON messages delivered to other endpoints. Constraints: Subjects must be ASCII text that begins with a letter, number, or punctuation mark; must not include line breaks or control characters; and must be less than 100 characters long.
- `TargetArn`: If you don't specify a value for the TargetArn parameter, you must specify a value for the PhoneNumber or TopicArn parameters.
- `TopicArn`: The topic you want to publish to. If you don't specify a value for the TopicArn parameter, you must specify a value for the PhoneNumber or TargetArn parameters.
"""

publish(Message; aws_config::AWSConfig=global_aws_config()) = sns("Publish", Dict{String, Any}("Message"=>Message); aws_config=aws_config)
publish(Message, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = sns("Publish", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Message"=>Message), args)); aws_config=aws_config)

"""
    RemovePermission()

Removes a statement from a topic's access control policy.

# Required Parameters
- `Label`: The unique label of the statement you want to remove.
- `TopicArn`: The ARN of the topic whose access control policy you wish to modify.

"""

remove_permission(Label, TopicArn; aws_config::AWSConfig=global_aws_config()) = sns("RemovePermission", Dict{String, Any}("Label"=>Label, "TopicArn"=>TopicArn); aws_config=aws_config)
remove_permission(Label, TopicArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = sns("RemovePermission", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Label"=>Label, "TopicArn"=>TopicArn), args)); aws_config=aws_config)

"""
    SetEndpointAttributes()

Sets the attributes for an endpoint for a device on one of the supported push notification services, such as GCM (Firebase Cloud Messaging) and APNS. For more information, see Using Amazon SNS Mobile Push Notifications.

# Required Parameters
- `Attributes`: A map of the endpoint attributes. Attributes in this map include the following:    CustomUserData – arbitrary user data to associate with the endpoint. Amazon SNS does not use this data. The data must be in UTF-8 format and less than 2KB.    Enabled – flag that enables/disables delivery to the endpoint. Amazon SNS will set this to false when a notification service indicates to Amazon SNS that the endpoint is invalid. Users can set it back to true, typically after updating Token.    Token – device token, also referred to as a registration id, for an app and mobile device. This is returned from the notification service when an app and mobile device are registered with the notification service.
- `EndpointArn`: EndpointArn used for SetEndpointAttributes action.

"""

set_endpoint_attributes(Attributes, EndpointArn; aws_config::AWSConfig=global_aws_config()) = sns("SetEndpointAttributes", Dict{String, Any}("Attributes"=>Attributes, "EndpointArn"=>EndpointArn); aws_config=aws_config)
set_endpoint_attributes(Attributes, EndpointArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = sns("SetEndpointAttributes", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Attributes"=>Attributes, "EndpointArn"=>EndpointArn), args)); aws_config=aws_config)

"""
    SetPlatformApplicationAttributes()

Sets the attributes of the platform application object for the supported push notification services, such as APNS and GCM (Firebase Cloud Messaging). For more information, see Using Amazon SNS Mobile Push Notifications. For information on configuring attributes for message delivery status, see Using Amazon SNS Application Attributes for Message Delivery Status.

# Required Parameters
- `Attributes`: A map of the platform application attributes. Attributes in this map include the following:    PlatformCredential – The credential received from the notification service. For APNS and APNS_SANDBOX, PlatformCredential is private key. For GCM (Firebase Cloud Messaging), PlatformCredential is API key. For ADM, PlatformCredential is client secret.    PlatformPrincipal – The principal received from the notification service. For APNS and APNS_SANDBOX, PlatformPrincipal is SSL certificate. For GCM (Firebase Cloud Messaging), there is no PlatformPrincipal. For ADM, PlatformPrincipal is client id.    EventEndpointCreated – Topic ARN to which EndpointCreated event notifications are sent.    EventEndpointDeleted – Topic ARN to which EndpointDeleted event notifications are sent.    EventEndpointUpdated – Topic ARN to which EndpointUpdate event notifications are sent.    EventDeliveryFailure – Topic ARN to which DeliveryFailure event notifications are sent upon Direct Publish delivery failure (permanent) to one of the application's endpoints.    SuccessFeedbackRoleArn – IAM role ARN used to give Amazon SNS write access to use CloudWatch Logs on your behalf.    FailureFeedbackRoleArn – IAM role ARN used to give Amazon SNS write access to use CloudWatch Logs on your behalf.    SuccessFeedbackSampleRate – Sample rate percentage (0-100) of successfully delivered messages.
- `PlatformApplicationArn`: PlatformApplicationArn for SetPlatformApplicationAttributes action.

"""

set_platform_application_attributes(Attributes, PlatformApplicationArn; aws_config::AWSConfig=global_aws_config()) = sns("SetPlatformApplicationAttributes", Dict{String, Any}("Attributes"=>Attributes, "PlatformApplicationArn"=>PlatformApplicationArn); aws_config=aws_config)
set_platform_application_attributes(Attributes, PlatformApplicationArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = sns("SetPlatformApplicationAttributes", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Attributes"=>Attributes, "PlatformApplicationArn"=>PlatformApplicationArn), args)); aws_config=aws_config)

"""
    SetSMSAttributes()

Use this request to set the default settings for sending SMS messages and receiving daily SMS usage reports. You can override some of these settings for a single message when you use the Publish action with the MessageAttributes.entry.N parameter. For more information, see Sending an SMS Message in the Amazon SNS Developer Guide.

# Required Parameters
- `attributes`: The default settings for sending SMS messages from your account. You can set values for the following attribute names:  MonthlySpendLimit – The maximum amount in USD that you are willing to spend each month to send SMS messages. When Amazon SNS determines that sending an SMS message would incur a cost that exceeds this limit, it stops sending SMS messages within minutes.  Amazon SNS stops sending SMS messages within minutes of the limit being crossed. During that interval, if you continue to send SMS messages, you will incur costs that exceed your limit.  By default, the spend limit is set to the maximum allowed by Amazon SNS. If you want to raise the limit, submit an SNS Limit Increase case. For New limit value, enter your desired monthly spend limit. In the Use Case Description field, explain that you are requesting an SMS monthly spend limit increase.  DeliveryStatusIAMRole – The ARN of the IAM role that allows Amazon SNS to write logs about SMS deliveries in CloudWatch Logs. For each SMS message that you send, Amazon SNS writes a log that includes the message price, the success or failure status, the reason for failure (if the message failed), the message dwell time, and other information.  DeliveryStatusSuccessSamplingRate – The percentage of successful SMS deliveries for which Amazon SNS will write logs in CloudWatch Logs. The value can be an integer from 0 - 100. For example, to write logs only for failed deliveries, set this value to 0. To write logs for 10% of your successful deliveries, set it to 10.  DefaultSenderID – A string, such as your business brand, that is displayed as the sender on the receiving device. Support for sender IDs varies by country. The sender ID can be 1 - 11 alphanumeric characters, and it must contain at least one letter.  DefaultSMSType – The type of SMS message that you will send by default. You can assign the following values:    Promotional – (Default) Noncritical messages, such as marketing messages. Amazon SNS optimizes the message delivery to incur the lowest cost.    Transactional – Critical messages that support customer transactions, such as one-time passcodes for multi-factor authentication. Amazon SNS optimizes the message delivery to achieve the highest reliability.    UsageReportS3Bucket – The name of the Amazon S3 bucket to receive daily SMS usage reports from Amazon SNS. Each day, Amazon SNS will deliver a usage report as a CSV file to the bucket. The report includes the following information for each SMS message that was successfully delivered by your account:   Time that the message was published (in UTC)   Message ID   Destination phone number   Message type   Delivery status   Message price (in USD)   Part number (a message is split into multiple parts if it is too long for a single message)   Total number of parts   To receive the report, the bucket must have a policy that allows the Amazon SNS service principle to perform the s3:PutObject and s3:GetBucketLocation actions. For an example bucket policy and usage report, see Monitoring SMS Activity in the Amazon SNS Developer Guide.

"""

set_smsattributes(attributes; aws_config::AWSConfig=global_aws_config()) = sns("SetSMSAttributes", Dict{String, Any}("attributes"=>attributes); aws_config=aws_config)
set_smsattributes(attributes, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = sns("SetSMSAttributes", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("attributes"=>attributes), args)); aws_config=aws_config)

"""
    SetSubscriptionAttributes()

Allows a subscription owner to set an attribute of the subscription to a new value.

# Required Parameters
- `AttributeName`: A map of attributes with their corresponding values. The following lists the names, descriptions, and values of the special request parameters that the SetTopicAttributes action uses:    DeliveryPolicy – The policy that defines how Amazon SNS retries failed deliveries to HTTP/S endpoints.    FilterPolicy – The simple JSON object that lets your subscriber receive only a subset of messages, rather than receiving every message published to the topic.    RawMessageDelivery – When set to true, enables raw message delivery to Amazon SQS or HTTP/S endpoints. This eliminates the need for the endpoints to process JSON formatting, which is otherwise created for Amazon SNS metadata.    RedrivePolicy – When specified, sends undeliverable messages to the specified Amazon SQS dead-letter queue. Messages that can't be delivered due to client errors (for example, when the subscribed endpoint is unreachable) or server errors (for example, when the service that powers the subscribed endpoint becomes unavailable) are held in the dead-letter queue for further analysis or reprocessing.
- `SubscriptionArn`: The ARN of the subscription to modify.

# Optional Parameters
- `AttributeValue`: The new value for the attribute in JSON format.
"""

set_subscription_attributes(AttributeName, SubscriptionArn; aws_config::AWSConfig=global_aws_config()) = sns("SetSubscriptionAttributes", Dict{String, Any}("AttributeName"=>AttributeName, "SubscriptionArn"=>SubscriptionArn); aws_config=aws_config)
set_subscription_attributes(AttributeName, SubscriptionArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = sns("SetSubscriptionAttributes", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("AttributeName"=>AttributeName, "SubscriptionArn"=>SubscriptionArn), args)); aws_config=aws_config)

"""
    SetTopicAttributes()

Allows a topic owner to set an attribute of the topic to a new value.

# Required Parameters
- `AttributeName`: A map of attributes with their corresponding values. The following lists the names, descriptions, and values of the special request parameters that the SetTopicAttributes action uses:    DeliveryPolicy – The policy that defines how Amazon SNS retries failed deliveries to HTTP/S endpoints.    DisplayName – The display name to use for a topic with SMS subscriptions.    Policy – The policy that defines who can access your topic. By default, only the topic owner can publish or subscribe to the topic.   The following attribute applies only to server-side-encryption:    KmsMasterKeyId - The ID of an AWS-managed customer master key (CMK) for Amazon SNS or a custom CMK. For more information, see Key Terms. For more examples, see KeyId in the AWS Key Management Service API Reference.
- `TopicArn`: The ARN of the topic to modify.

# Optional Parameters
- `AttributeValue`: The new value for the attribute.
"""

set_topic_attributes(AttributeName, TopicArn; aws_config::AWSConfig=global_aws_config()) = sns("SetTopicAttributes", Dict{String, Any}("AttributeName"=>AttributeName, "TopicArn"=>TopicArn); aws_config=aws_config)
set_topic_attributes(AttributeName, TopicArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = sns("SetTopicAttributes", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("AttributeName"=>AttributeName, "TopicArn"=>TopicArn), args)); aws_config=aws_config)

"""
    Subscribe()

Subscribes an endpoint to an Amazon SNS topic. If the endpoint type is HTTP/S or email, or if the endpoint and the topic are not in the same AWS account, the endpoint owner must the ConfirmSubscription action to confirm the subscription. You call the ConfirmSubscription action with the token from the subscription response. Confirmation tokens are valid for three days. This action is throttled at 100 transactions per second (TPS).

# Required Parameters
- `Protocol`: The protocol you want to use. Supported protocols include:    http – delivery of JSON-encoded message via HTTP POST    https – delivery of JSON-encoded message via HTTPS POST    email – delivery of message via SMTP    email-json – delivery of JSON-encoded message via SMTP    sms – delivery of message via SMS    sqs – delivery of JSON-encoded message to an Amazon SQS queue    application – delivery of JSON-encoded message to an EndpointArn for a mobile app and device.    lambda – delivery of JSON-encoded message to an Amazon Lambda function.
- `TopicArn`: The ARN of the topic you want to subscribe to.

# Optional Parameters
- `Attributes`: A map of attributes with their corresponding values. The following lists the names, descriptions, and values of the special request parameters that the SetTopicAttributes action uses:    DeliveryPolicy – The policy that defines how Amazon SNS retries failed deliveries to HTTP/S endpoints.    FilterPolicy – The simple JSON object that lets your subscriber receive only a subset of messages, rather than receiving every message published to the topic.    RawMessageDelivery – When set to true, enables raw message delivery to Amazon SQS or HTTP/S endpoints. This eliminates the need for the endpoints to process JSON formatting, which is otherwise created for Amazon SNS metadata.    RedrivePolicy – When specified, sends undeliverable messages to the specified Amazon SQS dead-letter queue. Messages that can't be delivered due to client errors (for example, when the subscribed endpoint is unreachable) or server errors (for example, when the service that powers the subscribed endpoint becomes unavailable) are held in the dead-letter queue for further analysis or reprocessing.
- `Endpoint`: The endpoint that you want to receive notifications. Endpoints vary by protocol:   For the http protocol, the (public) endpoint is a URL beginning with http://    For the https protocol, the (public) endpoint is a URL beginning with https://    For the email protocol, the endpoint is an email address   For the email-json protocol, the endpoint is an email address   For the sms protocol, the endpoint is a phone number of an SMS-enabled device   For the sqs protocol, the endpoint is the ARN of an Amazon SQS queue   For the application protocol, the endpoint is the EndpointArn of a mobile app and device.   For the lambda protocol, the endpoint is the ARN of an Amazon Lambda function.
- `ReturnSubscriptionArn`: Sets whether the response from the Subscribe request includes the subscription ARN, even if the subscription is not yet confirmed. If you set this parameter to true, the response includes the ARN in all cases, even if the subscription is not yet confirmed. In addition to the ARN for confirmed subscriptions, the response also includes the pending subscription ARN value for subscriptions that aren't yet confirmed. A subscription becomes confirmed when the subscriber calls the ConfirmSubscription action with a confirmation token.  The default value is false.
"""

subscribe(Protocol, TopicArn; aws_config::AWSConfig=global_aws_config()) = sns("Subscribe", Dict{String, Any}("Protocol"=>Protocol, "TopicArn"=>TopicArn); aws_config=aws_config)
subscribe(Protocol, TopicArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = sns("Subscribe", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Protocol"=>Protocol, "TopicArn"=>TopicArn), args)); aws_config=aws_config)

"""
    TagResource()

Add tags to the specified Amazon SNS topic. For an overview, see Amazon SNS Tags in the Amazon SNS Developer Guide. When you use topic tags, keep the following guidelines in mind:   Adding more than 50 tags to a topic isn't recommended.   Tags don't have any semantic meaning. Amazon SNS interprets tags as character strings.   Tags are case-sensitive.   A new tag with a key identical to that of an existing tag overwrites the existing tag.   Tagging actions are limited to 10 TPS per AWS account, per AWS region. If your application requires a higher throughput, file a technical support request.

# Required Parameters
- `ResourceArn`: The ARN of the topic to which to add tags.
- `Tags`: The tags to be added to the specified topic. A tag consists of a required key and an optional value.

"""

tag_resource(ResourceArn, Tags; aws_config::AWSConfig=global_aws_config()) = sns("TagResource", Dict{String, Any}("ResourceArn"=>ResourceArn, "Tags"=>Tags); aws_config=aws_config)
tag_resource(ResourceArn, Tags, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = sns("TagResource", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ResourceArn"=>ResourceArn, "Tags"=>Tags), args)); aws_config=aws_config)

"""
    Unsubscribe()

Deletes a subscription. If the subscription requires authentication for deletion, only the owner of the subscription or the topic's owner can unsubscribe, and an AWS signature is required. If the Unsubscribe call does not require authentication and the requester is not the subscription owner, a final cancellation message is delivered to the endpoint, so that the endpoint owner can easily resubscribe to the topic if the Unsubscribe request was unintended. This action is throttled at 100 transactions per second (TPS).

# Required Parameters
- `SubscriptionArn`: The ARN of the subscription to be deleted.

"""

unsubscribe(SubscriptionArn; aws_config::AWSConfig=global_aws_config()) = sns("Unsubscribe", Dict{String, Any}("SubscriptionArn"=>SubscriptionArn); aws_config=aws_config)
unsubscribe(SubscriptionArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = sns("Unsubscribe", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("SubscriptionArn"=>SubscriptionArn), args)); aws_config=aws_config)

"""
    UntagResource()

Remove tags from the specified Amazon SNS topic. For an overview, see Amazon SNS Tags in the Amazon SNS Developer Guide.

# Required Parameters
- `ResourceArn`: The ARN of the topic from which to remove tags.
- `TagKeys`: The list of tag keys to remove from the specified topic.

"""

untag_resource(ResourceArn, TagKeys; aws_config::AWSConfig=global_aws_config()) = sns("UntagResource", Dict{String, Any}("ResourceArn"=>ResourceArn, "TagKeys"=>TagKeys); aws_config=aws_config)
untag_resource(ResourceArn, TagKeys, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = sns("UntagResource", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ResourceArn"=>ResourceArn, "TagKeys"=>TagKeys), args)); aws_config=aws_config)


text:
## Resampling methods for SMC algorithms ##
export pf_resample!
export pf_residual_resample!, pf_multinomial_resample!, pf_stratified_resample!

using Distributions: rand!

"""
    pf_resample!(state::ParticleFilterState, method=:multinomial; kwargs...)

Resamples particles in the filter, stochastically pruning low-weight particles.
The resampling method can optionally be specified: `:multinomial` (default),
`:residual`, or `:stratified`. See [1] for a survey of resampling methods
and their variance properties. A `priority_fn` can also be specified as
keyword argument, which maps log particle weights to custom log priority scores
for the purpose of resampling (e.g. `w -> w/2` for less aggressive pruning).

[1] R. Douc and O. Cappé, "Comparison of resampling schemes
for particle filtering," in ISPA 2005. Proceedings of the 4th International
Symposium on Image and Signal Processing and Analysis, 2005., 2005, pp. 64–69.
"""
function pf_resample!(state::ParticleFilterState,
                      method::Symbol=:multinomial; kwargs...)
    if method == :multinomial
        return pf_multinomial_resample!(state; kwargs...)
    elseif method == :residual
        return pf_residual_resample!(state; kwargs...)
    elseif method == :stratified
        return pf_stratified_resample!(state; kwargs...)
    else
        error("Resampling method $method not recognized.")
    end
end

"""
    pf_multnomial_resample!(state::ParticleFilterState; kwargs...)

Performs multinomial resampling (i.e. simple random resampling) of the
particles in the filter. Each trace (i.e. particle) is resampled with
probability proportional to its weight.

A `priority_fn` can be specified as keyword argument, which maps log particle
weights to custom log priority scores for the purpose of resampling
(e.g. `w -> w/2` for less aggressive pruning).
"""
function pf_multinomial_resample!(state::ParticleFilterState;
                                  priority_fn=nothing)
    # Update estimate of log marginal likelihood
    n_particles = length(state.traces)
    state.log_ml_est += logsumexp(state.log_weights) - log(n_particles)
    # Compute priority scores if priority function is provided
    log_priorities = priority_fn == nothing ?
        state.log_weights : priority_fn.(state.log_weights)
    # Resample new traces according to current normalized weights
    rand!(Categorical(exp.(lognorm(log_priorities))), state.parents)
    state.new_traces[1:end] = state.traces[state.parents]
    # Reweight particles
    if priority_fn == nothing
        state.log_weights .= 0.0
    else
        ws = state.log_weights[state.parents] .- log_priorities[state.parents]
        state.log_weights = ws .+ (log(n_particles) - logsumexp(ws))
    end
    update_refs!(state)
    return state
end

"""
    pf_residual_resample!(state::ParticleFilterState; kwargs...)

Performs residual resampling of the particles in the filter, which reduces
variance relative to multinomial sampling. For each particle with
normalized weight ``w_i``, ``⌊n w_i⌋`` copies are resampled, where ``n`` is the
total number of particles. The remainder are sampled with probability
proportional to ``n w_i - ⌊n w_i⌋`` for each particle ``i``.

A `priority_fn` can be specified as keyword argument, which maps log particle
weights to custom log priority scores for the purpose of resampling
(e.g. `w -> w/2` for less aggressive pruning).
"""
function pf_residual_resample!(state::ParticleFilterState;
                               priority_fn=nothing)
    # Update estimate of log marginal likelihood
    n_particles = length(state.traces)
    state.log_ml_est += logsumexp(state.log_weights) - log(n_particles)
    # Compute priority scores if priority function is provided
    log_priorities = priority_fn == nothing ?
        state.log_weights : priority_fn.(state.log_weights)
    # Deterministically copy previous particles according to their weights
    n_resampled = 0
    weights = exp.(lognorm(log_priorities))
    for (i, w) in enumerate(weights)
        n_copies = floor(Int, n_particles * w)
        if n_copies == 0 continue end
        state.parents[n_resampled+1:n_resampled+n_copies] .= i
        for j in 1:n_copies
            state.new_traces[n_resampled+j] = state.traces[i]
        end
        n_resampled += n_copies
    end
    # Sample remainder according to residual weights
    if n_resampled < n_particles
        r_weights = n_particles .* weights .- floor.(n_particles .* weights)
        r_weights = r_weights / sum(r_weights)
        rand!(Categorical(r_weights), state.parents[n_resampled+1:end])
        state.new_traces[n_resampled+1:end] =
            state.traces[state.parents[n_resampled+1:end]]
    end
    # Reweight particles
    if priority_fn == nothing
        state.log_weights .= 0.0
    else
        ws = state.log_weights[state.parents] .- log_priorities[state.parents]
        state.log_weights = ws .+ (log(n_particles) - logsumexp(ws))
    end
    update_refs!(state)
    return state
end

"""
    pf_stratified_resample!(state::ParticleFilterState; kwargs...)

Performs stratified resampling of the particles in the filter, which reduces
variance relative to multinomial sampling. First, uniform random samples
``u_1, ..., u_n`` are drawn within the strata ``[0, 1/n)``, ..., ``[n-1/n, 1)``,
where ``n`` is the number of particles. Then, given the cumulative normalized
weights ``W_k = Σ_{j=1}^{k} w_j ``, sample the ``k``th particle for each ``u_i``
where ``W_{k-1} ≤ u_i < W_k``.

A `priority_fn` can be specified as keyword argument, which maps log particle
weights to custom log priority scores for the purpose of resampling
(e.g. `w -> w/2` for less aggressive pruning). The `sort_particles` keyword
argument controls whether particles are sorted by weight before stratification
(default: true).
"""
function pf_stratified_resample!(state::ParticleFilterState;
                                 priority_fn=nothing, sort_particles::Bool=true)
    # Update estimate of log marginal likelihood
    n_particles = length(state.traces)
    state.log_ml_est += logsumexp(state.log_weights) - log(n_particles)
    # Compute priority scores if priority function is provided
    log_priorities = priority_fn == nothing ?
        state.log_weights : priority_fn.(state.log_weights)
    weights = exp.(lognorm(log_priorities))
    # Optionally sort particles by weight before resampling
    order = sort_particles ?
        sortperm(log_priorities, rev=true) : collect(1:n_particles)
    # Sample particles within each weight stratum [i, i+1/n)
    i_old, weight_step, accum_weight = 0, 1/n_particles, 0.0
    for (i_new, lower) in enumerate(0.0:weight_step:1.0-weight_step)
        if lower + weight_step > accum_weight
            u = rand() * weight_step + lower
            while accum_weight < u
                accum_weight += weights[order[i_old+1]]
                i_old += 1
            end
        end
        state.parents[i_new] = order[i_old]
        state.new_traces[i_new] = state.traces[order[i_old]]
    end
    # Reweight particles
    if priority_fn == nothing
        state.log_weights .= 0.0
    else
        ws = state.log_weights[state.parents] .- log_priorities[state.parents]
        state.log_weights = ws .+ (log(n_particles) - logsumexp(ws))
    end
    update_refs!(state)
    return state
end

ext: jl


text:
"""When using distance geometry to generate geometries, lots of bad
distances get produced which messes up the resulting distributions.
Trim a series of bond length distribution files to a given frction of
the data.

This is a quick hack to trim those files. Not robust and will not
be needed when we have proper distributions"""

using ArgMacros
using CSV
using DataFrames
using LinearAlgebra

"""Very simplistic trimming of rhs and lhs based on the `counts` vector.
Args:
  distance: vector of distance values
  counts: vector of counts
  fraction: what fraction of data to retain
  output_fname: where to write the result
"""
function process_file_contents(distance::Vector{Float64},
                      counts::Vector{Int64},
                      fraction::Real,
                      output_fname::String)::Bool
  ntot = sum(counts)
  if ntot < 100
    @warn("Too few points $(ntot), skipping")
    return true
  end
  nkeep = round(Int, fraction * ntot)
  @info("N = $(ntot) fraction $fraction NKeep $(nkeep)")
  lhs = 1
  rhs = length(counts)
  removed = 0
  to_remove = ntot - nkeep
  while removed  < to_remove
    # If equal counts, make an arbitrary decision.
    if counts[lhs] <= counts[rhs]
      removed += counts[lhs]
      lhs += 1
    else
      removed += counts[rhs]
      rhs -= 1
    end
  end
  while counts[rhs] == 0
    rhs -= 1
  end
  while counts[lhs] == 0
    lhs += 1
  end
  x = distance[lhs:rhs]
  y = counts[lhs:rhs]
  to_write = DataFrame(distance=x, count=y)
  CSV.write(output_fname, to_write, writeheader=false)
  return true
end

function process_file(input_fname::String, output_fname::String,
                      fraction::Float64)::Bool
  if ! isfile(input_fname)
    @warn("Skipping $input_fname")
    return true
  end
  @info("Processing $input_fname")
  df = CSV.File(input_fname) |> DataFrame
  return process_file_contents(df[!, 1], df[!, 2], fraction, output_fname)
end

function main()
  @inlinearguments begin
    @argumentrequired String input_stem "-i" "--input_stem"
    @argumentrequired String output_stem "-o" "--output_stem"
    @argumentrequired Float64 fraction "-f" "--fraction"
  end

  bstart = 0
  bond_types = [0, 1, 2, 3]

  atomic_numbers = [1, 6, 7, 8, 9]
  for (t1, t2) in filter(x->x[1] <= x[2], collect(Iterators.product(ntuple(i->atomic_numbers, 2)...))[:])
    for btype in bstart:3
      input_fname = "$input_stem.$(t1).$(btype).$(t2)"
      output_fname = "$output_stem.$(t1).$(btype).$(t2)"
      process_file(input_fname, output_fname, fraction)
    end
  end
end

main()

max_stars_repo_name: IanAWatson/smu

max_issues_repo_name: IanAWatson/smu

max_forks_repo_name: IanAWatson/smu


text:
__precompile__()
module NoiseWaveform
include("pcfm.jl")
include("optimization.jl")
end


text:
# Autogenerated wrapper script for grep_jll for i686-linux-musl
export grep

using Libiconv_jll
JLLWrappers.@generate_wrapper_header("grep")
JLLWrappers.@declare_executable_product(grep)
function __init__()
    JLLWrappers.@generate_init_header(Libiconv_jll)
    JLLWrappers.@init_executable_product(
        grep,
        "bin/grep",
    )

    JLLWrappers.@generate_init_footer()
end  # __init__()


text:
using Printf

function play_mh_literal{T<:Integer}(ncur::T=3, ncar::T=1)
    ncar < ncur || throw(DomainError())
    curtains = shuffle(collect(1:ncur))
    cars = curtains[1:ncar]
    goats = curtains[(ncar+1):end]
    pick = rand(1:ncur)
    isstickwin = pick in cars
    deleteat!(curtains, findin(curtains, pick))
    if !isstickwin
        deleteat!(goats, findin(goats, pick))
    end
    if length(goats) > 0 # reveal goat
        deleteat!(curtains, findin(curtains, shuffle(goats)[1]))
    else # no goats, so reveal car
        deleteat!(curtains, rand(1:(ncur-1)))
    end
    pick = shuffle(curtains)[1]
    isswitchwin = pick in cars
    return (isstickwin, isswitchwin)
end

max_stars_repo_name: ethansaxenian/RosettaDecode

max_issues_repo_name: ethansaxenian/RosettaDecode

max_forks_repo_name: ethansaxenian/RosettaDecode


text:
#####
##### Momentum fluxes
#####

@inline momentum_flux_uu(i, j, k, grid, u)    = ℑxᶜᵃᵃ(i, j, k, grid, Ax_ψᵃᵃᶠ, u) * ℑxᶜᵃᵃ(i, j, k, grid, u)
@inline momentum_flux_uv(i, j, k, grid, u, v) = ℑxᶠᵃᵃ(i, j, k, grid, Ay_ψᵃᵃᶠ, v) * ℑyᵃᶠᵃ(i, j, k, grid, u)
@inline momentum_flux_uw(i, j, k, grid, u, w) = ℑxᶠᵃᵃ(i, j, k, grid, Az_ψᵃᵃᵃ, w) * ℑzᵃᵃᶠ(i, j, k, grid, u)

@inline momentum_flux_vu(i, j, k, grid, u, v) = ℑyᵃᶠᵃ(i, j, k, grid, Ax_ψᵃᵃᶠ, u) * ℑxᶠᵃᵃ(i, j, k, grid, v)
@inline momentum_flux_vv(i, j, k, grid, v)    = ℑyᵃᶜᵃ(i, j, k, grid, Ay_ψᵃᵃᶠ, v) * ℑyᵃᶜᵃ(i, j, k, grid, v)
@inline momentum_flux_vw(i, j, k, grid, v, w) = ℑyᵃᶠᵃ(i, j, k, grid, Az_ψᵃᵃᵃ, w) * ℑzᵃᵃᶠ(i, j, k, grid, v)

@inline momentum_flux_wu(i, j, k, grid, u, w) = ℑzᵃᵃᶠ(i, j, k, grid, Ax_ψᵃᵃᶠ, u) * ℑxᶠᵃᵃ(i, j, k, grid, w)
@inline momentum_flux_wv(i, j, k, grid, v, w) = ℑzᵃᵃᶠ(i, j, k, grid, Ay_ψᵃᵃᶠ, v) * ℑyᵃᶠᵃ(i, j, k, grid, w)
@inline momentum_flux_ww(i, j, k, grid, w)    = ℑzᵃᵃᶜ(i, j, k, grid, Az_ψᵃᵃᵃ, w) * ℑzᵃᵃᶜ(i, j, k, grid, w)

#####
##### Momentum advection operators
#####

"""
    u∇u(i, j, k, grid, U)

Calculate the advection of momentum in the x-direction U·∇u

    1/Vᵘ * [δxᶠᵃᵃ(ℑxᶜᵃᵃ(Ax * u) * ℑxᶜᵃᵃ(u)) + δy_fca(ℑxᶠᵃᵃ(Ay * v) * ℑyᵃᶠᵃ(u)) + δz_fac(ℑxᶠᵃᵃ(Az * w) * ℑzᵃᵃᶠ(u))]

which will end up at the location `fcc`.
"""
@inline function div_ũu(i, j, k, grid, U)
    return 1/Vᵃᵃᶜ(i, j, k, grid) * (δxᶠᵃᵃ(i, j, k, grid, momentum_flux_uu, U.u)    +
                                    δyᵃᶜᵃ(i, j, k, grid, momentum_flux_uv, U.u, U.v) +
                                    δzᵃᵃᶜ(i, j, k, grid, momentum_flux_uw, U.u, U.w))
end

"""
    u∇v(i, j, k, grid, U)

Calculates the advection of momentum in the y-direction U·∇v

    1/Vʸ * [δx_cfa(ℑyᵃᶠᵃ(Ax * u) * ℑxᶠᵃᵃ(v)) + δyᵃᶠᵃ(ℑyᵃᶜᵃ(Ay * v) * ℑyᵃᶜᵃ(v)) + δz_afc(ℑxᶠᵃᵃ(Az * w) * ℑzᵃᵃᶠ(w))]

which will end up at the location `cfc`.
"""
@inline function div_ũv(i, j, k, grid, U)
    return 1/Vᵃᵃᶜ(i, j, k, grid) * (δxᶜᵃᵃ(i, j, k, grid, momentum_flux_vu, U.u, U.v) +
                                    δyᵃᶠᵃ(i, j, k, grid, momentum_flux_vv, U.v)    +
                                    δzᵃᵃᶜ(i, j, k, grid, momentum_flux_vw, U.v, U.w))
end

"""
    u∇w(i, j, k, grid, U)

Calculates the advection of momentum in the z-direction U·∇w

    1/Vʷ * [δx_caf(ℑzᵃᵃᶠ(Ax * u) * ℑxᶠᵃᵃ(w)) + δy_acf(ℑzᵃᵃᶠ(Ay * v) * ℑyᵃᶠᵃ(w)) + δzᵃᵃᶠ(ℑzᵃᵃᶜ(Az * w) * ℑzᵃᵃᶜ(w))]

which will end up at the location `ccf`.
"""
@inline function div_ũw(i, j, k, grid, U)
    return 1/Vᵃᵃᶠ(i, j, k, grid) * (δxᶜᵃᵃ(i, j, k, grid, momentum_flux_wu, U.u, U.w) +
                                    δyᵃᶜᵃ(i, j, k, grid, momentum_flux_wv, U.v, U.w) +
                                    δzᵃᵃᶠ(i, j, k, grid, momentum_flux_ww, U.w))
end


text:
# This file is a part of JuliaFEM.
# License is MIT: see https://github.com/JuliaFEM/PkgTestSuite.jl/blob/master/LICENSE

using PkgTestSuite
using Base.Test

@testset "test checkheader" begin
    include("test_checkheader.jl")
end

@testset "test checktabs" begin
    include("test_checktabs.jl")
end

PkgTestSuite.init("PkgTestSuite")
PkgTestSuite.test("PkgTestSuite"; run_tests=false)
PkgTestSuite.deploy("PkgTestSuite")


text:
using LinearAlgebra
using StaticArrays

function position_in_world(x::Float64, y::Float64)
    target_width_px = 1123
    target_height_px = 791
    target_width_mm = 297
    target_height_mm = 210.025
    X = ((x + 0.5) / target_width_px) * target_width_mm - 0.5 * target_width_mm
    Y = ((y + 0.5) / target_height_px) * target_height_mm - 0.5 * target_height_mm
    Z = 0.0
    return SVector(X, Y, Z)
end

function compute_homograpy_DLT(M::StaticMatrix, P::StaticMatrix)
    T = promote_type(eltype(M), eltype(P))
    A = zeros(T, 8, 9)
    for i in 1:size(M, 1)
        Mi = M[i,:]
        A[2 * i - 1, 1:3] = Mi
        A[2 * i - 1, 7:9] = - P[i,1] * Mi
        A[2 * i, 4:6] = Mi
        A[2 * i, 7:9] = - P[i,2] * Mi
    end
    return nullspace(A)
end

function π_projection_function(K::StaticMatrix, R::StaticMatrix, t::StaticVector, point::StaticVector)
    # point_in_camera = R * point + t
    point_in_image = K * (R * point + t)
    return point_in_image / point_in_image[end]
end

function foo()
    K = @SMatrix [ 1169.19630    0.0     652.98743;
                0.0     1169.61014 528.83429;
                0.0        0.0       1.0]

    T = @SMatrix [0.961255 -0.275448 0.0108487  112.79;
            0.171961  0.629936 0.75737   -217.627;
        -0.21545  -0.72616  0.652895  1385.13]

    R = T[:, SOneTo(3)]
    t = T[:,end]

    tl = position_in_world(0.0, 0.0)
    tr = position_in_world(1123.0, 0.0)
    br = position_in_world(1123.0, 791.0)
    bl = position_in_world(0.0, 791.0)

    p1 = π_projection_function(K, R, t, tl)
    p2 = π_projection_function(K, R, t, tr)
    p3 = π_projection_function(K, R, t, br)
    p4 = π_projection_function(K, R, t, bl)
    P = [p1 p2 p3 p4]'

    M = @SMatrix [0.0    0.0 1.0;
                1123.0    0.0 1.0;
                1123.0 791.0 1.0;
                0.0 791.0 1.0]

    res = compute_homograpy_DLT(M, P)
    homography = reshape(res, (3,3))'
    return homography
end

using BenchmarkTools
@btime foo()

max_stars_repo_name: amin-abouee/test-cplusplus-and-julia

max_issues_repo_name: amin-abouee/test-cplusplus-and-julia

max_forks_repo_name: amin-abouee/test-cplusplus-and-julia


text:
### A Pluto.jl notebook ###
# v0.14.3

using Markdown
using InteractiveUtils

# ╔═╡ fae2ba1d-02ab-4cee-8c83-abda1e6a098c
begin
	import Pkg
	Pkg.activate(mktempdir())
	Pkg.add([
			Pkg.PackageSpec(name="CSV"),
			Pkg.PackageSpec(name="DataFrames")#,
			#Pkg.PackageSpec(name="EchelleCCFs")
			])
	Pkg.develop(name="EchelleCCFs")
	using CSV, DataFrames
	using EchelleCCFs
end

# ╔═╡ 0cbdbb36-4874-4862-823f-6bf0fbd4e60c
begin
	neid_data_path = "/gpfs/group/ebf11/default/ebf11/neid_solar/data/"
	proc_version_path = "v0.7develop20210501/solar"
	path_start = joinpath(neid_data_path,proc_version_path)
	output_path_base = "/gpfs/group/ebf11/default/ebf11/neid_solar/data/outputs2"
	proj_dir = "/gpfs/group/ebf11/default/ebf11/neid_solar/code/NeidSolarScripts.jl"
	script = joinpath(proj_dir,"examples","calc_order_ccfs_using_continuum_new.jl")
end

# ╔═╡ a62db4ef-c321-4dfe-b167-19c29ce45484
html"""<style>
main {
    max-width: 1000px;
}
"""

# ╔═╡ bd273401-b32e-44a6-a490-92575ed05ae9
begin
	df = DataFrame(:manifest_filename=>String[], :output_filename=>String[],:num_lines=>Int64[])
	for (root, dirs, files) in walkdir(output_path_base)
		for file in files
			if !occursin(r"manifest\.csv",file)  continue end
		  	#println("root = ", root)
		  	#println("dirs = ", dirs)
			#println("files = ", files)
			manifest_fn = joinpath(root,file)
			output_fn = joinpath(root,"daily_ccfs.jld2")
			nlines = countlines(manifest_fn)
			push!(df, Dict(:manifest_filename=>manifest_fn, :output_filename=>output_fn, :num_lines=>nlines))
    	end
	end
	df
end

# ╔═╡ d48ad3e0-14db-47b4-84db-4db10e1f0114
begin
	num_threads = 1
	min_order = 56
	max_order = 108
	#line_list_filename = joinpath(ENV["JULIA_DEPOT_PATH"],"dev/EchelleCCFs/data/masks","espresso+neid_mask_97_to_108.mas")
        #line_list_filename = joinpath(pkgdir(EchelleCCFs),"data/masks","espresso+neid_mask_97_to_108.mas")
        line_list_filename = "/gpfs/group/ebf11/default/ebf11/neid_solar/code/NeidSolarScripts.jl/scripts/linelist_20210208.csv"
	sed_filename = joinpath(proj_dir,"data", "neidMaster_HR_SmoothLampSED_20210101.fits")
        anchors_filename = "/gpfs/group/ebf11/default/ebf11/neid_solar/code/NeidSolarScripts.jl/scripts/anchors_20210208.jld2"
end

# ╔═╡ 8366a29a-1857-410f-aea3-87049e6248f6
pkgdir(EchelleCCFs)

# ╔═╡ e08192ce-9f0d-4e6f-a4aa-864f093dfcdd
#df[1,:manifest_filename]
df[1,:output_filename]

# ╔═╡ 73d682e9-cfa2-45b5-ba9e-b7cbf157b31d
begin
	last_job_id = 0
	function gen_job_name(; prefix::String = "auto")
	  global last_job_id
	  last_job_id += 1
	  return prefix * string(last_job_id)
	end
end

# ╔═╡ ed421e9d-2d2a-4af6-b832-591f38e092ad
function make_pbs_scr(;proj_dir::String, script::String, input_fn::String, output_fn::String, job_name::String = gen_job_name() )
   pbs_scr = """
#!/bin/bash
#PBS -N $job_name
#PBS -l nodes=1:ppn=$num_threads
#PBS -l pmem=4000mb
#PBS -l walltime=2:00:00
###PBS -A ebf11_c_g_vc_default
###PBS -q hprc
#PBS -A cyberlamp
#PBS -l feature=rhel7
#PBS -j oe
#PBS -M ebf11@psu.edu

# Get started
echo Job started on `hostname` at `date`

# Go to the correct place
cd \$PBS_O_WORKDIR
#cd $proj_dir

# Run the job itself
echo ~/julia --project=$proj_dir -t $num_threads $script $input_fn $output_fn --line_list_filename $line_list_filename  --sed_filename $sed_filename  --orders_to_use=$min_order $max_order --overwrite
~/julia --project=$proj_dir -t $num_threads $script $input_fn $output_fn --line_list_filename $line_list_filename  --sed_filename $sed_filename  --anchors_filename $anchors_filename  --orders_to_use=$min_order $max_order --apply_continuum_normalization  --overwrite

# Finish up
echo Job Ended at `date`
"""
  return pbs_scr
end

# ╔═╡ b5769171-0b0d-4e48-ae4e-be8c4995b4f2
"output_filename" ∈ names(df)

# ╔═╡ 8a7ff512-39aa-4b76-b3fd-f02ac410c85b

function make_pbs_multi_scr(;proj_dir::String, script::String, df::DataFrame, job_name::String = "auto", num_threads::Integer=1, pmem::String ="8000mb", walltime::String ="23:59:00", min_row::Integer = 1, max_row::Integer = size(df,1) )
	@assert "manifest_filename" ∈ names(df)
	@assert "output_filename" ∈ names(df)
    @assert size(df,1) >=1

	pbs_hdr_str = """
#!/bin/bash
#PBS -N $job_name
#PBS -l nodes=1:ppn=$num_threads
#PBS -l pmem=$pmem
#PBS -l walltime=$walltime
###PBS -A ebf11_c_g_vc_default
###PBS -q hprc
#PBS -A cyberlamp
#PBS -l feature=rhel7
#PBS -j oe
#PBS -M ebf11@psu.edu

# Get started
echo Job started on `hostname` at `date`

# Go to the correct place
cd \$PBS_O_WORKDIR
#cd $proj_dir
"""
 	pbs_str = pbs_hdr_str
	for (i,row) in enumerate(eachrow(df))
		if !(min_row<=i<=max_row) continue end
		input_fn = df[i,"manifest_filename"]
		output_fn = df[i,"output_filename"]
		pbs_cmd_str = """
# Run the job itself
~/julia --project=$proj_dir -t $num_threads $script $input_fn $output_fn --line_list_filename $line_list_filename  --sed_filename $sed_filename  --anchors_filename $anchors_filename  --orders_to_use=$min_order $max_order --apply_continuum_normalization  --overwrite

"""
		pbs_str = pbs_str * pbs_cmd_str

                # If want to do 2
                output2_fn = replace(output_fn,"daily_ccfs"=>"daily_ccfs_norm=sed")
		pbs_cmd_str = """
# Run the job itself
~/julia --project=$proj_dir -t $num_threads $script $input_fn $output2_fn --line_list_filename $line_list_filename  --sed_filename $sed_filename  --anchors_filename $anchors_filename  --orders_to_use=$min_order $max_order

"""
		pbs_str = pbs_str * pbs_cmd_str

	end
pbs_ftr_str = """
	# Finish up
echo Job Ended at `date`
"""

	pbs_str = pbs_str * pbs_ftr_str
  return pbs_str
end

# ╔═╡ 962d7e9e-4fdd-4080-82bf-f0175002ca19

open("submit_calc_ccfs.sh","w") do f_submit

for row in eachrow(df)
	if row.num_lines <= 1 continue end
   #=
    if isfile(joinpath(row.output_dir, "manifest.csv"))
       println("# Skipping ", row.output_dir)
       continue
    end
   =#
    m = match(r"(\d+)$", dirname(row.manifest_filename))
    dir = m.captures[1]

    pbs_scr = make_pbs_scr(proj_dir=proj_dir, script=script, input_fn=row.manifest_filename, output_fn=row.output_filename, job_name = "ccfs_"*dir)

    #println("Created script: ")
    #println(pbs_scr)
    #println("Echoing script: ")
    open("ccfs_$dir.pbs","w") do f_pbs
       print(f_pbs, pbs_scr)
    end
    println(f_submit, "qsub ccfs_$dir.pbs")
    #println(f_submit, "sleep $sleep_interval")
    #output = readchomp(pipeline(`echo $pbs_scr`, `qsub`))
    #println("output = ")
    #println(output)
end

end # submit_calc_ccfs.sh

# ╔═╡ 487c2c86-e56f-4823-be3c-05c076dbbe89

open("submit_calc_ccfs_multi.sh","w") do f_submit
files_per_jobs = 4
for i in reverse(1:files_per_jobs:size(df,1))
	#if row.num_lines <= 1 continue end
   #=
    if isfile(joinpath(row.output_dir, "manifest.csv"))
       println("# Skipping ", row.output_dir)
       continue
    end
   =#
    #m = match(r"(\d+)$", dirname(row.manifest_filename))
    #dir = m.captures[1]

    pbs_scr = make_pbs_multi_scr(proj_dir=proj_dir, script=script, df=df, min_row=i, max_row=min(i+files_per_jobs-1,size(df,1)), job_name = "ccfs_"*string(i), num_threads=num_threads)

    #println("Created script: ")
    #println(pbs_scr)
    #println("Echoing script: ")
    open("ccfs_" *string(i) * ".pbs","w") do f_pbs
       print(f_pbs, pbs_scr)
    end
    println(f_submit, "qsub ccfs_" *string(i) *".pbs")
    #println(f_submit, "sleep $sleep_interval")
    #output = readchomp(pipeline(`echo $pbs_scr`, `qsub`))
    #println("output = ")
    #println(output)
end

end # submit_calc_ccfs.sh|

# ╔═╡ Cell order:
# ╠═fae2ba1d-02ab-4cee-8c83-abda1e6a098c
# ╠═0cbdbb36-4874-4862-823f-6bf0fbd4e60c
# ╠═a62db4ef-c321-4dfe-b167-19c29ce45484
# ╠═bd273401-b32e-44a6-a490-92575ed05ae9
# ╠═d48ad3e0-14db-47b4-84db-4db10e1f0114
# ╠═8366a29a-1857-410f-aea3-87049e6248f6
# ╠═e08192ce-9f0d-4e6f-a4aa-864f093dfcdd
# ╠═73d682e9-cfa2-45b5-ba9e-b7cbf157b31d
# ╠═ed421e9d-2d2a-4af6-b832-591f38e092ad
# ╠═b5769171-0b0d-4e48-ae4e-be8c4995b4f2
# ╠═8a7ff512-39aa-4b76-b3fd-f02ac410c85b
# ╠═962d7e9e-4fdd-4080-82bf-f0175002ca19
# ╠═487c2c86-e56f-4823-be3c-05c076dbbe89


text:
@testset "KL Exchange" begin
    random_seed = 443591

    Random.seed!(random_seed)
    candidates = FullFactorial(fill([-1, 0, 1], 5))
    candidates_formula = ConstantTerm(0) ~ sum(Term.(Symbol.(names(candidates.matrix))))
    candidates_formula = FormulaTerm(candidates_formula.lhs,
                                     candidates_formula.rhs +
                                     (@formula 0 ~ factor3 ^ 2).rhs)
    selected_rows = kl_exchange(candidates_formula,
                                candidates.matrix,
                                seed_design_size = 2,
                                experiments = 11,
                                design_k = 11,
                                candidates_l = size(candidates.matrix, 1) - 11)

    @test isapprox(d_criterion(selected_rows), 0.7, atol = 0.1)

    Random.seed!(random_seed)
    n_candidates = 3000
    n_factors = 30;
    design_generator = DesignDistribution(Distributions.Uniform(0, 1), n_factors)
    candidates = rand(design_generator, n_candidates)
    selected_rows = kl_exchange(candidates.formula,
                                candidates.matrix,
                                experiments = n_factors + 2,
                                design_k = n_factors,
                                candidates_l = round(Int, (n_candidates - n_factors) / 2))

    @test isapprox(d_criterion(selected_rows), 0.07, atol = 0.01)
end


text:
#using Soss
using HypercubeTransform
import Distributions
const Dists = Distributions
import MeasureTheory
const MT = MeasureTheory

using Test

@testset "HypercubeTransform.jl" begin
    # Write your tests here.
    tests = [
        "transform",
        "composite",
        #"soss"
    ]
    res = map(tests) do t
        @eval module $(Symbol("Test_", t))
            include($t*".jl")
        end
        return
    end

end


text:
module Parsers

import Base: parse, &, |, ^

import ..Ex, ..Call, ..Nil, ..nil, ..Order, ..head, ..args

include("pcomb.jl")
include("prec.jl")
include("ast.jl")
include("grammar.jl")

end


text:
using Pkg
Pkg.activate(".")

filenames = (nodelocs="walmart_node_locations.txt",routes="walmart_routes.txt",
             distkm="distkm.txt")

url = "https://s3szufel.s3.eu-central-1.amazonaws.com/ComplexNetworks2019/"

using CodecZlib

for fname in filenames
    fnamegz = fname * ".gz"
    isfile(fname) && continue
    @info "Processing $fname"
    if !isfile("$fname.gz")
        @info "Downloading $fnamegz"
        download(url*fnamegz, fnamegz)
    end
    open(fname, "w") do io_out
        open(fnamegz) do io_in
            data = read(GzipDecompressorStream(io_in))
            write(io_out, data)
        end
    end
end
@info "Done!"


text:
struct Options{T<:AbstractFloat, U<:AbstractVector}

    # Display Options
    display::Bool
    displayInterval::UInt16

    # Function tolerance
    funcTol::T

    # Check function val for NaN and Inf
    funValCheck::Bool

    # Initial bounds
    iUB::U
    iLB::U

    # Max Iterations
    maxIters::UInt32

    # Max Stall Iterations
    maxStallIters::UInt32

    # Max Stall Time
    maxStallTime::T

    # Max Time
    maxTime::T

    # Objective Limit
    objLimit::T

    # Use parallel
    useParallel::Bool

    # Is vectorized
    #isVectorized::Bool # Not implemented
end

function Options(;display=true, displayInterval=1, funcTol=1e-6,
    funValCheck=true, iUB::V=nothing, iLB::V=nothing, maxIters=1000, maxStallIters=25,
    maxStallTime=500, maxTime=1800, objLimit=-Inf, useParallel=false) where
        {V<:Union{Nothing,AbstractArray}}

    T = typeof(funcTol)
    if iUB === nothing
        iUB = Vector{T}([])
    end
    if iLB === nothing
        iLB = Vector{T}([])
    end

    return Options{T,typeof(iUB)}(display, displayInterval, funcTol,
        funValCheck, iUB, iLB, maxIters, maxStallIters, maxStallTime,
        maxTime, objLimit, useParallel)
end


text:
wavenumber_low_volumefraction(ω::Number, medium::PhysicalMedium, specie::Specie; kws...) = wavenumber_low_volumefraction(ω, medium, [specie]; kws...)

wavenumber_low_volumefraction(ωs::AbstractVector{T}, medium::PhysicalMedium, species::Species{T}; kws...) where T<:Number = [wavenumber_low_volumefraction(ω, medium, species; kws...) for ω in ωs]

wavenumber_low_volumefraction(ωs::AbstractVector{T}, medium::PhysicalMedium, specie::Specie{T}; kws...) where T<:Number = [wavenumber_low_volumefraction(ω, medium, [specie]; kws...) for ω in ωs]

"""
    wavenumber_low_volumefraction(ω::T, medium::Acoustic{T,Dim}, species::Species{T,Dim}; basis_order::Int = 2)

Explicit formula for one effective wavenumber based on a low particle volume fraction expansion.
"""
function wavenumber_low_volumefraction(ω::T, medium::Acoustic{T,3}, species::Species{T,3};
        basis_order::Int = 2, verbose::Bool = true, numberofparticles::T = Inf
    ) where T

    volfrac = sum(volume_fraction.(species))
    if volfrac >= 0.4 && verbose
    @warn("the volume fraction $(round(100*volfrac))% is too high, expect a relative error of approximately $(round(100*volfrac^3.0))%")
    end

    # background wavenumber
    k = ω / medium.c

    # total particle number density
    scale_number_density = one(T) - one(T) / numberofparticles
    bar_numdensity = scale_number_density * sum(number_density.(species))

    Ts = get_t_matrices(medium, species, ω, basis_order)

    # Non-dimensional exclusion distance between particles
    kas = k .* [s1.exclusion_distance * outer_radius(s1) + s2.exclusion_distance * outer_radius(s2) for s1 in species, s2 in species]

    Ts_diag = diag.(Ts)
    fo = scale_number_density * sum(
            sum(Ts_diag[s]) * number_density(species[s])
    for s in eachindex(species)) / bar_numdensity

    len(order::Int) = basisorder_to_basislength(Acoustic{T,3},order)

    foo = scale_number_density^2 * sum(
        sqrt((2l + 1)*(2dl + 1)*(2l1 + 1)) * Complex{T}(im)^(l-dl-l1+1) * gaunt_coefficient(l,0,dl,0,l1,0) *
        sum(
            kas[s1,s2] * d3D(kas[s1,s2],l1) *
            Ts_diag[s1][len(l)] * Ts_diag[s2][len(dl)] *
            number_density(species[s1]) * number_density(species[s2])
        for s1 in eachindex(species), s2 in eachindex(species))
    for l = 0:basis_order for dl = 0:basis_order for l1 = abs(l-dl):abs(l+dl)) / Complex{T}(2 * sqrt(4pi) * bar_numdensity^2)

    # effective wavenumber squared up too second order in particle volume fraction
    kT2::Complex{T} = k^T(2) - im * 4pi * bar_numdensity * fo / k + (4pi)^2 * bar_numdensity^2 * foo / k^4

    return (imag(sqrt(kT2)) > zero(T)) ? sqrt(kT2) : -sqrt(kT2)
end

function wavenumber_low_volumefraction(ω::T, medium::Acoustic{T,2}, species::Species{T,2};
    basis_order::Int = 2, verbose::Bool = true, numberofparticles::T = Inf) where T

    volfrac = sum(volume_fraction.(species))
    if volfrac >= 0.4 && verbose
    @warn("the volume fraction $(round(100*volfrac))% is too high, expect a relative error of approximately $(round(100*volfrac^3.0))%")
    end

    # total particle number density
    scale_number_density = one(T) - one(T) / numberofparticles
    bar_numdensity = scale_number_density * sum(number_density.(species))

    # Add incident wavenumber
    kT2 = (ω/medium.c)^2.0
    # Add far-field contribution
    kT2 += - 4.0im*bar_numdensity*far_field_pattern(ω, medium, species; basis_order=basis_order)(0.0)
    # Add pair-field contribution
    kT2 += - 4.0im*bar_numdensity^(2.0)*pair_field_pattern(ω, medium, species; basis_order=basis_order)(0.0)

    return (imag(sqrt(kT2)) > zero(T)) ? sqrt(kT2) : -sqrt(kT2)
end

reflection_coefficient_low_volumefraction(ωs::AbstractVector{T},psource::PlaneSource{T,2,1,Acoustic{T,2}}, material::Material{2,Halfspace{T,2}}; kws... ) where T<:Number =
    [reflection_coefficient_low_volumefraction(ω, psource, material; kws... ) for ω in ωs]

"An explicit formula for the refleciton coefficient based on a low particle volume fraction."
function reflection_coefficient_low_volumefraction(ω::T, psource::PlaneSource{T,2,1,Acoustic{T,2}}, material::Material{2,Halfspace{T,2}}; kws...) where T<:Number

    θin = transmission_angle(psource,material)
    θ_ref = T(π) - T(2)*θin
    fo = far_field_pattern(ω, psource.medium, material.species; kws...)
    dfo = diff_far_field_pattern(ω, psource.medium, material.species; kws...)
    foo = pair_field_pattern(ω, psource.medium, material.species; kws...)

    k = ω / psource.medium.c
    α = k*cos(θin)
    R1 = im*fo(θ_ref)
    R2 = im*foo(θ_ref) + T(2)*fo(zero(T)) / (α^2.0) * (sin(θin)*cos(θin)*dfo(θ_ref) - fo(θ_ref))

    num_density = sum(number_density.(material.species))
    R = (R1 + num_density*R2)*num_density/(α^2.0)
    return R
end

function wavenumber_very_low_volumefraction(ω::Number, medium::Acoustic{T,2}, species::Species{T,2}; tol=1e-6, verbose = false) where T<:Number

  volume_fraction = sum(sp.volume_fraction for sp in species)
  if volume_fraction >= 0.4
    @warn("the volume fraction $(round(100*volume_fraction))% is too high, expect a relative error of approximately $(round(100*volume_fraction^3.0))%")
  end
  kT2 = (ω/medium.c)^2.0
  next_order = 4.0im*sum(number_density(sp) * t_matrix(sp, medium, ω, 0)[1,1] for sp in species)
  basis_order=1

  # sum more hankel orders until the relative error < tol
  while abs(next_order/kT2) > tol
    kT2 += next_order
    next_order = 4.0im*sum(number_density(sp) * t_matrix(sp, medium, ω, m)[m,m] for sp in species, m in (-basis_order,basis_order))
    basis_order +=1
  end
  kT2 += next_order
  basis_order +=1
  if verbose println("max Hankel order = $basis_order") end

  return sqrt(kT2)
end

max_stars_repo_name: arturgower/EffectiveWaves


text:
using SparseDiffTools, ForwardDiff, FiniteDiff, Zygote, IterativeSolvers
using LinearAlgebra, Test

using Random
Random.seed!(123)

const A = rand(300,300)
f(du,u) = mul!(du,A,u)
f(u) = A*u
x = rand(300)
v = rand(300)
du = similar(x)
g(u) = sum(abs2,u)
function h(x)
      FiniteDiff.finite_difference_gradient(g,x)
end
function h(dx,x)
      FiniteDiff.finite_difference_gradient!(dx,g,x)
end

cache1 = ForwardDiff.Dual{SparseDiffTools.DeivVecTag}.(x, v)
cache2 = ForwardDiff.Dual{SparseDiffTools.DeivVecTag}.(x, v)
@test num_jacvec!(du, f, x, v) ≈ ForwardDiff.jacobian(f,similar(x),x)*v rtol=1e-6
@test num_jacvec!(du, f, x, v, similar(v), similar(v)) ≈ ForwardDiff.jacobian(f,similar(x),x)*v rtol=1e-6
@test num_jacvec(f, x, v) ≈ ForwardDiff.jacobian(f,similar(x),x)*v rtol=1e-6

@test auto_jacvec!(du, f, x, v) ≈ ForwardDiff.jacobian(f,similar(x),x)*v
@test auto_jacvec!(du, f, x, v, cache1, cache2) ≈ ForwardDiff.jacobian(f,similar(x),x)*v
@test auto_jacvec(f, x, v) ≈ ForwardDiff.jacobian(f,similar(x),x)*v

@test num_hesvec!(du, g, x, v) ≈ ForwardDiff.hessian(g,x)*v rtol=1e-2
@test num_hesvec!(du, g, x, v, similar(v), similar(v), similar(v)) ≈ ForwardDiff.hessian(g,x)*v rtol=1e-2
@test num_hesvec(g, x, v) ≈ ForwardDiff.hessian(g,x)*v rtol=1e-2

@test numauto_hesvec!(du, g, x, v) ≈ ForwardDiff.hessian(g,x)*v rtol=1e-8
@test numauto_hesvec!(du, g, x, v, ForwardDiff.GradientConfig(g,x), similar(v), similar(v)) ≈ ForwardDiff.hessian(g,x)*v rtol=1e-8
@test numauto_hesvec(g, x, v) ≈ ForwardDiff.hessian(g,x)*v rtol=1e-8

@test autonum_hesvec!(du, g, x, v) ≈ ForwardDiff.hessian(g,x)*v rtol=1e-2
@test autonum_hesvec!(du, g, x, v, cache1, cache2) ≈ ForwardDiff.hessian(g,x)*v rtol=1e-2
@test autonum_hesvec(g, x, v) ≈ ForwardDiff.hessian(g,x)*v rtol=1e-8

@test numback_hesvec!(du, g, x, v) ≈ ForwardDiff.hessian(g,x)*v rtol=1e-8
@test numback_hesvec!(du, g, x, v, similar(v), similar(v)) ≈ ForwardDiff.hessian(g,x)*v rtol=1e-8
@test numback_hesvec(g, x, v) ≈ ForwardDiff.hessian(g,x)*v rtol=1e-8

cache3 = ForwardDiff.Dual{Nothing}.(x, v)
cache4 = ForwardDiff.Dual{Nothing}.(x, v)
@test autoback_hesvec!(du, g, x, v) ≈ ForwardDiff.hessian(g,x)*v rtol=1e-8
@test autoback_hesvec!(du, g, x, v, cache3, cache4) ≈ ForwardDiff.hessian(g,x)*v rtol=1e-8
@test autoback_hesvec(g, x, v) ≈ ForwardDiff.hessian(g,x)*v rtol=1e-8

@test num_hesvecgrad!(du, h, x, v) ≈ ForwardDiff.hessian(g,x)*v rtol=1e-2
@test num_hesvecgrad!(du, h, x, v, similar(v), similar(v)) ≈ ForwardDiff.hessian(g,x)*v rtol=1e-2
@test num_hesvecgrad(h, x, v) ≈ ForwardDiff.hessian(g,x)*v rtol=1e-2

@test auto_hesvecgrad!(du, h, x, v) ≈ ForwardDiff.hessian(g,x)*v rtol=1e-2
@test auto_hesvecgrad!(du, h, x, v, cache1, cache2) ≈ ForwardDiff.hessian(g,x)*v rtol=1e-2
@test auto_hesvecgrad(h, x, v) ≈ ForwardDiff.hessian(g,x)*v rtol=1e-2

L = JacVec(f,x)
@test L*x ≈ auto_jacvec(f, x, x)
@test L*v ≈ auto_jacvec(f, x, v)
@test mul!(du,L,v) ≈ auto_jacvec(f, x, v)
L.u .= v
@test mul!(du,L,v) ≈ auto_jacvec(f, v, v)

L = JacVec(f,x,autodiff=false)
@test L*x ≈ num_jacvec(f, x, x)
@test L*v ≈ num_jacvec(f, x, v)
L.u == x
@test mul!(du,L,v) ≈ num_jacvec(f, x, v) rtol=1e-6
L.u .= v
@test mul!(du,L,v) ≈ num_jacvec(f, v, v) rtol=1e-6

### Integration test with IterativeSolvers
out = similar(v)
gmres!(out, L, v)

x = rand(300)
v = rand(300)
L = HesVec(g,x,autodiff=false)
@test L*x ≈ num_hesvec(g, x, x)
@test L*v ≈ num_hesvec(g, x, v)
@test mul!(du,L,v) ≈ num_hesvec(g, x, v) rtol=1e-2
L.u .= v
@test mul!(du,L,v) ≈ num_hesvec(g, v, v) rtol=1e-2

L = HesVec(g,x)
@test L*x ≈ numauto_hesvec(g, x, x)
@test L*v ≈ numauto_hesvec(g, x, v)
@test mul!(du,L,v) ≈ numauto_hesvec(g, x, v) rtol=1e-8
L.u .= v
@test mul!(du,L,v) ≈ numauto_hesvec(g, v, v) rtol=1e-8

### Integration test with IterativeSolvers
out = similar(v)
gmres!(out, L, v)

x = rand(300)
v = rand(300)
L = HesVecGrad(h,x,autodiff=false)
@test L*x ≈ num_hesvec(g, x, x)
@test L*v ≈ num_hesvec(g, x, v)
@test mul!(du,L,v) ≈ num_hesvec(g, x, v) rtol=1e-2
L.u .= v
@test mul!(du,L,v) ≈ num_hesvec(g, v, v) rtol=1e-2

L = HesVecGrad(h,x,autodiff=true)
@test L*x ≈ autonum_hesvec(g, x, x)
@test L*v ≈ numauto_hesvec(g, x, v)
@test mul!(du,L,v) ≈ numauto_hesvec(g, x, v) rtol=1e-8
L.u .= v
@test mul!(du,L,v) ≈ numauto_hesvec(g, v, v) rtol=1e-8

### Integration test with IterativeSolvers
out = similar(v)
gmres!(out, L, v)


text:
module JetPackTransforms

using FFTW, JetPack, Jets, LinearAlgebra, Wavelets

include("jop_dct.jl")
include("jop_dwt.jl")
include("jop_fft.jl")
include("jop_sft.jl")
include("jop_slantstack.jl") # requires JopTaper from JetPack

end


text:
# ---
# title: 1609. Even Odd Tree
# id: problem1609
# author: Tian Jun
# date: 2020-10-31
# difficulty: Medium
# categories: Tree
# link: <https://leetcode.com/problems/even-odd-tree/description/>
# hidden: true
# ---
#
# A binary tree is named **Even-Odd** if it meets the following conditions:
#
#   * The root of the binary tree is at level index `0`, its children are at level index `1`, their children are at level index `2`, etc.
#   * For every **even-indexed** level, all nodes at the level have **odd** integer values in **strictly increasing** order (from left to right).
#   * For every **odd-indexed** level, all nodes at the level have **even** integer values in **strictly decreasing** order (from left to right).
#
# Given the `root` of a binary tree, _return_`true` _if the binary tree is
# **Even-Odd** , otherwise return _`false` _._
#
#
#
# **Example 1:**
#
# **![](https://assets.leetcode.com/uploads/2020/09/15/sample_1_1966.png)**
#
#
#
#     Input: root = [1,10,4,3,null,7,9,12,8,6,null,null,2]
#     Output: true
#     Explanation: The node values on each level are:
#     Level 0: [1]
#     Level 1: [10,4]
#     Level 2: [3,7,9]
#     Level 3: [12,8,6,2]
#     Since levels 0 and 2 are all odd and increasing, and levels 1 and 3 are all even and decreasing, the tree is Even-Odd.
#
#
# **Example 2:**
#
# **![](https://assets.leetcode.com/uploads/2020/09/15/sample_2_1966.png)**
#
#
#
#     Input: root = [5,4,2,3,3,7]
#     Output: false
#     Explanation: The node values on each level are:
#     Level 0: [5]
#     Level 1: [4,2]
#     Level 2: [3,3,7]
#     Node values in the level 2 must be in strictly increasing order, so the tree is not Even-Odd.
#
#
# **Example 3:**
#
# ![](https://assets.leetcode.com/uploads/2020/09/22/sample_1_333_1966.png)
#
#
#
#     Input: root = [5,9,1,3,5,7]
#     Output: false
#     Explanation: Node values in the level 1 should be even integers.
#
#
# **Example 4:**
#
#
#
#     Input: root = [1]
#     Output: true
#
#
# **Example 5:**
#
#
#
#     Input: root = [11,8,6,1,3,9,11,30,20,18,16,12,10,4,2,17]
#     Output: true
#
#
#
#
# **Constraints:**
#
#   * The number of nodes in the tree is in the range `[1, 105]`.
#   * `1 <= Node.val <= 106`
#
#
## @lc code=start
using LeetCode

## add your code here:
## @lc code=end


text:
using Pollen
using FastAI
using FastAI: Image
Image
using FluxTraining
using DLPipelines
import DataAugmentation
using FilePathsBase

import CairoMakie

ENV["DATADEPS_ALWAYS_ACCEPT"] = "true"

refmodules = [FastAI, FluxTraining, DLPipelines, DataAugmentation, FastAI.Datasets, FastAI.Models]
project = Pollen.documentationproject(FastAI; refmodules = refmodules)
Pollen.fullbuild(project, Pollen.FileBuilder(Pollen.HTML(), p"dev/"))


text:
###############################################################################
#
# Latex unit
#
###############################################################################
"""
    latex_unit(id::String;
               paren::Bool = true,
               squared::Bool = false,
               space::Bool = true,
               unicode::Bool = false
    )

Return the unit, given
- `id` Identifier of the unit (if not in libary, use id as unit)
- `paren` Optional: if true, include parenthesis
- `squared` Optional: if true, use `[]`, otherwise, use `()`
- `space` Optional: if true, add a SPACE at the beginning
- `unicode` Optional. If true, return unicode; otherwise, return upgreek string

The predefined units include
- `A` μmol CO₂ m⁻² s⁻¹
- `E` mol H₂O m⁻² s⁻¹
- `E_MMOL` mmol H₂O m⁻² s⁻¹
- `G` mol m⁻² s⁻¹
- `PAR` μmol m⁻² s⁻¹
- `T` °C
- `WUE` μmol mol⁻¹
"""
function latex_unit(
            id::String;
            paren::Bool = true,
            squared::Bool = false,
            space::Bool = true,
            unicode::Bool = false
)
    # initialize with an empty String
    if space
        unit_string = " ";
    else
        unit_string = "";
    end

    # add parenthesis
    if squared
        unit_string *= "[";
    else
        unit_string *= "(";
    end

    # switch id
    if id=="A"
        _unit = parse_symbol("μ", unicode) * "mol CO" * subscript(2) *
                " m" * superscript(-2) * " s" * superscript(-1);
    elseif id=="E"
        _unit = "mol H" * subscript(2) * "O" *
                " m" * superscript(-2) * " s" * superscript(-1);
    elseif id=="E_MMOL"
        _unit = "mmol H" * subscript(2) * "O" *
                " m" * superscript(-2) * " s" * superscript(-1);
    elseif id=="G"
        _unit = "mol m" * superscript(-2) * " s" * superscript(-1);
    elseif id=="PAR"
        _unit = parse_symbol("μ", unicode) * "mol" *
                " m" * superscript(-2) * " s" * superscript(-1);
    elseif id=="T"
        _unit = parse_symbol("degc", unicode);
    elseif id=="WUE"
        _unit = parse_symbol("μ", unicode) * "mol mol" * superscript(-1);
    else
        _unit = id;
    end

    # add unit to unit_string
    unit_string *= _unit;

    # end with parenthesis
    if squared
        unit_string *= "]";
    else
        unit_string *= ")";
    end

    return unit_string
end


text:
@with_kw mutable struct BBParameters{T <: AbstractFloat} <: AbstractPolicyParameters
    γ₀::T = 1.
end

mutable struct BB <: AbstractStep
    params::BBParameters{Float64}
    xprev::Vector{Float64}
    gprev::Vector{Float64}

    function (::Type{BB})(; kwargs...)
        return new(BBParameters(; kwargs...))
    end
end

function initialize!(bb::BB,x₀::Vector{Float64})
    bb.xprev = zeros(length(x₀))
    bb.gprev = zeros(length(x₀))
end

function stepsize(bb::BB,klocal::Integer,kglobal::Integer,fval::Real,x::AbstractVector,g::AbstractVector)
    if kglobal == 1
        bb.xprev .= x
        bb.gprev .= g
        return bb.params.γ₀
    end
    s = x - bb.xprev
    y = g - bb.gprev
    η = norm(s,2)^2/(s⋅y)
    bb.xprev .= x
    bb.gprev .= g
    return η
end


text:
# Check ChangepointSampler works for different distributions

using Distributions

@testset "Running ChangepointSampler tests..." begin

    num_samples = 1000
    λ = 50                 # Frequency of changes

    # Normal mean change sampler
    μ = Normal(1.0, 1.0)
    σ = 1.0
    Y = ChangepointSampler(()->Normal(rand(μ), σ), λ)
    @test_nowarn rand(Y, num_samples)
    @test_nowarn @changepoint_sampler num_samples λ Normal(μ, σ)

    # Normal variance change sampler
    μ = 1.0
    σ = Uniform(2.0, 15.0)
    Y = ChangepointSampler(()->Normal(μ, rand(σ)), λ)
    @test_nowarn rand(Y, num_samples)
    @test_nowarn @changepoint_sampler num_samples λ Normal(μ, σ)

    # Exponential change sampler
    μ = Uniform(0.0, 10.0)
    Y = ChangepointSampler(()->Exponential(rand(μ)), λ)
    @test_nowarn rand(Y, num_samples)
    @test_nowarn @changepoint_sampler num_samples λ Exponential(μ)

    # Poisson change sampler
    μ = Uniform(0.0, 10.0)
    Y = ChangepointSampler(()->Poisson(rand(μ)), λ)
    @test_nowarn rand(Y, num_samples)
    @test_nowarn @changepoint_sampler num_samples λ Poisson(μ)
end