text:
#==============================================================================#
# CloudWatch.jl
#
# This file is generated from:
# https://github.com/aws/aws-sdk-js/blob/master/apis/monitoring-2010-08-01.normal.json
#==============================================================================#

__precompile__()

module CloudWatch

using AWSCore

"""
    using AWSSDK.CloudWatch.delete_alarms
    delete_alarms([::AWSConfig], arguments::Dict)
    delete_alarms([::AWSConfig]; AlarmNames=)

    using AWSCore.Services.monitoring
    monitoring([::AWSConfig], "DeleteAlarms", arguments::Dict)
    monitoring([::AWSConfig], "DeleteAlarms", AlarmNames=)

# DeleteAlarms Operation

Deletes the specified alarms. In the event of an error, no alarms are deleted.

# Arguments

## `AlarmNames = [::String, ...]` -- *Required*
The alarms to be deleted.

# Exceptions

`ResourceNotFound`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/monitoring-2010-08-01/DeleteAlarms)
"""
@inline delete_alarms(aws::AWSConfig=default_aws_config(); args...) = delete_alarms(aws, args)

@inline delete_alarms(aws::AWSConfig, args) = AWSCore.Services.monitoring(aws, "DeleteAlarms", args)

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

"""
    using AWSSDK.CloudWatch.delete_dashboards
    delete_dashboards([::AWSConfig], arguments::Dict)
    delete_dashboards([::AWSConfig]; DashboardNames=)

    using AWSCore.Services.monitoring
    monitoring([::AWSConfig], "DeleteDashboards", arguments::Dict)
    monitoring([::AWSConfig], "DeleteDashboards", DashboardNames=)

# DeleteDashboards Operation

Deletes all dashboards that you specify. You may specify up to 100 dashboards to delete. If there is an error during this call, no dashboards are deleted.

# Arguments

## `DashboardNames = [::String, ...]` -- *Required*
The dashboards to be deleted. This parameter is required.

# Returns

`DeleteDashboardsOutput`

# Exceptions

`InvalidParameterValueException`, `DashboardNotFoundError` or `InternalServiceFault`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/monitoring-2010-08-01/DeleteDashboards)
"""
@inline delete_dashboards(aws::AWSConfig=default_aws_config(); args...) = delete_dashboards(aws, args)

@inline delete_dashboards(aws::AWSConfig, args) = AWSCore.Services.monitoring(aws, "DeleteDashboards", args)

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

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

    using AWSCore.Services.monitoring
    monitoring([::AWSConfig], "DescribeAlarmHistory", arguments::Dict)
    monitoring([::AWSConfig], "DescribeAlarmHistory", <keyword arguments>)

# DescribeAlarmHistory Operation

Retrieves the history for the specified alarm. You can filter the results by date range or item type. If an alarm name is not specified, the histories for all alarms are returned.

CloudWatch retains the history of an alarm even if you delete the alarm.

# Arguments

## `AlarmName = ::String`
The name of the alarm.

## `HistoryItemType = "ConfigurationUpdate", "StateUpdate" or "Action"`
The type of alarm histories to retrieve.

## `StartDate = timestamp`
The starting date to retrieve alarm history.

## `EndDate = timestamp`
The ending date to retrieve alarm history.

## `MaxRecords = ::Int`
The maximum number of alarm history records to retrieve.

## `NextToken = ::String`
The token returned by a previous call to indicate that there is more data available.

# Returns

`DescribeAlarmHistoryOutput`

# Exceptions

`InvalidNextToken`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/monitoring-2010-08-01/DescribeAlarmHistory)
"""
@inline describe_alarm_history(aws::AWSConfig=default_aws_config(); args...) = describe_alarm_history(aws, args)

@inline describe_alarm_history(aws::AWSConfig, args) = AWSCore.Services.monitoring(aws, "DescribeAlarmHistory", args)

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

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

    using AWSCore.Services.monitoring
    monitoring([::AWSConfig], "DescribeAlarms", arguments::Dict)
    monitoring([::AWSConfig], "DescribeAlarms", <keyword arguments>)

# DescribeAlarms Operation

Retrieves the specified alarms. If no alarms are specified, all alarms are returned. Alarms can be retrieved by using only a prefix for the alarm name, the alarm state, or a prefix for any action.

# Arguments

## `AlarmNames = [::String, ...]`
The names of the alarms.

## `AlarmNamePrefix = ::String`
The alarm name prefix. If this parameter is specified, you cannot specify `AlarmNames`.

## `StateValue = "OK", "ALARM" or "INSUFFICIENT_DATA"`
The state value to be used in matching alarms.

## `ActionPrefix = ::String`
The action name prefix.

## `MaxRecords = ::Int`
The maximum number of alarm descriptions to retrieve.

## `NextToken = ::String`
The token returned by a previous call to indicate that there is more data available.

# Returns

`DescribeAlarmsOutput`

# Exceptions

`InvalidNextToken`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/monitoring-2010-08-01/DescribeAlarms)
"""
@inline describe_alarms(aws::AWSConfig=default_aws_config(); args...) = describe_alarms(aws, args)

@inline describe_alarms(aws::AWSConfig, args) = AWSCore.Services.monitoring(aws, "DescribeAlarms", args)

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

"""
    using AWSSDK.CloudWatch.describe_alarms_for_metric
    describe_alarms_for_metric([::AWSConfig], arguments::Dict)
    describe_alarms_for_metric([::AWSConfig]; MetricName=, Namespace=, <keyword arguments>)

    using AWSCore.Services.monitoring
    monitoring([::AWSConfig], "DescribeAlarmsForMetric", arguments::Dict)
    monitoring([::AWSConfig], "DescribeAlarmsForMetric", MetricName=, Namespace=, <keyword arguments>)

# DescribeAlarmsForMetric Operation

Retrieves the alarms for the specified metric. To filter the results, specify a statistic, period, or unit.

# Arguments

## `MetricName = ::String` -- *Required*
The name of the metric.

## `Namespace = ::String` -- *Required*
The namespace of the metric.

## `Statistic = "SampleCount", "Average", "Sum", "Minimum" or "Maximum"`
The statistic for the metric, other than percentiles. For percentile statistics, use `ExtendedStatistics`.

## `ExtendedStatistic = ::String`
The percentile statistic for the metric. Specify a value between p0.0 and p100.

## `Dimensions = [[ ... ], ...]`
The dimensions associated with the metric. If the metric has any associated dimensions, you must specify them in order for the call to succeed.
```
 Dimensions = [[
        "Name" => <required> ::String,
        "Value" => <required> ::String
    ], ...]
```

## `Period = ::Int`
The period, in seconds, over which the statistic is applied.

## `Unit = "Seconds", "Microseconds", "Milliseconds", "Bytes", "Kilobytes", "Megabytes", "Gigabytes", "Terabytes", "Bits", "Kilobits", "Megabits", "Gigabits", "Terabits", "Percent", "Count", "Bytes/Second", "Kilobytes/Second", "Megabytes/Second", "Gigabytes/Second", "Terabytes/Second", "Bits/Second", "Kilobits/Second", "Megabits/Second", "Gigabits/Second", "Terabits/Second", "Count/Second" or "None"`
The unit for the metric.

# Returns

`DescribeAlarmsForMetricOutput`

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/monitoring-2010-08-01/DescribeAlarmsForMetric)
"""
@inline describe_alarms_for_metric(aws::AWSConfig=default_aws_config(); args...) = describe_alarms_for_metric(aws, args)

@inline describe_alarms_for_metric(aws::AWSConfig, args) = AWSCore.Services.monitoring(aws, "DescribeAlarmsForMetric", args)

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

"""
    using AWSSDK.CloudWatch.disable_alarm_actions
    disable_alarm_actions([::AWSConfig], arguments::Dict)
    disable_alarm_actions([::AWSConfig]; AlarmNames=)

    using AWSCore.Services.monitoring
    monitoring([::AWSConfig], "DisableAlarmActions", arguments::Dict)
    monitoring([::AWSConfig], "DisableAlarmActions", AlarmNames=)

# DisableAlarmActions Operation

Disables the actions for the specified alarms. When an alarm's actions are disabled, the alarm actions do not execute when the alarm state changes.

# Arguments

## `AlarmNames = [::String, ...]` -- *Required*
The names of the alarms.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/monitoring-2010-08-01/DisableAlarmActions)
"""
@inline disable_alarm_actions(aws::AWSConfig=default_aws_config(); args...) = disable_alarm_actions(aws, args)

@inline disable_alarm_actions(aws::AWSConfig, args) = AWSCore.Services.monitoring(aws, "DisableAlarmActions", args)

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

"""
    using AWSSDK.CloudWatch.enable_alarm_actions
    enable_alarm_actions([::AWSConfig], arguments::Dict)
    enable_alarm_actions([::AWSConfig]; AlarmNames=)

    using AWSCore.Services.monitoring
    monitoring([::AWSConfig], "EnableAlarmActions", arguments::Dict)
    monitoring([::AWSConfig], "EnableAlarmActions", AlarmNames=)

# EnableAlarmActions Operation

Enables the actions for the specified alarms.

# Arguments

## `AlarmNames = [::String, ...]` -- *Required*
The names of the alarms.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/monitoring-2010-08-01/EnableAlarmActions)
"""
@inline enable_alarm_actions(aws::AWSConfig=default_aws_config(); args...) = enable_alarm_actions(aws, args)

@inline enable_alarm_actions(aws::AWSConfig, args) = AWSCore.Services.monitoring(aws, "EnableAlarmActions", args)

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

"""
    using AWSSDK.CloudWatch.get_dashboard
    get_dashboard([::AWSConfig], arguments::Dict)
    get_dashboard([::AWSConfig]; DashboardName=)

    using AWSCore.Services.monitoring
    monitoring([::AWSConfig], "GetDashboard", arguments::Dict)
    monitoring([::AWSConfig], "GetDashboard", DashboardName=)

# GetDashboard Operation

Displays the details of the dashboard that you specify.

To copy an existing dashboard, use `GetDashboard`, and then use the data returned within `DashboardBody` as the template for the new dashboard when you call `PutDashboard` to create the copy.

# Arguments

## `DashboardName = ::String` -- *Required*
The name of the dashboard to be described.

# Returns

`GetDashboardOutput`

# Exceptions

`InvalidParameterValueException`, `DashboardNotFoundError` or `InternalServiceFault`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/monitoring-2010-08-01/GetDashboard)
"""
@inline get_dashboard(aws::AWSConfig=default_aws_config(); args...) = get_dashboard(aws, args)

@inline get_dashboard(aws::AWSConfig, args) = AWSCore.Services.monitoring(aws, "GetDashboard", args)

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

"""
    using AWSSDK.CloudWatch.get_metric_data
    get_metric_data([::AWSConfig], arguments::Dict)
    get_metric_data([::AWSConfig]; MetricDataQueries=, StartTime=, EndTime=, <keyword arguments>)

    using AWSCore.Services.monitoring
    monitoring([::AWSConfig], "GetMetricData", arguments::Dict)
    monitoring([::AWSConfig], "GetMetricData", MetricDataQueries=, StartTime=, EndTime=, <keyword arguments>)

# GetMetricData Operation

You can use the `GetMetricData` API to retrieve as many as 100 different metrics in a single request, with a total of as many as 100,800 datapoints. You can also optionally perform math expressions on the values of the returned statistics, to create new time series that represent new insights into your data. For example, using Lambda metrics, you could divide the Errors metric by the Invocations metric to get an error rate time series. For more information about metric math expressions, see [Metric Math Syntax and Functions](http://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/using-metric-math.html#metric-math-syntax) in the *Amazon CloudWatch User Guide*.

Calls to the `GetMetricData` API have a different pricing structure than calls to `GetMetricStatistics`. For more information about pricing, see [Amazon CloudWatch Pricing](https://aws.amazon.com/cloudwatch/pricing/).

# Arguments

## `MetricDataQueries = [[ ... ], ...]` -- *Required*
The metric queries to be returned. A single `GetMetricData` call can include as many as 100 `MetricDataQuery` structures. Each of these structures can specify either a metric to retrieve, or a math expression to perform on retrieved data.
```
 MetricDataQueries = [[
        "Id" => <required> ::String,
        "MetricStat" =>  [
            "Metric" => <required> [
                "Namespace" =>  ::String,
                "MetricName" =>  ::String,
                "Dimensions" =>  [[
                    "Name" => <required> ::String,
                    "Value" => <required> ::String
                ], ...]
            ],
            "Period" => <required> ::Int,
            "Stat" => <required> ::String,
            "Unit" =>  "Seconds", "Microseconds", "Milliseconds", "Bytes", "Kilobytes", "Megabytes", "Gigabytes", "Terabytes", "Bits", "Kilobits", "Megabits", "Gigabits", "Terabits", "Percent", "Count", "Bytes/Second", "Kilobytes/Second", "Megabytes/Second", "Gigabytes/Second", "Terabytes/Second", "Bits/Second", "Kilobits/Second", "Megabits/Second", "Gigabits/Second", "Terabits/Second", "Count/Second" or "None"
        ],
        "Expression" =>  ::String,
        "Label" =>  ::String,
        "ReturnData" =>  ::Bool
    ], ...]
```

## `StartTime = timestamp` -- *Required*
The time stamp indicating the earliest data to be returned.

## `EndTime = timestamp` -- *Required*
The time stamp indicating the latest data to be returned.

## `NextToken = ::String`
Include this value, if it was returned by the previous call, to get the next set of data points.

## `ScanBy = "TimestampDescending" or "TimestampAscending"`
The order in which data points should be returned. `TimestampDescending` returns the newest data first and paginates when the `MaxDatapoints` limit is reached. `TimestampAscending` returns the oldest data first and paginates when the `MaxDatapoints` limit is reached.

## `MaxDatapoints = ::Int`
The maximum number of data points the request should return before paginating. If you omit this, the default of 100,800 is used.

# Returns

`GetMetricDataOutput`

# Exceptions

`InvalidNextToken`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/monitoring-2010-08-01/GetMetricData)
"""
@inline get_metric_data(aws::AWSConfig=default_aws_config(); args...) = get_metric_data(aws, args)

@inline get_metric_data(aws::AWSConfig, args) = AWSCore.Services.monitoring(aws, "GetMetricData", args)

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

"""
    using AWSSDK.CloudWatch.get_metric_statistics
    get_metric_statistics([::AWSConfig], arguments::Dict)
    get_metric_statistics([::AWSConfig]; Namespace=, MetricName=, StartTime=, EndTime=, Period=, <keyword arguments>)

    using AWSCore.Services.monitoring
    monitoring([::AWSConfig], "GetMetricStatistics", arguments::Dict)
    monitoring([::AWSConfig], "GetMetricStatistics", Namespace=, MetricName=, StartTime=, EndTime=, Period=, <keyword arguments>)

# GetMetricStatistics Operation

Gets statistics for the specified metric.

The maximum number of data points returned from a single call is 1,440. If you request more than 1,440 data points, CloudWatch returns an error. To reduce the number of data points, you can narrow the specified time range and make multiple requests across adjacent time ranges, or you can increase the specified period. Data points are not returned in chronological order.

CloudWatch aggregates data points based on the length of the period that you specify. For example, if you request statistics with a one-hour period, CloudWatch aggregates all data points with time stamps that fall within each one-hour period. Therefore, the number of values aggregated by CloudWatch is larger than the number of data points returned.

CloudWatch needs raw data points to calculate percentile statistics. If you publish data using a statistic set instead, you can only retrieve percentile statistics for this data if one of the following conditions is true:

*   The SampleCount value of the statistic set is 1.

*   The Min and the Max values of the statistic set are equal.

Amazon CloudWatch retains metric data as follows:

*   Data points with a period of less than 60 seconds are available for 3 hours. These data points are high-resolution metrics and are available only for custom metrics that have been defined with a `StorageResolution` of 1.

*   Data points with a period of 60 seconds (1-minute) are available for 15 days.

*   Data points with a period of 300 seconds (5-minute) are available for 63 days.

*   Data points with a period of 3600 seconds (1 hour) are available for 455 days (15 months).

Data points that are initially published with a shorter period are aggregated together for long-term storage. For example, if you collect data using a period of 1 minute, the data remains available for 15 days with 1-minute resolution. After 15 days, this data is still available, but is aggregated and retrievable only with a resolution of 5 minutes. After 63 days, the data is further aggregated and is available with a resolution of 1 hour.

CloudWatch started retaining 5-minute and 1-hour metric data as of July 9, 2016.

For information about metrics and dimensions supported by AWS services, see the [Amazon CloudWatch Metrics and Dimensions Reference](http://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CW_Support_For_AWS.html) in the *Amazon CloudWatch User Guide*.

# Arguments

## `Namespace = ::String` -- *Required*
The namespace of the metric, with or without spaces.

## `MetricName = ::String` -- *Required*
The name of the metric, with or without spaces.

## `Dimensions = [[ ... ], ...]`
The dimensions. If the metric contains multiple dimensions, you must include a value for each dimension. CloudWatch treats each unique combination of dimensions as a separate metric. If a specific combination of dimensions was not published, you can't retrieve statistics for it. You must specify the same dimensions that were used when the metrics were created. For an example, see [Dimension Combinations](http://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#dimension-combinations) in the *Amazon CloudWatch User Guide*. For more information about specifying dimensions, see [Publishing Metrics](http://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/publishingMetrics.html) in the *Amazon CloudWatch User Guide*.
```
 Dimensions = [[
        "Name" => <required> ::String,
        "Value" => <required> ::String
    ], ...]
```

## `StartTime = timestamp` -- *Required*
The time stamp that determines the first data point to return. Start times are evaluated relative to the time that CloudWatch receives the request.

The value specified is inclusive; results include data points with the specified time stamp. The time stamp must be in ISO 8601 UTC format (for example, 2016-10-03T23:00:00Z).

CloudWatch rounds the specified time stamp as follows:

*   Start time less than 15 days ago - Round down to the nearest whole minute. For example, 12:32:34 is rounded down to 12:32:00.

*   Start time between 15 and 63 days ago - Round down to the nearest 5-minute clock interval. For example, 12:32:34 is rounded down to 12:30:00.

*   Start time greater than 63 days ago - Round down to the nearest 1-hour clock interval. For example, 12:32:34 is rounded down to 12:00:00.

If you set `Period` to 5, 10, or 30, the start time of your request is rounded down to the nearest time that corresponds to even 5-, 10-, or 30-second divisions of a minute. For example, if you make a query at (HH:mm:ss) 01:05:23 for the previous 10-second period, the start time of your request is rounded down and you receive data from 01:05:10 to 01:05:20. If you make a query at 15:07:17 for the previous 5 minutes of data, using a period of 5 seconds, you receive data timestamped between 15:02:15 and 15:07:15.

## `EndTime = timestamp` -- *Required*
The time stamp that determines the last data point to return.

The value specified is exclusive; results include data points up to the specified time stamp. The time stamp must be in ISO 8601 UTC format (for example, 2016-10-10T23:00:00Z).

## `Period = ::Int` -- *Required*
The granularity, in seconds, of the returned data points. For metrics with regular resolution, a period can be as short as one minute (60 seconds) and must be a multiple of 60. For high-resolution metrics that are collected at intervals of less than one minute, the period can be 1, 5, 10, 30, 60, or any multiple of 60. High-resolution metrics are those metrics stored by a `PutMetricData` call that includes a `StorageResolution` of 1 second.

If the `StartTime` parameter specifies a time stamp that is greater than 3 hours ago, you must specify the period as follows or no data points in that time range is returned:

*   Start time between 3 hours and 15 days ago - Use a multiple of 60 seconds (1 minute).

*   Start time between 15 and 63 days ago - Use a multiple of 300 seconds (5 minutes).

*   Start time greater than 63 days ago - Use a multiple of 3600 seconds (1 hour).

## `Statistics = ["SampleCount", "Average", "Sum", "Minimum" or "Maximum", ...]`
The metric statistics, other than percentile. For percentile statistics, use `ExtendedStatistics`. When calling `GetMetricStatistics`, you must specify either `Statistics` or `ExtendedStatistics`, but not both.

## `ExtendedStatistics = [::String, ...]`
The percentile statistics. Specify values between p0.0 and p100. When calling `GetMetricStatistics`, you must specify either `Statistics` or `ExtendedStatistics`, but not both.

## `Unit = "Seconds", "Microseconds", "Milliseconds", "Bytes", "Kilobytes", "Megabytes", "Gigabytes", "Terabytes", "Bits", "Kilobits", "Megabits", "Gigabits", "Terabits", "Percent", "Count", "Bytes/Second", "Kilobytes/Second", "Megabytes/Second", "Gigabytes/Second", "Terabytes/Second", "Bits/Second", "Kilobits/Second", "Megabits/Second", "Gigabits/Second", "Terabits/Second", "Count/Second" or "None"`
The unit for a given metric. Metrics may be reported in multiple units. Not supplying a unit results in all units being returned. If you specify only a unit that the metric does not report, the results of the call are null.

# Returns

`GetMetricStatisticsOutput`

# Exceptions

`InvalidParameterValueException`, `MissingRequiredParameterException`, `InvalidParameterCombinationException` or `InternalServiceFault`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/monitoring-2010-08-01/GetMetricStatistics)
"""
@inline get_metric_statistics(aws::AWSConfig=default_aws_config(); args...) = get_metric_statistics(aws, args)

@inline get_metric_statistics(aws::AWSConfig, args) = AWSCore.Services.monitoring(aws, "GetMetricStatistics", args)

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

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

    using AWSCore.Services.monitoring
    monitoring([::AWSConfig], "ListDashboards", arguments::Dict)
    monitoring([::AWSConfig], "ListDashboards", <keyword arguments>)

# ListDashboards Operation

Returns a list of the dashboards for your account. If you include `DashboardNamePrefix`, only those dashboards with names starting with the prefix are listed. Otherwise, all dashboards in your account are listed.

# Arguments

## `DashboardNamePrefix = ::String`
If you specify this parameter, only the dashboards with names starting with the specified string are listed. The maximum length is 255, and valid characters are A-Z, a-z, 0-9, ".", "-", and "_".

## `NextToken = ::String`
The token returned by a previous call to indicate that there is more data available.

# Returns

`ListDashboardsOutput`

# Exceptions

`InvalidParameterValueException` or `InternalServiceFault`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/monitoring-2010-08-01/ListDashboards)
"""
@inline list_dashboards(aws::AWSConfig=default_aws_config(); args...) = list_dashboards(aws, args)

@inline list_dashboards(aws::AWSConfig, args) = AWSCore.Services.monitoring(aws, "ListDashboards", args)

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

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

    using AWSCore.Services.monitoring
    monitoring([::AWSConfig], "ListMetrics", arguments::Dict)
    monitoring([::AWSConfig], "ListMetrics", <keyword arguments>)

# ListMetrics Operation

List the specified metrics. You can use the returned metrics with [GetMetricStatistics](@ref) to obtain statistical data.

Up to 500 results are returned for any one call. To retrieve additional results, use the returned token with subsequent calls.

After you create a metric, allow up to fifteen minutes before the metric appears. Statistics about the metric, however, are available sooner using [GetMetricStatistics](@ref).

# Arguments

## `Namespace = ::String`
The namespace to filter against.

## `MetricName = ::String`
The name of the metric to filter against.

## `Dimensions = [[ ... ], ...]`
The dimensions to filter against.
```
 Dimensions = [[
        "Name" => <required> ::String,
        "Value" =>  ::String
    ], ...]
```

## `NextToken = ::String`
The token returned by a previous call to indicate that there is more data available.

# Returns

`ListMetricsOutput`

# Exceptions

`InternalServiceFault` or `InvalidParameterValueException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/monitoring-2010-08-01/ListMetrics)
"""
@inline list_metrics(aws::AWSConfig=default_aws_config(); args...) = list_metrics(aws, args)

@inline list_metrics(aws::AWSConfig, args) = AWSCore.Services.monitoring(aws, "ListMetrics", args)

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

"""
    using AWSSDK.CloudWatch.put_dashboard
    put_dashboard([::AWSConfig], arguments::Dict)
    put_dashboard([::AWSConfig]; DashboardName=, DashboardBody=)

    using AWSCore.Services.monitoring
    monitoring([::AWSConfig], "PutDashboard", arguments::Dict)
    monitoring([::AWSConfig], "PutDashboard", DashboardName=, DashboardBody=)

# PutDashboard Operation

Creates a dashboard if it does not already exist, or updates an existing dashboard. If you update a dashboard, the entire contents are replaced with what you specify here.

You can have up to 500 dashboards per account. All dashboards in your account are global, not region-specific.

A simple way to create a dashboard using `PutDashboard` is to copy an existing dashboard. To copy an existing dashboard using the console, you can load the dashboard and then use the View/edit source command in the Actions menu to display the JSON block for that dashboard. Another way to copy a dashboard is to use `GetDashboard`, and then use the data returned within `DashboardBody` as the template for the new dashboard when you call `PutDashboard`.

When you create a dashboard with `PutDashboard`, a good practice is to add a text widget at the top of the dashboard with a message that the dashboard was created by script and should not be changed in the console. This message could also point console users to the location of the `DashboardBody` script or the CloudFormation template used to create the dashboard.

# Arguments

## `DashboardName = ::String` -- *Required*
The name of the dashboard. If a dashboard with this name already exists, this call modifies that dashboard, replacing its current contents. Otherwise, a new dashboard is created. The maximum length is 255, and valid characters are A-Z, a-z, 0-9, "-", and "_". This parameter is required.

## `DashboardBody = ::String` -- *Required*
The detailed information about the dashboard in JSON format, including the widgets to include and their location on the dashboard. This parameter is required.

For more information about the syntax, see [CloudWatch-Dashboard-Body-Structure](@ref).

# Returns

`PutDashboardOutput`

# Exceptions

`DashboardInvalidInputError` or `InternalServiceFault`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/monitoring-2010-08-01/PutDashboard)
"""
@inline put_dashboard(aws::AWSConfig=default_aws_config(); args...) = put_dashboard(aws, args)

@inline put_dashboard(aws::AWSConfig, args) = AWSCore.Services.monitoring(aws, "PutDashboard", args)

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

"""
    using AWSSDK.CloudWatch.put_metric_alarm
    put_metric_alarm([::AWSConfig], arguments::Dict)
    put_metric_alarm([::AWSConfig]; AlarmName=, MetricName=, Namespace=, Period=, EvaluationPeriods=, Threshold=, ComparisonOperator=, <keyword arguments>)

    using AWSCore.Services.monitoring
    monitoring([::AWSConfig], "PutMetricAlarm", arguments::Dict)
    monitoring([::AWSConfig], "PutMetricAlarm", AlarmName=, MetricName=, Namespace=, Period=, EvaluationPeriods=, Threshold=, ComparisonOperator=, <keyword arguments>)

# PutMetricAlarm Operation

Creates or updates an alarm and associates it with the specified metric. Optionally, this operation can associate one or more Amazon SNS resources with the alarm.

When this operation creates an alarm, the alarm state is immediately set to `INSUFFICIENT_DATA`. The alarm is evaluated and its state is set appropriately. Any actions associated with the state are then executed.

When you update an existing alarm, its state is left unchanged, but the update completely overwrites the previous configuration of the alarm.

If you are an IAM user, you must have Amazon EC2 permissions for some operations:

*   `iam:CreateServiceLinkedRole` for all alarms with EC2 actions

*   `ec2:DescribeInstanceStatus` and `ec2:DescribeInstances` for all alarms on EC2 instance status metrics

*   `ec2:StopInstances` for alarms with stop actions

*   `ec2:TerminateInstances` for alarms with terminate actions

*   `ec2:DescribeInstanceRecoveryAttribute` and `ec2:RecoverInstances` for alarms with recover actions

If you have read/write permissions for Amazon CloudWatch but not for Amazon EC2, you can still create an alarm, but the stop or terminate actions are not performed. However, if you are later granted the required permissions, the alarm actions that you created earlier are performed.

If you are using an IAM role (for example, an EC2 instance profile), you cannot stop or terminate the instance using alarm actions. However, you can still see the alarm state and perform any other actions such as Amazon SNS notifications or Auto Scaling policies.

If you are using temporary security credentials granted using AWS STS, you cannot stop or terminate an EC2 instance using alarm actions.

You must create at least one stop, terminate, or reboot alarm using either the Amazon EC2 or CloudWatch consoles to create the **EC2ActionsAccess** IAM role. After this IAM role is created, you can create stop, terminate, or reboot alarms using a command-line interface or API.

# Arguments

## `AlarmName = ::String` -- *Required*
The name for the alarm. This name must be unique within the AWS account.

## `AlarmDescription = ::String`
The description for the alarm.

## `ActionsEnabled = ::Bool`
Indicates whether actions should be executed during any changes to the alarm state.

## `OKActions = [::String, ...]`
The actions to execute when this alarm transitions to an `OK` state from any other state. Each action is specified as an Amazon Resource Name (ARN).

Valid Values: arn:aws:automate:*region*:ec2:stop | arn:aws:automate:*region*:ec2:terminate | arn:aws:automate:*region*:ec2:recover | arn:aws:sns:*region*:*account-id*:*sns-topic-name* | arn:aws:autoscaling:*region*:*account-id*:scalingPolicy:*policy-id* autoScalingGroupName/*group-friendly-name*:policyName/*policy-friendly-name*

Valid Values (for use with IAM roles): arn:aws:swf:*region*:{*account-id*}:action/actions/AWS_EC2.InstanceId.Stop/1.0 | arn:aws:swf:*region*:{*account-id*}:action/actions/AWS_EC2.InstanceId.Terminate/1.0 | arn:aws:swf:*region*:{*account-id*}:action/actions/AWS_EC2.InstanceId.Reboot/1.0

## `AlarmActions = [::String, ...]`
The actions to execute when this alarm transitions to the `ALARM` state from any other state. Each action is specified as an Amazon Resource Name (ARN).

Valid Values: arn:aws:automate:*region*:ec2:stop | arn:aws:automate:*region*:ec2:terminate | arn:aws:automate:*region*:ec2:recover | arn:aws:sns:*region*:*account-id*:*sns-topic-name* | arn:aws:autoscaling:*region*:*account-id*:scalingPolicy:*policy-id* autoScalingGroupName/*group-friendly-name*:policyName/*policy-friendly-name*

Valid Values (for use with IAM roles): arn:aws:swf:*region*:{*account-id*}:action/actions/AWS_EC2.InstanceId.Stop/1.0 | arn:aws:swf:*region*:{*account-id*}:action/actions/AWS_EC2.InstanceId.Terminate/1.0 | arn:aws:swf:*region*:{*account-id*}:action/actions/AWS_EC2.InstanceId.Reboot/1.0

## `InsufficientDataActions = [::String, ...]`
The actions to execute when this alarm transitions to the `INSUFFICIENT_DATA` state from any other state. Each action is specified as an Amazon Resource Name (ARN).

Valid Values: arn:aws:automate:*region*:ec2:stop | arn:aws:automate:*region*:ec2:terminate | arn:aws:automate:*region*:ec2:recover | arn:aws:sns:*region*:*account-id*:*sns-topic-name* | arn:aws:autoscaling:*region*:*account-id*:scalingPolicy:*policy-id* autoScalingGroupName/*group-friendly-name*:policyName/*policy-friendly-name*

Valid Values (for use with IAM roles): arn:aws:swf:*region*:{*account-id*}:action/actions/AWS_EC2.InstanceId.Stop/1.0 | arn:aws:swf:*region*:{*account-id*}:action/actions/AWS_EC2.InstanceId.Terminate/1.0 | arn:aws:swf:*region*:{*account-id*}:action/actions/AWS_EC2.InstanceId.Reboot/1.0

## `MetricName = ::String` -- *Required*
The name for the metric associated with the alarm.

## `Namespace = ::String` -- *Required*
The namespace for the metric associated with the alarm.

## `Statistic = "SampleCount", "Average", "Sum", "Minimum" or "Maximum"`
The statistic for the metric associated with the alarm, other than percentile. For percentile statistics, use `ExtendedStatistic`. When you call `PutMetricAlarm`, you must specify either `Statistic` or `ExtendedStatistic,` but not both.

## `ExtendedStatistic = ::String`
The percentile statistic for the metric associated with the alarm. Specify a value between p0.0 and p100. When you call `PutMetricAlarm`, you must specify either `Statistic` or `ExtendedStatistic,` but not both.

## `Dimensions = [[ ... ], ...]`
The dimensions for the metric associated with the alarm.
```
 Dimensions = [[
        "Name" => <required> ::String,
        "Value" => <required> ::String
    ], ...]
```

## `Period = ::Int` -- *Required*
The period, in seconds, over which the specified statistic is applied. Valid values are 10, 30, and any multiple of 60.

Be sure to specify 10 or 30 only for metrics that are stored by a `PutMetricData` call with a `StorageResolution` of 1. If you specify a period of 10 or 30 for a metric that does not have sub-minute resolution, the alarm still attempts to gather data at the period rate that you specify. In this case, it does not receive data for the attempts that do not correspond to a one-minute data resolution, and the alarm may often lapse into INSUFFICENT_DATA status. Specifying 10 or 30 also sets this alarm as a high-resolution alarm, which has a higher charge than other alarms. For more information about pricing, see [Amazon CloudWatch Pricing](https://aws.amazon.com/cloudwatch/pricing/).

An alarm's total current evaluation period can be no longer than one day, so `Period` multiplied by `EvaluationPeriods` cannot be more than 86,400 seconds.

## `Unit = "Seconds", "Microseconds", "Milliseconds", "Bytes", "Kilobytes", "Megabytes", "Gigabytes", "Terabytes", "Bits", "Kilobits", "Megabits", "Gigabits", "Terabits", "Percent", "Count", "Bytes/Second", "Kilobytes/Second", "Megabytes/Second", "Gigabytes/Second", "Terabytes/Second", "Bits/Second", "Kilobits/Second", "Megabits/Second", "Gigabits/Second", "Terabits/Second", "Count/Second" or "None"`
The unit of measure for the statistic. For example, the units for the Amazon EC2 NetworkIn metric are Bytes because NetworkIn tracks the number of bytes that an instance receives on all network interfaces. You can also specify a unit when you create a custom metric. Units help provide conceptual meaning to your data. Metric data points that specify a unit of measure, such as Percent, are aggregated separately.

If you specify a unit, you must use a unit that is appropriate for the metric. Otherwise, the CloudWatch alarm can get stuck in the `INSUFFICIENT DATA` state.

## `EvaluationPeriods = ::Int` -- *Required*
The number of periods over which data is compared to the specified threshold. If you are setting an alarm which requires that a number of consecutive data points be breaching to trigger the alarm, this value specifies that number. If you are setting an "M out of N" alarm, this value is the N.

An alarm's total current evaluation period can be no longer than one day, so this number multiplied by `Period` cannot be more than 86,400 seconds.

## `DatapointsToAlarm = ::Int`
The number of datapoints that must be breaching to trigger the alarm. This is used only if you are setting an "M out of N" alarm. In that case, this value is the M. For more information, see [Evaluating an Alarm](http://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/AlarmThatSendsEmail.html#alarm-evaluation) in the *Amazon CloudWatch User Guide*.

## `Threshold = double` -- *Required*
The value against which the specified statistic is compared.

## `ComparisonOperator = "GreaterThanOrEqualToThreshold", "GreaterThanThreshold", "LessThanThreshold" or "LessThanOrEqualToThreshold"` -- *Required*
The arithmetic operation to use when comparing the specified statistic and threshold. The specified statistic value is used as the first operand.

## `TreatMissingData = ::String`
Sets how this alarm is to handle missing data points. If `TreatMissingData` is omitted, the default behavior of `missing` is used. For more information, see [Configuring How CloudWatch Alarms Treats Missing Data](http://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/AlarmThatSendsEmail.html#alarms-and-missing-data).

Valid Values: `breaching | notBreaching | ignore | missing`

## `EvaluateLowSampleCountPercentile = ::String`
Used only for alarms based on percentiles. If you specify `ignore`, the alarm state does not change during periods with too few data points to be statistically significant. If you specify `evaluate` or omit this parameter, the alarm is always evaluated and possibly changes state no matter how many data points are available. For more information, see [Percentile-Based CloudWatch Alarms and Low Data Samples](http://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/AlarmThatSendsEmail.html#percentiles-with-low-samples).

Valid Values: `evaluate | ignore`

# Exceptions

`LimitExceededFault`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/monitoring-2010-08-01/PutMetricAlarm)
"""
@inline put_metric_alarm(aws::AWSConfig=default_aws_config(); args...) = put_metric_alarm(aws, args)

@inline put_metric_alarm(aws::AWSConfig, args) = AWSCore.Services.monitoring(aws, "PutMetricAlarm", args)

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

"""
    using AWSSDK.CloudWatch.put_metric_data
    put_metric_data([::AWSConfig], arguments::Dict)
    put_metric_data([::AWSConfig]; Namespace=, MetricData=)

    using AWSCore.Services.monitoring
    monitoring([::AWSConfig], "PutMetricData", arguments::Dict)
    monitoring([::AWSConfig], "PutMetricData", Namespace=, MetricData=)

# PutMetricData Operation

Publishes metric data points to Amazon CloudWatch. CloudWatch associates the data points with the specified metric. If the specified metric does not exist, CloudWatch creates the metric. When CloudWatch creates a metric, it can take up to fifteen minutes for the metric to appear in calls to [ListMetrics](@ref).

Each `PutMetricData` request is limited to 40 KB in size for HTTP POST requests.

Although the `Value` parameter accepts numbers of type `Double`, CloudWatch rejects values that are either too small or too large. Values must be in the range of 8.515920e-109 to 1.174271e+108 (Base 10) or 2e-360 to 2e360 (Base 2). In addition, special values (for example, NaN, +Infinity, -Infinity) are not supported.

You can use up to 10 dimensions per metric to further clarify what data the metric collects. For more information about specifying dimensions, see [Publishing Metrics](http://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/publishingMetrics.html) in the *Amazon CloudWatch User Guide*.

Data points with time stamps from 24 hours ago or longer can take at least 48 hours to become available for [GetMetricStatistics](@ref) from the time they are submitted.

CloudWatch needs raw data points to calculate percentile statistics. If you publish data using a statistic set instead, you can only retrieve percentile statistics for this data if one of the following conditions is true:

*   The SampleCount value of the statistic set is 1

*   The Min and the Max values of the statistic set are equal

# Arguments

## `Namespace = ::String` -- *Required*
The namespace for the metric data.

You cannot specify a namespace that begins with "AWS/". Namespaces that begin with "AWS/" are reserved for use by Amazon Web Services products.

## `MetricData = [[ ... ], ...]` -- *Required*
The data for the metric.
```
 MetricData = [[
        "MetricName" => <required> ::String,
        "Dimensions" =>  [[
            "Name" => <required> ::String,
            "Value" => <required> ::String
        ], ...],
        "Timestamp" =>  timestamp,
        "Value" =>  double,
        "StatisticValues" =>  [
            "SampleCount" => <required> double,
            "Sum" => <required> double,
            "Minimum" => <required> double,
            "Maximum" => <required> double
        ],
        "Unit" =>  "Seconds", "Microseconds", "Milliseconds", "Bytes", "Kilobytes", "Megabytes", "Gigabytes", "Terabytes", "Bits", "Kilobits", "Megabits", "Gigabits", "Terabits", "Percent", "Count", "Bytes/Second", "Kilobytes/Second", "Megabytes/Second", "Gigabytes/Second", "Terabytes/Second", "Bits/Second", "Kilobits/Second", "Megabits/Second", "Gigabits/Second", "Terabits/Second", "Count/Second" or "None",
        "StorageResolution" =>  ::Int
    ], ...]
```

# Exceptions

`InvalidParameterValueException`, `MissingRequiredParameterException`, `InvalidParameterCombinationException` or `InternalServiceFault`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/monitoring-2010-08-01/PutMetricData)
"""
@inline put_metric_data(aws::AWSConfig=default_aws_config(); args...) = put_metric_data(aws, args)

@inline put_metric_data(aws::AWSConfig, args) = AWSCore.Services.monitoring(aws, "PutMetricData", args)

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

"""
    using AWSSDK.CloudWatch.set_alarm_state
    set_alarm_state([::AWSConfig], arguments::Dict)
    set_alarm_state([::AWSConfig]; AlarmName=, StateValue=, StateReason=, <keyword arguments>)

    using AWSCore.Services.monitoring
    monitoring([::AWSConfig], "SetAlarmState", arguments::Dict)
    monitoring([::AWSConfig], "SetAlarmState", AlarmName=, StateValue=, StateReason=, <keyword arguments>)

# SetAlarmState Operation

Temporarily sets the state of an alarm for testing purposes. When the updated state differs from the previous value, the action configured for the appropriate state is invoked. For example, if your alarm is configured to send an Amazon SNS message when an alarm is triggered, temporarily changing the alarm state to `ALARM` sends an SNS message. The alarm returns to its actual state (often within seconds). Because the alarm state change happens quickly, it is typically only visible in the alarm's **History** tab in the Amazon CloudWatch console or through [DescribeAlarmHistory](@ref).

# Arguments

## `AlarmName = ::String` -- *Required*
The name for the alarm. This name must be unique within the AWS account. The maximum length is 255 characters.

## `StateValue = "OK", "ALARM" or "INSUFFICIENT_DATA"` -- *Required*
The value of the state.

## `StateReason = ::String` -- *Required*
The reason that this alarm is set to this specific state, in text format.

## `StateReasonData = ::String`
The reason that this alarm is set to this specific state, in JSON format.

# Exceptions

`ResourceNotFound` or `InvalidFormatFault`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/monitoring-2010-08-01/SetAlarmState)
"""
@inline set_alarm_state(aws::AWSConfig=default_aws_config(); args...) = set_alarm_state(aws, args)

@inline set_alarm_state(aws::AWSConfig, args) = AWSCore.Services.monitoring(aws, "SetAlarmState", args)

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

end # module CloudWatch

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


text:
"""
    print_parameters(all_obs::AllObservations)

Print information about the variable parameters about which the
`all_obs.param_depend` object stores some interdependency information.
"""
function print_parameters(all_obs::AllObservations)
    num_rec = length(all_obs.recordings)
    params = collect(keys(all_obs.param_depend))
    obs = collect(keys(all_obs.param_depend))
    p_and_o = collect(unique(hcat(obs, params)))
    println()
    println("There are $num_rec independent recordings.")
    println("There are also $(length(p_and_o)) variable parameters.")
    println("* * *")
    println("You may define the var-parameters using the following template:")
    println("# start of template")
    println("using OrderedCollections")
    println()
    println("θ_init = OrderedDict(")
    for (i,p) in enumerate(p_and_o)
        println("\t:$p => ... , # param $i")
    end
    println(")")
    println("# end of template")
    println("and in an MCMC setting you may let your parameter update step ")
    println("refer to a subset of indices you wish to update using the order ")
    println("given above.")
    println("* * *")
end

const _SYMS = Tuple{Vararg{Pair{Int64,Symbol},N} where N} # localθidx, pname
const _OBSIDX = Tuple{Vararg{Pair{Int64,Int64},N} where N} # localθidx, obsidx
"""
    local_symbols(
        all_obs::AllObservations,
        objects::AbstractArray{<:AbstractArray},
        f::Function,
        θsym::Vector{Symbol}
    ) where T

`objects` is usually an array of arrays that must in total have the same number
of elements as there are observations in the recording. It may however have a
different jagged structure. The output is of the same structure as `objects`
and gives for each `o` in `object` a corresponding lists of parameters and
observations it depends on.
"""
function local_symbols(
        all_obs::AllObservations,
        objects::AbstractArray{<:AbstractArray},
        f::Function,
        θsym::Vector{Symbol}
    ) where T
    all_p_symbols = Vector{Vector{_SYMS}}(undef, length(objects))
    all_o_indices = Vector{Vector{_OBSIDX}}(undef, length(objects))
    _i = _j = 1

    for i in eachindex(objects)
        all_p_symbols[i] = Vector{_SYMS}(undef, length(objects[i]))
        all_o_indices[i] = Vector{_OBSIDX}(undef, length(objects[i]))

        for j in eachindex(objects[i])
            plocal, olocal = find_local_names(all_obs, θsym, (_i, _j))
            all_p_symbols[i][j] = Tuple(
                filter(s->hasproperty(f(objects[i][j]), s[2]), plocal)
            )
            all_o_indices[i][j] = Tuple(olocal)
            _j += 1
            if _j > length(all_obs.recordings[_i].obs)
                _j = 1
                _i += 1
            end
        end
    end
    all_p_symbols, all_o_indices
end

function find_local_names(all_obs::AllObservations, θsym, (i, j))
    plocal = Pair{Int64,Symbol}[]
    p_dep = all_obs.param_depend_rev[i]

    for k in 1:length(p_dep)
        global_symbol, local_symbol = p_dep[k]
        idx = findfirst(x->x==global_symbol, θsym)
        if idx != nothing
            push!(plocal, (idx => local_symbol))
        end
    end

    olocal = Pair{Int64,Int64}[]
    o_dep = all_obs.obs_depend_rev[i][j]

    for k in 1:length(o_dep)
        global_symbol, local_idx = o_dep[k]
        idx = findfirst(x->x==global_symbol, θsym)
        if idx != nothing
            push!(olcal, (idx => local_idx))
        end
    end
    plocal, olocal
end

ext: jl


text:
# Input, 1-based, closed interval
# returned bin index is 0-based!!!
function reg2bin(s::Int, e::Int)
	@assert s>0 && e>0 "Region coordinates must be positive integers."
	@assert s<=2^29 && e<=2^29 "Region coordinates must be <= 2^29."

	s = s-1 # 1-based to 0-based
	e = e-1 # 1-based to 0-based
	# Original implementation is for closed intervals (if we skip end--), so e is correct.

	s>>14 == e>>14 && return div((1<<15)-1,7) + (s>>14)
	s>>17 == e>>17 && return div((1<<12)-1,7) + (s>>17)
	s>>20 == e>>20 && return div( (1<<9)-1,7) + (s>>20)
	s>>23 == e>>23 && return div( (1<<6)-1,7) + (s>>23)
	s>>26 == e>>26 && return div( (1<<3)-1,7) + (s>>26)
	0

	# from BAM specification pdf
	# --end;
	# if (beg>>14 == end>>14) return ((1<<15)-1)/7 + (beg>>14);
	# if (beg>>17 == end>>17) return ((1<<12)-1)/7 + (beg>>17);
	# if (beg>>20 == end>>20) return ((1<<9)-1)/7 + (beg>>20);
	# if (beg>>23 == end>>23) return ((1<<6)-1)/7 + (beg>>23);
	# if (beg>>26 == end>>26) return ((1<<3)-1)/7 + (beg>>26);
	# return 0;
end

# Input, 1-based, closed interval
# returned bin indices are 0-based!!!
function reg2bins(s::Int, e::Int)
	@assert s>0 && e>0 "Region coordinates must be positive integers."
	@assert s<=2^29 && e<=2^29 "Region coordinates must be <= 2^29."

	s = s-1 # 1-based to 0-based
	e = e-1 # 1-based to 0-based
	# Original implementation is for closed intervals (if we skip end--), so e is correct.

	bins = Int[]
	push!(bins, 0)
	append!(bins,    1 + (s>>26) :     1 + (e>>26))
	append!(bins,    9 + (s>>23) :     9 + (e>>23))
	append!(bins,   73 + (s>>20) :    73 + (e>>20))
	append!(bins,  585 + (s>>17) :   585 + (e>>17))
	append!(bins, 4681 + (s>>14) :  4681 + (e>>14))

	# from BAM specification pdf
	#const MAX_BIN = div((1<<18)-1,7)
	# int i = 0, k;
	# --end;
	# list[i++] = 0;
	# for (k = 1 + (beg>>26); k <= 1 + (end>>26); ++k) list[i++] = k;
	# for (k = 9 + (beg>>23); k <= 9 + (end>>23); ++k) list[i++] = k;
	# for (k = 73 + (beg>>20); k <= 73 + (end>>20); ++k) list[i++] = k;
	# for (k = 585 + (beg>>17); k <= 585 + (end>>17); ++k) list[i++] = k;
	# for (k = 4681 + (beg>>14); k <= 4681 + (end>>14); ++k) list[i++] = k;
	# return i;
end

# Input, 1-based, closed interval
# returned bin indices are 0-based!!!
function reg2binranges(s::Int, e::Int)
	@assert s>0 && e>0 "Region coordinates must be positive integers."
	@assert s<=2^29 && e<=2^29 "Region coordinates must be <= 2^29."

	s = s-1 # 1-based to 0-based
	e = e-1 # 1-based to 0-based
	# Original implementation is for closed intervals (if we skip end--), so e is correct.

	UnitRange{Int}[             0 :               0,
	                  1 + (s>>26) :     1 + (e>>26),
	                  9 + (s>>23) :     9 + (e>>23),
	                 73 + (s>>20) :    73 + (e>>20),
	                585 + (s>>17) :   585 + (e>>17),
	               4681 + (s>>14) :  4681 + (e>>14)]
end

struct VirtualOffset
	o::UInt64
end
function VirtualOffset(coffset::Integer, uoffset::Integer)
	@assert 0<=coffset<(UInt64(2)^48-1) && 0<=uoffset<2^16
	VirtualOffset(UInt64(coffset)<<16 | uoffset)
end

coffset(v::VirtualOffset) = v.o>>16
uoffset(v::VirtualOffset) = v.o & (1<<16-1)

# allow adding to virual offset as long as we stay within the same block
function +(v::VirtualOffset, i::Integer)
	@assert i>=0
	@assert uoffset(v)+i < (1<<16)
	VirtualOffset( v.o + i )
end

isless(u::VirtualOffset, v::VirtualOffset) = u.o<v.o

function print(io::IO, v::VirtualOffset)
	# print(io, "0x", hex(v.o,16))
	print(io, "c=0x", hex(coffset(v),12), ":u=0x", hex(uoffset(v),4))
end
show(io::IO, v::VirtualOffset) = print(io,v)

struct Chunk
	s::VirtualOffset # start
	e::VirtualOffset # end
end
function Chunk(is::IO)
	s = VirtualOffset(read(is,UInt64))
	e = VirtualOffset(read(is,UInt64))
	Chunk(s,e)
end

# define a total order of chunks
isless(a::Chunk, b::Chunk) = a.s<b.s || (a.s==b.s && a.e<b.e)

function print(io::IO, chunk::Chunk)
	#print(io, "Chunk(0x", hex(chunk.s,16), "-0x", hex(chunk.e,16), ")")
	print(io, "Chunk(", chunk.s, "-", chunk.e, ")")
end
show(io::IO, chunk::Chunk) = print(io,chunk)

mutable struct Bin
	bin::UInt # distinct bin - TODO: remove? store as key in Bin Dict only.
	chunks::Vector{Chunk}
end
function Bin(is::IO)
	bin = UInt( read(is,UInt32) )

	nChunks = Int(read(is,Int32))
	chunks = Vector{Chunk}(undef,nChunks)

	for i=1:nChunks
		chunks[i] = Chunk(is)
	end

	Bin(bin,chunks)
end

function print(io::IO, bin::Bin)
	print(io, "Bin(", Int64(bin.bin), ", ", bin.chunks, ")")
end
show(io::IO, bin::Bin) = print(io,bin)

# BamIndex for a single reference
mutable struct BamIndexRef
	bins::Dict{Int,Bin}
	linearIndex::Vector{VirtualOffset}
end

function BamIndexRef(is::IO)
	nBins = Int(read(is,Int32))
	bins = Dict{Int,Bin}()

	for i=1:nBins
		b = Bin(is)
		bins[b.bin] = b
	end

	nIntervals = Int(read(is,Int32))
	linearIndex = reinterpret(VirtualOffset, read!(is,Vector{UInt64}(undef,nIntervals)))

	BamIndexRef(bins,linearIndex)
end

mutable struct BamIndex
	refs::Vector{BamIndexRef}
	nbrNoCooord::UInt64
end
BamIndex() = BamIndex(Vector{BamIndexRef}(),0) # empty bam index

isempty(index::BamIndex) = length(index.refs)==0 && index.nbrNoCooord==0

function BamIndex(is::IO)
	magic = UInt32('B') | UInt32('A')<<8 | UInt32('I')<<16 | UInt32(1)<<24
	magicRead = read(is,UInt32)

	@assert magicRead == magic "Corrupt BAI file, magic string doesn't match."

	nRef = Int(read(is,Int32))
	refs = Vector{BamIndexRef}(undef,nRef)

	for i=1:nRef
		refs[i] = BamIndexRef(is)
	end

	nbrNoCooord = UInt64(0)
	if !eof(is)
		# handle n_no_coor if it is available
		nbrNoCooord = read(is,UInt64)
	end

	BamIndex(refs,0)
end
function BamIndex(filename::AbstractString)
	is = open(filename)
	bi = BamIndex(is)
	close(is)
	bi
end

function tryloadindex(bamFilename::AbstractString)
	bai = bamFilename * ".bai" # try to load "filename.bam.bai"
	!isfile(bai) && (bai = splitext(bamFilename)[1] * ".bai") # try to load "filename.bai"
	!isfile(bai) && return BamIndex() # neither found - return empty index
	BamIndex(bai) # load index
end

mutable struct ChunkQueueSingle
	index::BamIndexRef
	binRange::UnitRange{Int}
	currBin::Int
	currChunk::Int
end

function next!(q::ChunkQueueSingle)
	q.currChunk += 1

	#while !isempty(q) && q.currChunk>length(q.index.bins[q.currBin].chunks)
	while !isempty(q) &&
	      (!haskey(q.index.bins,q.binRange[q.currBin]) ||
	       q.currChunk>length(q.index.bins[q.binRange[q.currBin]].chunks))
		q.currBin += 1
		q.currChunk = 1
	end
	q
end

function ChunkQueueSingle(index::BamIndexRef, binRange::UnitRange{Int})
	q = ChunkQueueSingle(index,binRange,1,0) # start before first
	next!(q) # move to next
end

isempty(q::ChunkQueueSingle) = q.currBin>length(q.binRange)

function shift!(q::ChunkQueueSingle)
	ret = q.index.bins[q.binRange[q.currBin]].chunks[q.currChunk] # TODO: avoid index[currBin] every iteration, unnecessary lookup.
	next!(q)
	ret
end

mutable struct ChunkQueue
	queues::Vector{ChunkQueueSingle}
	pq::PriorityQueue{Int,Chunk} # bin level -> Chunk (the bin level is the index in array of single queues)

	function ChunkQueue(queues::Vector{ChunkQueueSingle}, pq::PriorityQueue{Int,Chunk})
		@assert length(queues)==6 "Incorrect number of bin levels."
		for i=1:length(queues)
			isempty(queues[i]) || (pq[i] = shift!(queues[i]))
		end
		new(queues,pq)
	end
end

ChunkQueue(queues::Vector{ChunkQueueSingle}) = ChunkQueue(queues,PriorityQueue(Int,Chunk))
ChunkQueue(index::BamIndexRef, binRanges::Vector{UnitRange{Int}}) = ChunkQueue(map(x->ChunkQueueSingle(index,x), binRanges))
ChunkQueue(index::BamIndexRef, region::UnitRange{Int}) = ChunkQueue(index,reg2binranges(region[1], region[end]))
ChunkQueue(index::BamIndex, refID::Int, region::UnitRange{Int}) = ChunkQueue(index.refs[refID+1], reg2binranges(region[1], region[end]))

isempty(q::ChunkQueue) = isempty(q.pq)

function shift!(q::ChunkQueue)
	(binLevel, chunk) = peek(q.pq)
	dequeue!(q.pq)

	# println("binLevel: ", binLevel, ", chunk: ", chunk)

	# add next chunk from this queue (if there is one)
	isempty(q.queues[binLevel]) || (q.pq[binLevel] = shift!(q.queues[binLevel]))

	chunk
end


text:
using LinearAlgebra: svd, svdvals, cond, pinv, I, diagm, norm
using Statistics
using Distributions, TransformVariables
using Random
using JLD

include("../../../src/PotentialUQ.jl")

######################################################
##################### Setup ##########################
######################################################

ϵ = 1.0
σ = 1.0
Temp = 0.25
seed = 10
ljtrue = PotentialUQ.Potentials.LennardJones(ϵ, σ)

## Set up training and test data
num_configs = 50
r_train = Vector{PotentialUQ.Potentials.Configuration}(undef, num_configs)
for j = 1:num_configs
    file_path = "examples/Argon7/DATA_training/TEMP_$(Int(100*Temp))/seed_$seed/DATA.$(5*1000*j)"
    c = PotentialUQ.Potentials.Configuration(file_path; atom_names = [:Ar],
                    radii = [3.4], weights = [1.0])
    r_train[j] = c
end

seed = 20
num_configs_test = 50
r_test = Vector{PotentialUQ.Potentials.Configuration}(undef, num_configs_test)
for j = num_configs+1:num_configs+num_configs_test
    file_path = "examples/Argon7/DATA_training/TEMP_$(Int(100*Temp))/seed_$seed/DATA.$(5*1000*j)"
    c = PotentialUQ.Potentials.Configuration(file_path; atom_names = [:Ar],
                    radii = [3.4], weights = [1.0])
    r_test[j-num_configs] = c
end

etrain = PotentialUQ.Potentials.potential_energy(r_train, ljtrue)
etest = PotentialUQ.Potentials.potential_energy(r_test, ljtrue)

ftrain = PotentialUQ.Potentials.force(r_train, ljtrue)
ftest = PotentialUQ.Potentials.force(r_test, ljtrue)

vtrain = PotentialUQ.Potentials.virial(r_train, ljtrue)
vtest = PotentialUQ.Potentials.virial(r_test, ljtrue)

######################################################
##################### UQ #############################
######################################################
# Unknowns

ϵ = 0.9
σ = 1.1
lj_train = PotentialUQ.Potentials.LennardJones(ϵ, σ)
nt = (ϵ = ϵ, σ = σ)
t = PotentialUQ.namedtp_to_vec(nt)
x = TransformVariables.inverse(t, nt)

# # Prior
function sampler(rng::Random.AbstractRNG, d::ContinuousMultivariateDistribution)
    x1 = 0.5+rand()
    x2 = 0.5+rand()
    return [x1, x2]
end
logpdf(x::Vector) = loglikelihood(Uniform(0.5, 1.5), x[1]) + loglikelihood(Uniform(0.5, 1.5), x[2])
lj_prior = PotentialUQ.LJ_Prior_Distribution(r_train, x, t, sampler, logpdf)

function lj_likelihood(x::Vector)
    lj_temp = PotentialUQ.Potentials.LennardJones(x[1], x[2])
    ehat = PotentialUQ.Potentials.potential_energy(r_train, lj_temp)
    fhat = PotentialUQ.Potentials.force(r_train, lj_temp)
    vhat = PotentialUQ.Potentials.virial(r_train, lj_temp)

    error = 0.5*sqrt(mean( (ehat - etrain).^2 ))
    ff = vcat( (fhat - ftrain)... )
    error += 0.5* mean( norm.(ff) )
    error += 0.5*sqrt( mean( (vhat - vtrain).^2 ) )
    return -error
end

println("prior = ", logpdf(x))
println("Likelihood = ", lj_likelihood(x))

dlj = PotentialUQ.PotentialDistribution(lj_train, nt, lj_prior, lj_likelihood)

@time chain, samp = PotentialUQ.Sample(dlj; return_chain = true, num_samples = 1000, num_adapts = 500, verbose = true)

# corner(chain)

save("examples/Argon7/lj_estimation/samples_lj_TEMP_$(Int(100*Temp)).jld", "samples", samp, "map", dlj.x)


text:
# Note that this script can accept some limited command-line arguments, run
# `julia build_tarballs.jl --help` to see a usage message.
using BinaryBuilder, Pkg

name = "LAZperf"
version = v"2.1.0"

# Collection of sources required to complete build
sources = [
    ArchiveSource("https://github.com/hobu/laz-perf/archive/refs/tags/$version.tar.gz", "0ea01f37dfa0e623d64846a58c3c2f0e77f8b17b9b8ba5721c3abcdbe14ac2d5"),
    DirectorySource("./bundled")
]

# Bash recipe for building across all platforms
script = raw"""

cd $WORKSPACE/srcdir/laz-perf-*

if [[ "${target}" == *-mingw* ]]; then
    atomic_patch -p1 ${WORKSPACE}/srcdir/patches/mingw-portable-endian.patch
fi

cmake . \
-DCMAKE_INSTALL_PREFIX=$prefix \
-DCMAKE_TOOLCHAIN_FILE=${CMAKE_TARGET_TOOLCHAIN} \
-DCMAKE_BUILD_TYPE=Release \
-DEMSCRIPTEN=OFF \
-DWITH_TESTS=OFF

make -j${nproc}
make install

"""

# These are the platforms we will build for by default, unless further
# platforms are passed in on the command line
platforms = expand_cxxstring_abis(supported_platforms(; experimental=true))

# The products that we will ensure are always built
products = [
    LibraryProduct("liblazperf", :liblazperf)
]

# Dependencies that must be installed before this package can be built
dependencies = Dependency[]

# Build the tarballs, and possibly a `build.jl` as well.
build_tarballs(ARGS, name, version, sources, script, platforms, products, dependencies; julia_compat="1.6")

max_stars_repo_name: sharanry/Yggdrasil

max_issues_repo_name: sharanry/Yggdrasil

max_forks_repo_name: sharanry/Yggdrasil


text:
abstract type AbstractBranchingRule end
abstract type AbstractVariableBranchingRule <: AbstractBranchingRule end
struct MostInfeasible <: AbstractVariableBranchingRule end
struct PseudocostBranching <: AbstractVariableBranchingRule end
mutable struct StrongBranching <: AbstractVariableBranchingRule
    μ::Real
    StrongBranching(; μ::Real = 1 / 6) = new(μ)
end

@enum WarmStartStrategy NO_WARM_STARTS WARM_START_WHEN_BACKTRACKING WARM_START_WHENEVER_POSSIBLE
@enum ModelReuseStrategy NO_MODEL_REUSE REUSE_MODEL_ON_DIVES USE_SINGLE_MODEL
@enum FormulationTighteningStrategy STATIC_FORMULATION TIGHTEN_WHEN_REBUILDING TIGHTEN_AT_EACH_NODE

# NOTE: This is not a true configurable parameter; it should really only be
# changed for debugging.
const _SILENT_LP_SOLVER = true

function _default_lp_solver_factory(state, config)
    model = Gurobi.Optimizer(state.gurobi_env)
    # TODO: Rather than have factory as a configurable parameter, can probably
    # just get by with making `silence_lp_solver::Bool` a parameter.
    MOI.set(model, MOI.Silent(), _SILENT_LP_SOLVER)
    MOI.set(model, MOI.RawParameter("Method"), 1)
    MOI.set(model, MOI.RawParameter("Presolve"), 0)
    # TODO: Rather than set this parameter, we could instead handle the
    # INF_OR_UNBD case directly. However, this might require resolving
    # some node LPs, which is a bit tricky to do in the current design.
    MOI.set(model, MOI.RawParameter("DualReductions"), 0)
    MOI.set(model, MOI.RawParameter("InfUnbdInfo"), 1)
    return model
end
const DEFAULT_LP_SOLVER_FACTORY = _default_lp_solver_factory
const DEFAULT_SILENT = false
const DEFAULT_BRANCHING_RULE = MostInfeasible()
const DEFAULT_TIME_LIMIT_SEC = Inf
const DEFAULT_NODE_LIMIT = 10_000_000
const DEFAULT_GAP_TOL = 1e-4
const DEFAULT_INTEGRALITY_TOL = 1e-5
const DEFAULT_WARM_START_STRATEGY = WARM_START_WHEN_BACKTRACKING
const DEFAULT_MODEL_REUSE_STRATEGY = REUSE_MODEL_ON_DIVES
# TODO: Change this default to TIGHTEN_WHENEVER_POSSIBLE
const DEFAULT_FORMULATION_TIGHTENING_STRATEGY = TIGHTEN_WHEN_REBUILDING
const DEFAULT_ACTIVITY_METHOD = DisjunctiveConstraints.IntervalArithmetic()

Base.@kwdef mutable struct AlgorithmConfig{B<:AbstractBranchingRule}
    lp_solver_factory::Function = DEFAULT_LP_SOLVER_FACTORY
    silent::Bool = DEFAULT_SILENT
    branching_rule::B = DEFAULT_BRANCHING_RULE
    time_limit_sec::Float64 = DEFAULT_TIME_LIMIT_SEC
    node_limit::Int = DEFAULT_NODE_LIMIT
    gap_tol::Float64 = DEFAULT_GAP_TOL
    int_tol::Float64 = DEFAULT_INTEGRALITY_TOL
    warm_start_strategy::WarmStartStrategy = DEFAULT_WARM_START_STRATEGY
    model_reuse_strategy::ModelReuseStrategy = DEFAULT_MODEL_REUSE_STRATEGY
    formulation_tightening_strategy::FormulationTighteningStrategy =
        DEFAULT_FORMULATION_TIGHTENING_STRATEGY
    # TODO: Unit test this parameter
    activity_method::DisjunctiveConstraints.AbstractActivityMethod =
        DEFAULT_ACTIVITY_METHOD
end


text:
using Flux, XConv, BSON, IterTools
using Flux: onecold, logitcrossentropy, @epochs
using CUDA
using Parameters: @with_kw
using Distributed

addprocs(length(devices()))
@everywhere using CUDA, BSON, XConv, Flux
@everywhere using Flux: onecold, logitcrossentropy, @epochs
@everywhere using Parameters: @with_kw

@everywhere CUDA.unsafe_free!(h::Flux.OneHotMatrix) = CUDA.unsafe_free!(h.data)

cd(dirname(@__FILE__))

wp = default_worker_pool()

if CUDA.has_cuda()
    @everywhere device = gpu
    @everywhere CUDA.allowscalar(false)
    @everywhere iterator = CuIterator
    @info "Training on GPU"
else
    @everywhere iterator = ()
    @everywhere device = cpu
    @info "Training on CPU"
end

@everywhere include("./datautils.jl")
@everywhere include("./modelutils.jl")

@everywhere @with_kw mutable struct Args
    name::String = "MNIST"
    batchsize::Int = 128
    η::Float64 = 3e-3
    epochs::Int = 20
    splitr_::Float64 = 0.1
    probe_size::Int = 8
    mode::String = "TrueGrad"
    savepath::String = "./$(name)_bench"
end

@everywhere function accuracy(test_data, m)
    correct, total = 0, 0
    for (x, y) in iterator(test_data)
        correct += sum(onecold(cpu(m(x)), 0:9) .== onecold(cpu(y), 0:9))
        total += size(y, 2)
    end
    test_accuracy = correct / total
    test_accuracy
end

@everywhere augment(x) = x .+ device(0.1f0*randn(eltype(x), size(x)))
@everywhere filename(args) = joinpath(args.savepath, "$(args.name)_conv_$(args.mode)_$(args.batchsize)_$(args.probe_size).bson")

@everywhere function train(; kws...)
    # Initialize the hyperparameters
    args = Args(; kws...)
    isfile(filename(args)) && return
    # Load the train, validation data
    train_data, val_data = get_train_data(args)
    test_data = get_test_data(args)

    @info("Constructing Model")
    # Defining the loss and accuracy functions
    m = build_model(args.name) |> device
    loss(x, y) = logitcrossentropy(m(x), y)

    @info("Training $(args.name) with batch size $(args.batchsize)")
    args.mode == "TrueGrad" ? @info("Mode: $(args.mode)") : @info("Mode: $(args.mode), probing vectors: $(args.probe_size)")
    lhist = []

    # Defining the optimizer
    opt = ADAM(args.η)
    ps = Flux.params(m)

    # Initialize gradient mode
    XConv.initXConv(args.probe_size, args.mode)
    # Starting to train models
    for epoch in 1:args.epochs
        Base.flush(Base.stdout)
        local l
        for (x, y) in iterator(train_data)
            gs = Flux.gradient(ps) do
                l = loss(x, y)
                l
            end
            Flux.update!(opt, ps, gs)
            push!(lhist, l)
        end

        validation_loss = 0f0
        for (x, y) in iterator(val_data)
            validation_loss += loss(x, y)
        end
        validation_loss /= length(val_data)
        acc = accuracy(val_data, m)
        @info "Epoch $epoch validation with ($(args.mode), $(args.probe_size)) loss = $(validation_loss), accuracy = $(acc)"
    end
    acc = accuracy(test_data, m)
    BSON.@save filename(args) params=cpu.(params(m)) acc lhist
    GC.gc()
end

datasets = ["MNIST", "CIFAR10"]

b_sizes = [2^i for i=5:10]
ps_sizes = [0..., [2^i for i=1:6]...]

# assign devices
asyncmap((zip(workers(), devices()))) do (p, d)
    remotecall_wait(p) do
        @info "Worker $p uses $d"
        device!(d)
    end
end

pw = default_worker_pool()

@sync for d in datasets
    for b in b_sizes
        for ps in ps_sizes
	    η = d == "CIFAR10" ? 3e-4 : 3e-3
            @async remotecall_fetch(train, pw;η=η, epochs=20,batchsize=b, probe_size=ps, name=d, mode= ps>0 ? "EVGrad" : "TrueGrad")
        end
    end
end

max_stars_repo_name: sheevy/XConv

max_issues_repo_name: sheevy/XConv

max_forks_repo_name: sheevy/XConv


text:
using Test
using ForwardDiff
using Rotations
include("./BEMUtils.jl")

function primitive(x, h, r)
  η = sqrt(h^2 + r^2 * x^2 + x^2)
  # return x * log(η / sqrt(h^2 + x^2) + r * x / sqrt(h^2 + x^2)) -
  # 1/2 * h * atan((h * (η^2 - r^3 * x * η)) / ((r^2 * (x^2 + h^2) - η^2) * η^2 - h^2 * r^4 * x^2))

  return x * log(η / sqrt(h^2 + x^2) + r * x / sqrt(h^2 + x^2)) -
  1/2 * h * angle((r^2 - 1) * h^2 - (r^2 + 1) * x^2 + im * 2 * h *r * η)

end

function deriv(x, h, r)
  return log(sqrt(1 + r^2 * x^2 / (x^2 + h^2)) + r * x / sqrt(x^2 + h^2))
end

function grad_primitive(x, h, r)
  return ForwardDiff.derivative(x -> primitive(x, h, r), x)
end

function ∫Φ_rectangle_numeric(a, b, h)
  Φ(xy) = 1/sqrt(xy[1]^2 + xy[2]^2 + h^2)
  cb_result = hcubature(Φ, (0.0,0.0), (a,b))
  return cb_result[1]
end

function ∫Φ_rectangle(a, b, h)
  return ∫Φ_right_angle(a, b, h) + ∫Φ_right_angle(b, a, h)
end

function ∫Φ_right_angle_test()
  a, b, h = rand(3)
  # @show ∫Φ_rectangle_numeric(a, b, h) - ∫Φ_rectangle(a, b, h)
  return ∫Φ_rectangle_numeric(a, b, h) ≈ ∫Φ_rectangle(a, b, h)
end

function ∫Φ_general_angle_test()
  a, b, d, h = rand(4) .- 0.5
  a⃗ = SVector(a, d)
  α⃗ = SVector(a, 0.)
  b⃗ = SVector(b, d)
  β⃗ = SVector(b, 0.)

  return abs(∫Φ_rectangle_numeric(abs(a), abs(d), h) -
             sign(a * b) * ∫Φ_rectangle_numeric(abs(b), abs(d), h)) ≈
         abs(sign(a * b) * ∫Φ_general_angle(α⃗, a⃗, h) -
             ∫Φ_general_angle(b⃗, β⃗, h)) +
         ∫Φ_general_angle(a⃗, b⃗, h)
end

function ∫Φ_square_test()
  c1, c2, h = rand(3) .-0.5; d = rand()
  c1 *= 4; c2 *= 4
  c⃗ = SVector(c1, c2)

  Φ(xy) = 1/sqrt(xy[1]^2 + xy[2]^2 + h^2)
  cb_result = hcubature(Φ, (c1 - d/2, c2 - d/2), (c1 + d/2, c2 + d/2))
  cb_result[1]
  ∫Φ_square(c⃗, d, h)
  return ∫Φ_square(c⃗, d, h) ≈ cb_result[1]
end

function matrix_element_point_scaling_test()
  d = rand()
  v_point = rand(3)
  v_scaling = rand(3)
  O = rand(RotMatrix{3})
  point = Point(v_point)
  scaling = rotate(HaarScaling(d, v_scaling), O)

  @show constructMatrixElement(point, scaling)
  @show constructMatrixElement_numeric(point, scaling)

  return constructMatrixElement(point, scaling) ≈ constructMatrixElement_numeric(point, scaling)
end

function matrix_element_scaling_scaling_test()
  d1, d2 = rand(), rand()
  v1, v2 = rand(3), rand(3)
  O1, O2 = rand(RotMatrix{3}), rand(RotMatrix{3})
  e1 = rotate(HaarScaling(d1, v1), O1)
  e2 = rotate(HaarScaling(d2, v2), O2)

  @show constructMatrixElement(e1, e2)
  @show constructMatrixElement_numeric(e1, e2)
  return constructMatrixElement(e1, e2) ≈ constructMatrixElement_numeric(e1, e2)
end

@test ∫Φ_right_angle_test()
@test ∫Φ_general_angle_test()
@test ∫Φ_square_test()
@test matrix_element_point_scaling_test()
@test matrix_element_scaling_scaling_test()


text:
using KissMCMC
import Distributions, StatsBase
using Parameters: @unpack
const D = Distributions
const SB = StatsBase
using Test, Statistics

std2(x) = sqrt.(var(x)) # works in multi dims

"""
Struct to hold a test-case for MCMC sampling
"""
Base.@kwdef struct ATest
    dist # a Distribution dist or a logpdf function
    dim = length(mean(dist))
    mean_ = mean(dist)
    median_ = dim==1 ? median(dist) : nothing
    std_ = std2(dist)
    skewness_ = dim==1 ? D.skewness(dist) : nothing #
    theta0 = 0.0
    ball_radius = 0.1
    nwalkers = 100
    niter = 10^4
    hasblob = false
    sample_ppdf = theta -> randn() + theta
    tole = 0.3
    tolm = 0.3
    otherkws = Dict{Symbol,Any}()
    blob_truths = nothing
    squash_walkers_kws = Dict{Symbol,Any}()
end

# helpers
function test_mean_std(thetas, atest::ATest, tol)
    @unpack mean_, std_, skewness_, median_ = atest
    @show atest.dist
    mean_!=nothing && @test all(abs.(mean(thetas) .- mean_) .< abs.(std_ * tol))
    std_!=nothing && @test all(abs.(std(thetas) - std_) .< abs.(std_ * tol))
    median_!=nothing && @test abs.(median(thetas) - median_) < abs.(std_ * tol)
    skewness_!=nothing && @test abs.(SB.skewness(thetas) - skewness_) < abs.(std_ * 2*tol)
end
function test_blobs(blob_truths, blobs)
    blob_truths==nothing && return nothing
    @test blob_truths==blobs
end
function test_logdensities(samples, logdensities, pdf)
    nothing
end

testcases = [
    ATest(dist = D.Normal(-5.0, 3.0),
          theta0=-4.0,
          sample_ppdf = theta -> 9*randn() + theta,
          ),
    ATest(dist = D.LogNormal(0.0,1.0),
          theta0 = 0.4,
          sample_ppdf = theta -> 7.5*randn() + theta,
          niter = 10^7,
          tolm = 0.4),
    ATest(dist = D.MvNormal([0.5,-0.25], [0.47 1.8
                                          1.8 7.]), # 2D normal dist
          theta0 = [0.4, 0.3],
          sample_ppdf = theta -> 0.5*randn(2) .+ theta,
          niter = 10^5,
          ),
    ATest(dist =  x-> -(100*(x[2] - x[1]^2)^2 + (1 - x[1])^2 ) / 20, # Rosenbrock
          dim = 2,
          mean_ = [0.98, 10.3], # from running emcee with niter=10^9
          median_ = nothing,
          std_ = [3.1, 13.8],
          skewness_ = nothing,
          theta0 = [0.0, 0.0],
          niter = 10^7,
          sample_ppdf = theta -> 0.5*randn(2) .+ theta,
          tolm = 0.6,
          tole = 0.6),
    # tests with blobs
    ATest(dist = x -> (-(x+5)^2/(2*3.0^2), ones(1000)), # a blob, default reductions
          dim = 1,
          median_ = -5.0,
          mean_ = -5.0,
          std_ = 3.0,
          skewness_ = nothing,
          theta0=-4.0,
          hasblob=true,
          sample_ppdf = (theta -> 9*randn() + theta),
          nwalkers = 100,
          niter = 10^4,
          blob_truths = [ones(1000) for i=1:10^4÷2]
          ),
    ATest(dist = x -> (-(x+5)^2/(2*3.0^2), ones(1000)), # a blob
          dim = 1,
          median_ = -5.0,
          mean_ = -5.0,
          std_ = 3.0,
          skewness_ = nothing,
          theta0=-4.0,
          hasblob=true,
          sample_ppdf = (theta -> 9*randn() + theta),
          otherkws=Dict(:init_blobs => (blob0, nsamples) -> [0],
                        :reduce_blob! => (blobs, blob) -> blobs[1] += blob[1]), # use the sum as blob-reduction
          squash_walkers_kws = Dict(:merge_blobs! => (blobs1, blobs2) -> blobs1[1] += blobs2[1]),
          blob_truths = [10^4÷2]
          )
]

make_lpdf(dist::D.Distribution) = x -> D.logpdf(dist, x)
make_lpdf(dist) = dist

## run tests
include("metro.jl")
include("emcee.jl")


text:
using TriangleMesh
using Plots
using Triplot
using LinearAlgebra
using SparseArrays
using ForwardDiff
using UnPack  # for convenience @unpack macro
include("./TriFEMUtils.jl") # plotting and misc routines

poly = polygon_unitSquare()
# poly = polygon_regular(5)
poly = polygon_Lshape()
num_refinements = 3
max_triangle_area = .05/(4^num_refinements)
mesh = create_mesh(poly, quality_meshing=true,
                   add_switches="penva"*string(max_triangle_area)*"q") # switches

# new problem
f(x,y) = exp(sin(1+pi*x)*sin(pi*y))
on_Neumann(x,y)   = x ≈ 1 && y > 0 && y < .5 # right face x = 1 (excluding corners)
on_Dirichlet(x,y) = !on_Neumann(x,y) # Dirichlet boundary = everywhere else
u_Dirichlet(x,y)  = 0.0
∇u_dot_n(x,y)     = 0.0 # note that n = [1,0] on the Neumann face
u0(x,y) = sin(pi*x)*sin(pi*y)

# ordering of reference element vertices
# 3
# |`.
# 1--2
reference_vertices = [[-1,1,-1],[-1,-1,1]] # stored as [r,s]
reference_face_indices = [[1,2],[2,3],[1,3]] # ordering of faces for the reference element
ref_elem_info = (;reference_face_indices,reference_vertices)

# define reference basis functions
λ1(r,s) = -(r+s)/2
λ2(r,s) = (1+r)/2
λ3(r,s) = (1+s)/2
λ(r,s) = [λ1.(r,s) λ2.(r,s) λ3.(r,s)]
dλr() = [-.5 .5 0.0]
dλs() = [-.5 0.0 .5]

# x,y = lists of vertices
function compute_geometric_terms(x,y)
    # dx(r,s)/dr = dλ1/dr*x1 + dλ2/dr*x2 + dλ3/dr*x3 = [dλ1/dr dλ2/dr dλ3/dr] * [x1; x2; x3]
    dxdr,dydr = dλr()*x, dλr()*y
    dxds,dyds = dλs()*x, dλs()*y
    G = [dxdr dxds; dydr dyds] # G*r = x, r = inv(G)*x
    J = det(G) # change of variables det(Jacobian) for integration
    drdx, dsdx, drdy, dsdy = inv(G)
    return J, drdx, dsdx, drdy, dsdy
end

# assemble stiffness matrix and RHS vector
function assemble_FE_matrix(mesh)
    VX,VY,EToV = unpack_mesh_info(mesh)
    num_vertices = length(VX)
    num_elements = size(EToV,2) # number of elements = of columns

    # rq,sq,wq = 1/3,1/3,2.0
    rq,sq,wq = [-2/3; 1/3; -2/3], [-2/3; -2/3; 1/3], 2/3 * ones(3) # 3 point rule - Gockenbach

    A = spzeros(num_vertices, num_vertices)
    M = spzeros(num_vertices, num_vertices)
    b = zeros(num_vertices)
    for e = 1:num_elements # loop through all elements
        ids = EToV[:,e] # vertex ids = local to global index maps
        xv,yv = VX[ids],VY[ids]

        # compute geometric mappings
        J,drdx,dsdx,drdy,dsdy = compute_geometric_terms(xv,yv)
        dλdx = drdx*dλr() + dsdx*dλs() # dλr() = [dλ1/dr dλ2/dr dλ3/dr]
        dλdy = drdy*dλr() + dsdy*dλs() # dλs() = [dλ1/ds dλ2/ds dλ3/ds]
        reference_elem_area = 2.0
        @. A[ids,ids] += J*reference_elem_area*(dλdx'*dλdx + dλdy'*dλdy) # (dλdx'*dλdx)_ij = dλj/dx * dλi/dx

        # assemble mass matrix using quadrature: ∫ϕ_j * ϕ_i = integrals of quadratic
        M[ids,ids] .+= J*reference_elem_area*(λ(rq,sq)'*Diagonal(wq)*λ(rq,sq)) # M = V^T * diag(weights) * V

        # quadrature rule
        xq,yq = map_triangle_pts(rq,sq,xv,yv)
        b[ids] .+= J*λ(rq,sq)'*(wq.*f.(xq,yq))
    end
    return M,A,b
end

function compute_Neumann_BCs(mesh,ref_elem_info,on_Neumann_boundary,∇u_dot_n)

    @unpack reference_face_indices, reference_vertices = ref_elem_info
    VX,VY,EToV = unpack_mesh_info(mesh)
    boundary_indices, boundary_faces = get_boundary_info(reference_face_indices, mesh)
    # contributions from Neumann BCs

    num_vertices = length(VX)
    b = zeros(num_vertices)
    for (f,e) in boundary_faces
        ref_fids = reference_face_indices[f]
        fids = EToV[ref_fids,e]
        xf,yf = VX[fids],VY[fids]
        x_mid,y_mid = sum(xf)/2,sum(yf)/2

        if on_Neumann_boundary(x_mid,y_mid)
            r,s = reference_vertices
            r_mid, s_mid = sum(r[ref_fids])/2, sum(s[ref_fids])/2
            w_mid = 2.0

            ids = EToV[:,e]
            face_length = sqrt((xf[1]-xf[2])^2 + (yf[1]-yf[2])^2)
            b[ids] .+= face_length/2 * vec(λ(r_mid,s_mid)) * w_mid * ∇u_dot_n(x_mid,y_mid) # ∫ ∇u⋅n ϕ_i on each Neumann face
        end
    end
    return b
end
function modify_matrix_Dirichlet_BCs!(A,mesh,ref_elem_info,on_Dirichlet_boundary)
    @unpack reference_face_indices, reference_vertices = ref_elem_info
    VX,VY,EToV = unpack_mesh_info(mesh)
    boundary_indices, boundary_faces = get_boundary_info(reference_face_indices, mesh)

    # impose Dirichlet BCs
    for i in boundary_indices
        xi,yi = VX[i],VY[i]
        if on_Dirichlet_boundary(xi,yi)
            A[:,i] .= 0
            A[i,:] .= 0
            A[i,i] = 1.0
        end
    end
end
function compute_Dirichlet_BCs(A,mesh,ref_elem_info,on_Dirichlet_boundary,u_Dirichlet)
    @unpack reference_face_indices, reference_vertices = ref_elem_info
    VX,VY,EToV = unpack_mesh_info(mesh)
    boundary_indices, boundary_faces = get_boundary_info(reference_face_indices, mesh)

    num_vertices = length(VX)
    b = zeros(num_vertices)
    # impose Dirichlet BCs
    for i in boundary_indices
        xi,yi = VX[i],VY[i]
        if on_Dirichlet_boundary(xi,yi)
            b -= Vector(A[:,i]*u_Dirichlet(xi,yi))
        end
    end
    return b
end
# modifies the arguments
function constrain_Dirichlet_nodes!(b,mesh,ref_elem_info,on_Dirichlet_boundary,u_Dirichlet)
    @unpack reference_face_indices, reference_vertices = ref_elem_info
    VX,VY,EToV = unpack_mesh_info(mesh)
    boundary_indices, boundary_faces = get_boundary_info(reference_face_indices, mesh)

    for i in boundary_indices
        xi,yi = VX[i],VY[i]
        if on_Dirichlet_boundary(xi,yi)
            b[i] = u_Dirichlet(xi,yi)
        end
    end
end

M,A,b = assemble_FE_matrix(mesh)

# set up timestepping parameters
Δt = .001
T = .5

# create/prefactor Crank-Nicolson matrix
C = (M + .5*Δt*A)
modify_matrix_Dirichlet_BCs!(C,mesh,ref_elem_info,on_Dirichlet)
C = cholesky(Symmetric(C)) # speed up solution of C\b

# precompute BC contributions
b_Neumann = compute_Neumann_BCs(mesh,ref_elem_info,on_Neumann,∇u_dot_n)
b_Dirichlet = compute_Dirichlet_BCs(M+.5*Δt*A,mesh,ref_elem_info,on_Dirichlet,u_Dirichlet)

Nsteps = ceil(T/Δt)
Δt = T/Nsteps
VX,VY,EToV = unpack_mesh_info(mesh)
u = u0.(VX,VY)
plot()
VX,VY,EToV = unpack_mesh_info(mesh) # for plotting
@gif for i = 1:Nsteps
    global u

    # compute RHS
    b = M*u - .5*Δt*A*u

    # compute BC contributions
    @. b += b_Neumann + b_Dirichlet # add BC contributions

    # modify b_i = u[i]
    constrain_Dirichlet_nodes!(b,mesh,ref_elem_info,on_Dirichlet,u_Dirichlet)

    u = C \ b

    if i%5==0
        println("on iter $i out of $Nsteps")
        triplot(VX,VY,u,EToV)
    end
end every 5

# triplot(VX,VY,uexact.(VX,VY),EToV)


text:
#############################################################################
# L_BFGS.jl
# Implement the L_BFGS method to solve convex optimization of the form:
# minimize f(x) + g(x), where f(x) is the Lovasz extension of a submodular funciton.
#############################################################################

export L_BFGS

function L_BFGS(p::Problem,                    # the convex problem
                f::LovaszExtAtom;              # the lovasz extension
                x₀::AbstractArray = collect(1:length(get_v(f)[1])),  # the starting point
                m::Int = length(get_v(f)[1]),  # the number of kept iterations
                c₁::Float64 = 0.7,             # linesearch parameter
                c₂::Float64 = 0.9,             # linesearch parameter
                μ::Float64 = 0.9,              # linesearch shrink rate
                epsilon::Float64 = 1e-3,       # the stopping criteria of the algorithm
                max_iters::Int = 100)          # the maximal iteration time

  if length(get_v(p.objective + f)) != 1
    error("Cannot optimize functions with multiple variables.")
  end

  x = x₀                                              # the candidate
  objective = p.objective + f
  var = get_v(f)[1]
  n = length(var)
  s = Array{AbstractArray}(m)                         # the differences between candidates of neighbouring iterations
  y = Array{AbstractArray}(m)                         # the differences between gradients candidates of neighbouring iterations
  α = Array{Number}(m)
  ρ = Array{Number}(m)
  r = AbstractArray                                   # quasi_gradient
  z = AbstractArray                                   # descent direction
  λ = 1.0                                             # step size
  λ̃ = 1.0                                             # the λ producing the largest gap satisfying the wolfe condition
  β = 0
  decr = 0.0                                          # the decrement
  gap = 0.0
  gap_upper = 0.0
  check = false
  grad_conv = grad(p.objective)
  obj(λ) = evaluate(objective, x + λ*z)[1]
  gra(λ) = evaluate(grad_conv, x + λ*z) + greedy(f.func, x + λ*z)
  q = evaluate(grad_conv, x) + greedy(f.func, x)

  for k = 0:max_iters
    # println("k = $k")
    # println("norm(q) = $(norm(q))")
    if k > 1
    end
    if norm(q) < epsilon
      return x
      break
    else
      # lev_tol = norm(q)/(n^0.5)*0.01                  # the tolerance for level sets
      if k == 0
        r = q
      elseif k < m
        H = (dot(s[k], y[k]) / dot(y[k], y[k])) * eye(n)
        for i = k:-1:1
          α[i] = ρ[i] * dot(s[i], q)
          q -= α[i] * y[i]
        end
        r = H * q
        for i = 1:k
          β = ρ[i] * dot(y[i], r)
          r += s[i] * (α[i] - β)
        end
      else
        k̃ = mod(k-1, m) + 1
        H = (dot(s[k̃], y[k̃]) / dot(y[k̃], y[k̃])) * eye(n)
        for i = k:-1:k-m+1
          ĩ = mod(i-1, m) + 1
          α[ĩ] = ρ[ĩ] * dot(s[ĩ], q)
          q -= α[ĩ] * y[ĩ]
        end
        r = H * q
        for i = (k-m+1):k
          ĩ = mod(i-1, m) + 1
          β = ρ[ĩ] * dot(y[ĩ], r)
          r += s[ĩ] * (α[ĩ] - β)
        end
      end
      z = -r
      λ = 1
      q = evaluate(grad_conv, x) + greedy(f.func, x)
      obj0 = obj(0)
      decr = dot(q, z)
      # println("x = $x")
      # println("q = $q")
      # println("z = $z")
      # println("decr = $decr")
      if abs(decr) < epsilon
        return x
        break
      end
      while obj(λ) > (obj0 + c₁ * λ * decr)
        if λ < 1e-2
          error("Line search fail to terminate")
          return x
        end
        # println("λ = $λ")
        # println("cond1 = $(obj(λ) - (obj0 + c₁ * λ * decr))")
  		  λ *= μ
  	  end
      while dot(gra(λ), z) < c₂ * decr
        if λ < 1e-2
          error("Line search fail to terminate")
          return x
        end
        # println("λ = $λ")
        # println("cond2 = $(dot(gra(λ), z) - c₂ * decr)")
  		  λ *= μ
      end
      # λ̃ = copy(λ)
      # check, gap = level_detector(x + λ*z, lev_tol)
      # gap_upper = gap
      # while check == true && dot(gra(λ), z) >= c₂ * decr
      #   if gap_upper < gap
      #     λ̃ = λ
      #     gap_upper = gap
      #   end
      #   λ *= μ
      #   # println(λ)
      #   check, gap = level_detector(x + λ*z, lev_tol)
      # end
      # if dot(gra(λ), z) < c₂ * decr                   # the wolfe condition is violated, pick the λ that produces the largest gap while satisfying the wolfe condition
      #   λ = λ̃
      # end
      # println()
      # println("λ = $λ")
      # println()
      x += λ * z
      k̃ = mod(k, m) + 1                              # update new entries
      s[k̃] = λ * z
      q_new = evaluate(grad_conv, x) + greedy(f.func, x)
      y[k̃] = q_new - q
      ρ[k̃] = 1 / dot(y[k̃], s[k̃])
      q = q_new
    end
  end
end

function level_detector(x::AbstractArray, lev_tol::Float64 = 1e-2)
  w = sort(x)
  gap = lev_tol                                       # the tightest gap
  check = false
  for i = 1:(length(x)-1)
    if w[i+1] - w[i] < gap
      gap = w[i+1] - w[i]
      check = true
    end
  end
  return check, gap
end


text:
# my first julia file
# - coded by Liang Zheng
# - 2020-01-25

# plot f(x,y)
using Plots;
x=[0:50];
x=convert(Array{Float32},x[1]);
y1=sin.(x);
y2=cos.(x);
y=[y1,y2];
plot(x,y1,label="sin");
plot!(x,y2,line=:dash,label="cos");
scatter!(x,y2,label="");
title!("my first Julia plot");
ylabel!("y");
xlabel!("x");

max_stars_repo_name: gassive/texJuliaCopyMatlab

max_issues_repo_name: gassive/texJuliaCopyMatlab

max_forks_repo_name: gassive/texJuliaCopyMatlab


text:
using Twitter, Test
using JSON, OAuth

# set debugging
ENV["JULIA_DEBUG"]=Twitter

twitterauth(ENV["CONSUMER_KEY"], ENV["CONSUMER_SECRET"], ENV["ACCESS_TOKEN"], ENV["ACCESS_TOKEN_SECRET"])

#get_mentions_timeline
mentions_timeline_default = get_mentions_timeline()
tw = mentions_timeline_default[1]
tw_df = DataFrame(mentions_timeline_default)
@test 0 <= length(mentions_timeline_default) <= 20
@test typeof(mentions_timeline_default) == Vector{Tweets}
@test typeof(tw) == Tweets
@test size(tw_df)[2] == 30

#get_user_timeline
user_timeline_default = get_user_timeline(screen_name = "randyzwitch")
@test typeof(user_timeline_default) == Vector{Tweets}

#get_home_timeline
home_timeline_default = get_home_timeline()
@test typeof(home_timeline_default) == Vector{Tweets}

#get_single_tweet_id
get_tweet_by_id = get_single_tweet_id(id = "434685122671939584")
@test typeof(get_tweet_by_id) == Tweets

#get_search_tweets
duke_tweets = get_search_tweets(q = "#Duke", count = 200)
@test typeof(duke_tweets) <: Dict

#test sending/deleting direct messages
#commenting out because Twitter API changed. Come back to fix
# send_dm = post_direct_messages_send(text = "Testing from Julia, this might disappear later $(time())", screen_name = "randyzwitch")
# get_single_dm = get_direct_messages_show(id = send_dm.id)
# destroy = post_direct_messages_destroy(id = send_dm.id)
# @test typeof(send_dm) == Tweets
# @test typeof(get_single_dm) == Tweets
# @test typeof(destroy) == Tweets

#creating/destroying friendships
add_friend = post_friendships_create(screen_name = "kyrieirving")

unfollow = post_friendships_destroy(screen_name = "kyrieirving")
unfollow_df = DataFrame(unfollow)
@test typeof(add_friend) == Users
@test typeof(unfollow) == Users
@test size(unfollow_df)[2] == 40

# create a cursor for follower ids
follow_cursor_test = get_followers_ids(screen_name = "twitter", count = 10_000)
@test length(follow_cursor_test["ids"]) == 10_000

# create a cursor for friend ids - use barackobama because he follows a lot of accounts!
friend_cursor_test = get_friends_ids(screen_name = "BarackObama", count = 10_000)
@test length(friend_cursor_test["ids"]) == 10_000

# create a test for home timelines
home_t = get_home_timeline(count = 2)
@test length(home_t) > 1

# TEST of cursoring functionality on user timelines
user_t = get_user_timeline(screen_name = "stefanjwojcik", count = 400)
@test length(user_t) == 400
# get the minimum ID of the tweets returned (the earliest)
minid = minimum(x.id for x in user_t);

# now iterate until you hit that tweet: should return 399
# WARNING: current versions of julia cannot use keywords in macros? read here: https://github.com/JuliaLang/julia/pull/29261
# eventually replace since_id = minid
tweets_since = get_user_timeline(screen_name = "stefanjwojcik", count = 400, since_id = 1001808621053898752, include_rts=1)

@test length(tweets_since)>=399

# testing get_mentions_timeline
mentions = get_mentions_timeline(screen_name = "stefanjwojcik", count = 300)
@test length(mentions) >= 50 #sometimes API doesn't return number requested (twitter API specifies count is the max returned, may be much lower)
@test Tweets<:typeof(mentions[1])

# testing retweets_of_me
my_rts = get_retweets_of_me(count = 300)
@test Tweets<:typeof(my_rts[1])


text:
"""
# module PHonon

# Examples

```julia
julia>
```
"""
module PHonon

using Crystallography: ReciprocalPoint
using Setfield: @set!

using ..Inputs: Card

import ..Inputs: VerbositySetter, groupname

export QPointsCard,
    PhInput,
    Q2rInput,
    MatdynInput,
    DynmatInput,
    PhNamelist,
    Q2rNamelist,
    MatdynNamelist,
    DynmatNamelist,
    VerbositySetter
export relayinfo

include("namelists.jl")

struct QPointsCard <: Card
    data::Vector{ReciprocalPoint}
end

include("inputs.jl")

end


text:
swap_node(x::AbstractNode, old::AbstractNode, new::AbstractNode) = x == old ? new : throw(KeyError(old))
swap_node(x, oldnew::Pair) = swap_node(x, oldnew...)
swap_node(x::T, old::Node, new::Node) where {T <: Union{ModifiedNode, ModifyingNode}} = T(swap_node(keep(x, Node), old, new), modifiers(x))
function swap_node(x::T, old, new) where {T <: Edge}
    if keep(x, Src) == old
        return T(swap_node(keep(x, Src), old, new), keep(x, Dst))
    elseif keep(x, Dst) == old
        return T(keep(x, Src), swap_node(keep(x, Dst), old, new))
    else
        throw(KeyError(old))
    end
end
swap_node(x::ModifiedEdge, old, new) = ModifiedEdge(swap_node(keep(x, Edge), old, new), modifiers(x))

swap_edge(x::AbstractEdge, old::AbstractEdge, new::AbstractEdge) = x == old ? new : throw(KeyError(old))
swap_edge(x, oldnew::Pair) = swap_edge(x, oldnew...)
swap_edge(x::ModifiedEdge, old::T, new::T) where {T <: Union{DirectedEdge, UndirectedEdge}} = ModifiedEdge(swap_edge(keep(x, Edge), old, new), modifiers(x))


text:
module Machines

export Machine, run_tape, read_instructions

using ..Utils: zero_based

## Instruction file parsing
"""
    read_instructions(io)

Read instructions from `io` which can be either a filename or an IOBuffer.
"""
read_instructions(io) = zero_based(parse_line.(readlines(io)))

function parse_line(line)
    f, args = split(line, limit=2)
    f = Symbol(f)
    args = parse.(Int, split(args, keepempty=false))
    return f, (args...,)
end

## Types
"""
# Summary
    mutable struct Machine <: Any

# Constructors
    Machine(accumulator, current_line, lines_visited, track)

    Machine(;
        accumulator::Int = 0,
        current_line::Int = 0,
        lines_visited::Vector{Int} = Int[],
        track::Bool = false,
    )

Machine to run instruction tape. Sorta like an intcode machine, but not intcode.
"""
Base.@kwdef mutable struct Machine
    accumulator::Int = 0
    current_line::Int = 0
    lines_visited::Vector{Int} = Int[]
    track::Bool = false
end

# Package up invalid instructions into a nice little error
struct InstructionError{N} <: Exception
    pos::Int
    op::Symbol
    args::NTuple{N,Int}
end

function Base.showerror(io::IO, e::InstructionError)
    arg_str = join([arg<0 ? string(arg) : "+"*string(arg) for arg in e.args], ' ')
    print(io, "InstructionError: Invalid instruction `$(e.op) $arg_str` at position $(e.pos)")
end

## Operations
# Add to accumulator
function acc!(machine, val)
    machine.accumulator += val
    jmp!(machine, 1)
    return machine.accumulator
end

# Jump to relative position
function jmp!(machine, val)
    machine.track && push!(machine.lines_visited, machine.current_line)
    machine.current_line += val
    return -1
end

# No op (do nothing)
function nop!(machine, val)
    jmp!(machine, 1)
    return -1
end

## Actually run things
"""
    run_tape(tape[, machine=Machine(track=true); halt_condition=x->false])

Run instruction tape. Will create a new machine with instruction tracking turned on if no
machine is supplied. A halt condition can also be given with the `halt_condition` keyword.
"""
function run_tape(tape, machine=Machine(track=false); halt_condition=x->false)
    while machine.current_line<length(tape)
        if halt_condition(machine)
            return machine, true
        end

        f, args = tape[machine.current_line]
        if f == :acc
            acc!(machine, args...)
        elseif f == :jmp
            jmp!(machine, args...)
        elseif f == :nop
            nop!(machine, args...)
        else
            throw(InstructionError(machine.current_line, f, args))
        end
    end

    return machine, false
end

end


text:
# von Mises distribution
#
#  Implemented based on Wikipedia
#

immutable VonMises <: ContinuousUnivariateDistribution
    μ::Float64      # mean
    κ::Float64      # concentration
    I0κ::Float64    # I0(κ), where I0 is the modified Bessel function of order 0

    function VonMises(μ::Real, κ::Real)
        κ > zero(κ) || error("kappa must be positive")
        new(float64(μ), float64(κ), besseli(0, κ))
    end

    VonMises(κ::Real) = VonMises(0.0, float64(κ))
    VonMises() = VonMises(0.0, 1.0)
end

show(io::IO, d::VonMises) = show(io, d, (:μ, :κ))

### Properties

minimum(d::VonMises) = d.μ - π
maximum(d::VonMises) = d.μ + π
islowerbounded(d::VonMises) = true
isupperbounded(d::VonMises) = true
insupport(d::VonMises, x::Real) = -π <= (x - d.μ) <= π

mean(d::VonMises) = d.μ
median(d::VonMises) = d.μ
mode(d::VonMises) = d.μ
circvar(d::VonMises) = 1.0 - besseli(1, d.κ) / I0κ
entropy(d::VonMises) = log(twoπ * d.I0κ) - d.κ * (besseli(1, d.κ) / d.I0κ)

cf(d::VonMises, t::Real) = (besseli(abs(t), d.k) / I0κ) * exp(im * t * d.μ)

### Functions

pdf(d::VonMises, x::Real) = exp(d.κ * cos(float64(x) - d.μ)) / (twoπ * d.I0κ)
logpdf(d::VonMises, x::Real) = d.κ * cos(float64(x) - d.μ) - log(d.I0κ) - log2π

cdf(d::VonMises, x::Real) = _vmcdf(d.κ, d.I0κ, float64(x) - d.μ, 1.0e-15)

function _vmcdf(κ::Float64, I0κ::Float64, x::Float64, tol::Float64)
    j = 1
    cj = besseli(j, κ) / j
    s = cj * sin(j * x)
    while abs(cj) > tol
        j += 1
        cj = besseli(j, κ) / j
        s += cj * sin(j * x)
    end
    return (x + 2.0 * s / I0κ) / twoπ + 0.5
end

## Sampling
sampler(d::VonMises) = VonMisesSampler(d.μ, d.κ)