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

using AWS.Compat
using AWS.UUIDs
"""
    CreateDataset()

Creates an Amazon Forecast dataset. The information about the dataset that you provide helps Forecast understand how to consume the data for model training. This includes the following:     DataFrequency  - How frequently your historical time-series data is collected.     Domain  and  DatasetType  - Each dataset has an associated dataset domain and a type within the domain. Amazon Forecast provides a list of predefined domains and types within each domain. For each unique dataset domain and type within the domain, Amazon Forecast requires your data to include a minimum set of predefined fields.     Schema  - A schema specifies the fields in the dataset, including the field name and data type.   After creating a dataset, you import your training data into it and add the dataset to a dataset group. You use the dataset group to create a predictor. For more information, see howitworks-datasets-groups. To get a list of all your datasets, use the ListDatasets operation. For example Forecast datasets, see the Amazon Forecast Sample GitHub repository.  The Status of a dataset must be ACTIVE before you can import training data. Use the DescribeDataset operation to get the status.

# Required Parameters
- `DatasetName`: A name for the dataset.
- `DatasetType`: The dataset type. Valid values depend on the chosen Domain.
- `Domain`: The domain associated with the dataset. When you add a dataset to a dataset group, this value and the value specified for the Domain parameter of the CreateDatasetGroup operation must match. The Domain and DatasetType that you choose determine the fields that must be present in the training data that you import to the dataset. For example, if you choose the RETAIL domain and TARGET_TIME_SERIES as the DatasetType, Amazon Forecast requires item_id, timestamp, and demand fields to be present in your data. For more information, see howitworks-datasets-groups.
- `Schema`: The schema for the dataset. The schema attributes and their order must match the fields in your data. The dataset Domain and DatasetType that you choose determine the minimum required fields in your training data. For information about the required fields for a specific dataset domain and type, see howitworks-domains-ds-types.

# Optional Parameters
- `DataFrequency`: The frequency of data collection. This parameter is required for RELATED_TIME_SERIES datasets. Valid intervals are Y (Year), M (Month), W (Week), D (Day), H (Hour), 30min (30 minutes), 15min (15 minutes), 10min (10 minutes), 5min (5 minutes), and 1min (1 minute). For example, \"D\" indicates every day and \"15min\" indicates every 15 minutes.
- `EncryptionConfig`: An AWS Key Management Service (KMS) key and the AWS Identity and Access Management (IAM) role that Amazon Forecast can assume to access the key.
- `Tags`: The optional metadata that you apply to the dataset to help you categorize and organize them. Each tag consists of a key and an optional value, both of which you define. The following basic restrictions apply to tags:   Maximum number of tags per resource - 50.   For each resource, each tag key must be unique, and each tag key can have only one value.   Maximum key length - 128 Unicode characters in UTF-8.   Maximum value length - 256 Unicode characters in UTF-8.   If your tagging schema is used across multiple services and resources, remember that other services may have restrictions on allowed characters. Generally allowed characters are: letters, numbers, and spaces representable in UTF-8, and the following characters: + - = . _ : / @.   Tag keys and values are case sensitive.   Do not use aws:, AWS:, or any upper or lowercase combination of such as a prefix for keys as it is reserved for AWS use. You cannot edit or delete tag keys with this prefix. Values can have this prefix. If a tag value has aws as its prefix but the key does not, then Forecast considers it to be a user tag and will count against the limit of 50 tags. Tags with only the key prefix of aws do not count against your tags per resource limit.
"""

create_dataset(DatasetName, DatasetType, Domain, Schema; aws_config::AWSConfig=global_aws_config()) = forecast("CreateDataset", Dict{String, Any}("DatasetName"=>DatasetName, "DatasetType"=>DatasetType, "Domain"=>Domain, "Schema"=>Schema); aws_config=aws_config)
create_dataset(DatasetName, DatasetType, Domain, Schema, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = forecast("CreateDataset", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("DatasetName"=>DatasetName, "DatasetType"=>DatasetType, "Domain"=>Domain, "Schema"=>Schema), args)); aws_config=aws_config)

"""
    CreateDatasetGroup()

Creates a dataset group, which holds a collection of related datasets. You can add datasets to the dataset group when you create the dataset group, or later by using the UpdateDatasetGroup operation. After creating a dataset group and adding datasets, you use the dataset group when you create a predictor. For more information, see howitworks-datasets-groups. To get a list of all your datasets groups, use the ListDatasetGroups operation.  The Status of a dataset group must be ACTIVE before you can create use the dataset group to create a predictor. To get the status, use the DescribeDatasetGroup operation.

# Required Parameters
- `DatasetGroupName`: A name for the dataset group.
- `Domain`: The domain associated with the dataset group. When you add a dataset to a dataset group, this value and the value specified for the Domain parameter of the CreateDataset operation must match. The Domain and DatasetType that you choose determine the fields that must be present in training data that you import to a dataset. For example, if you choose the RETAIL domain and TARGET_TIME_SERIES as the DatasetType, Amazon Forecast requires that item_id, timestamp, and demand fields are present in your data. For more information, see howitworks-datasets-groups.

# Optional Parameters
- `DatasetArns`: An array of Amazon Resource Names (ARNs) of the datasets that you want to include in the dataset group.
- `Tags`: The optional metadata that you apply to the dataset group to help you categorize and organize them. Each tag consists of a key and an optional value, both of which you define. The following basic restrictions apply to tags:   Maximum number of tags per resource - 50.   For each resource, each tag key must be unique, and each tag key can have only one value.   Maximum key length - 128 Unicode characters in UTF-8.   Maximum value length - 256 Unicode characters in UTF-8.   If your tagging schema is used across multiple services and resources, remember that other services may have restrictions on allowed characters. Generally allowed characters are: letters, numbers, and spaces representable in UTF-8, and the following characters: + - = . _ : / @.   Tag keys and values are case sensitive.   Do not use aws:, AWS:, or any upper or lowercase combination of such as a prefix for keys as it is reserved for AWS use. You cannot edit or delete tag keys with this prefix. Values can have this prefix. If a tag value has aws as its prefix but the key does not, then Forecast considers it to be a user tag and will count against the limit of 50 tags. Tags with only the key prefix of aws do not count against your tags per resource limit.
"""

create_dataset_group(DatasetGroupName, Domain; aws_config::AWSConfig=global_aws_config()) = forecast("CreateDatasetGroup", Dict{String, Any}("DatasetGroupName"=>DatasetGroupName, "Domain"=>Domain); aws_config=aws_config)
create_dataset_group(DatasetGroupName, Domain, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = forecast("CreateDatasetGroup", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("DatasetGroupName"=>DatasetGroupName, "Domain"=>Domain), args)); aws_config=aws_config)

"""
    CreateDatasetImportJob()

Imports your training data to an Amazon Forecast dataset. You provide the location of your training data in an Amazon Simple Storage Service (Amazon S3) bucket and the Amazon Resource Name (ARN) of the dataset that you want to import the data to. You must specify a DataSource object that includes an AWS Identity and Access Management (IAM) role that Amazon Forecast can assume to access the data, as Amazon Forecast makes a copy of your data and processes it in an internal AWS system. For more information, see aws-forecast-iam-roles. The training data must be in CSV format. The delimiter must be a comma (,). You can specify the path to a specific CSV file, the S3 bucket, or to a folder in the S3 bucket. For the latter two cases, Amazon Forecast imports all files up to the limit of 10,000 files. Because dataset imports are not aggregated, your most recent dataset import is the one that is used when training a predictor or generating a forecast. Make sure that your most recent dataset import contains all of the data you want to model off of, and not just the new data collected since the previous import. To get a list of all your dataset import jobs, filtered by specified criteria, use the ListDatasetImportJobs operation.

# Required Parameters
- `DataSource`: The location of the training data to import and an AWS Identity and Access Management (IAM) role that Amazon Forecast can assume to access the data. The training data must be stored in an Amazon S3 bucket. If encryption is used, DataSource must include an AWS Key Management Service (KMS) key and the IAM role must allow Amazon Forecast permission to access the key. The KMS key and IAM role must match those specified in the EncryptionConfig parameter of the CreateDataset operation.
- `DatasetArn`: The Amazon Resource Name (ARN) of the Amazon Forecast dataset that you want to import data to.
- `DatasetImportJobName`: The name for the dataset import job. We recommend including the current timestamp in the name, for example, 20190721DatasetImport. This can help you avoid getting a ResourceAlreadyExistsException exception.

# Optional Parameters
- `Tags`: The optional metadata that you apply to the dataset import job to help you categorize and organize them. Each tag consists of a key and an optional value, both of which you define. The following basic restrictions apply to tags:   Maximum number of tags per resource - 50.   For each resource, each tag key must be unique, and each tag key can have only one value.   Maximum key length - 128 Unicode characters in UTF-8.   Maximum value length - 256 Unicode characters in UTF-8.   If your tagging schema is used across multiple services and resources, remember that other services may have restrictions on allowed characters. Generally allowed characters are: letters, numbers, and spaces representable in UTF-8, and the following characters: + - = . _ : / @.   Tag keys and values are case sensitive.   Do not use aws:, AWS:, or any upper or lowercase combination of such as a prefix for keys as it is reserved for AWS use. You cannot edit or delete tag keys with this prefix. Values can have this prefix. If a tag value has aws as its prefix but the key does not, then Forecast considers it to be a user tag and will count against the limit of 50 tags. Tags with only the key prefix of aws do not count against your tags per resource limit.
- `TimestampFormat`: The format of timestamps in the dataset. The format that you specify depends on the DataFrequency specified when the dataset was created. The following formats are supported   \"yyyy-MM-dd\" For the following data frequencies: Y, M, W, and D   \"yyyy-MM-dd HH:mm:ss\" For the following data frequencies: H, 30min, 15min, and 1min; and optionally, for: Y, M, W, and D   If the format isn't specified, Amazon Forecast expects the format to be \"yyyy-MM-dd HH:mm:ss\".
"""

create_dataset_import_job(DataSource, DatasetArn, DatasetImportJobName; aws_config::AWSConfig=global_aws_config()) = forecast("CreateDatasetImportJob", Dict{String, Any}("DataSource"=>DataSource, "DatasetArn"=>DatasetArn, "DatasetImportJobName"=>DatasetImportJobName); aws_config=aws_config)
create_dataset_import_job(DataSource, DatasetArn, DatasetImportJobName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = forecast("CreateDatasetImportJob", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("DataSource"=>DataSource, "DatasetArn"=>DatasetArn, "DatasetImportJobName"=>DatasetImportJobName), args)); aws_config=aws_config)

"""
    CreateForecast()

Creates a forecast for each item in the TARGET_TIME_SERIES dataset that was used to train the predictor. This is known as inference. To retrieve the forecast for a single item at low latency, use the operation. To export the complete forecast into your Amazon Simple Storage Service (Amazon S3) bucket, use the CreateForecastExportJob operation. The range of the forecast is determined by the ForecastHorizon value, which you specify in the CreatePredictor request. When you query a forecast, you can request a specific date range within the forecast. To get a list of all your forecasts, use the ListForecasts operation.  The forecasts generated by Amazon Forecast are in the same time zone as the dataset that was used to create the predictor.  For more information, see howitworks-forecast.  The Status of the forecast must be ACTIVE before you can query or export the forecast. Use the DescribeForecast operation to get the status.

# Required Parameters
- `ForecastName`: A name for the forecast.
- `PredictorArn`: The Amazon Resource Name (ARN) of the predictor to use to generate the forecast.

# Optional Parameters
- `ForecastTypes`: The quantiles at which probabilistic forecasts are generated. You can currently specify up to 5 quantiles per forecast. Accepted values include 0.01 to 0.99 (increments of .01 only) and mean. The mean forecast is different from the median (0.50) when the distribution is not symmetric (for example, Beta and Negative Binomial). The default value is [\"0.1\", \"0.5\", \"0.9\"].
- `Tags`: The optional metadata that you apply to the forecast to help you categorize and organize them. Each tag consists of a key and an optional value, both of which you define. The following basic restrictions apply to tags:   Maximum number of tags per resource - 50.   For each resource, each tag key must be unique, and each tag key can have only one value.   Maximum key length - 128 Unicode characters in UTF-8.   Maximum value length - 256 Unicode characters in UTF-8.   If your tagging schema is used across multiple services and resources, remember that other services may have restrictions on allowed characters. Generally allowed characters are: letters, numbers, and spaces representable in UTF-8, and the following characters: + - = . _ : / @.   Tag keys and values are case sensitive.   Do not use aws:, AWS:, or any upper or lowercase combination of such as a prefix for keys as it is reserved for AWS use. You cannot edit or delete tag keys with this prefix. Values can have this prefix. If a tag value has aws as its prefix but the key does not, then Forecast considers it to be a user tag and will count against the limit of 50 tags. Tags with only the key prefix of aws do not count against your tags per resource limit.
"""

create_forecast(ForecastName, PredictorArn; aws_config::AWSConfig=global_aws_config()) = forecast("CreateForecast", Dict{String, Any}("ForecastName"=>ForecastName, "PredictorArn"=>PredictorArn); aws_config=aws_config)
create_forecast(ForecastName, PredictorArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = forecast("CreateForecast", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ForecastName"=>ForecastName, "PredictorArn"=>PredictorArn), args)); aws_config=aws_config)

"""
    CreateForecastExportJob()

Exports a forecast created by the CreateForecast operation to your Amazon Simple Storage Service (Amazon S3) bucket. The forecast file name will match the following conventions: <ForecastExportJobName>_<ExportTimestamp>_<PartNumber> where the <ExportTimestamp> component is in Java SimpleDateFormat (yyyy-MM-ddTHH-mm-ssZ). You must specify a DataDestination object that includes an AWS Identity and Access Management (IAM) role that Amazon Forecast can assume to access the Amazon S3 bucket. For more information, see aws-forecast-iam-roles. For more information, see howitworks-forecast. To get a list of all your forecast export jobs, use the ListForecastExportJobs operation.  The Status of the forecast export job must be ACTIVE before you can access the forecast in your Amazon S3 bucket. To get the status, use the DescribeForecastExportJob operation.

# Required Parameters
- `Destination`: The location where you want to save the forecast and an AWS Identity and Access Management (IAM) role that Amazon Forecast can assume to access the location. The forecast must be exported to an Amazon S3 bucket. If encryption is used, Destination must include an AWS Key Management Service (KMS) key. The IAM role must allow Amazon Forecast permission to access the key.
- `ForecastArn`: The Amazon Resource Name (ARN) of the forecast that you want to export.
- `ForecastExportJobName`: The name for the forecast export job.

# Optional Parameters
- `Tags`: The optional metadata that you apply to the forecast export job to help you categorize and organize them. Each tag consists of a key and an optional value, both of which you define. The following basic restrictions apply to tags:   Maximum number of tags per resource - 50.   For each resource, each tag key must be unique, and each tag key can have only one value.   Maximum key length - 128 Unicode characters in UTF-8.   Maximum value length - 256 Unicode characters in UTF-8.   If your tagging schema is used across multiple services and resources, remember that other services may have restrictions on allowed characters. Generally allowed characters are: letters, numbers, and spaces representable in UTF-8, and the following characters: + - = . _ : / @.   Tag keys and values are case sensitive.   Do not use aws:, AWS:, or any upper or lowercase combination of such as a prefix for keys as it is reserved for AWS use. You cannot edit or delete tag keys with this prefix. Values can have this prefix. If a tag value has aws as its prefix but the key does not, then Forecast considers it to be a user tag and will count against the limit of 50 tags. Tags with only the key prefix of aws do not count against your tags per resource limit.
"""

create_forecast_export_job(Destination, ForecastArn, ForecastExportJobName; aws_config::AWSConfig=global_aws_config()) = forecast("CreateForecastExportJob", Dict{String, Any}("Destination"=>Destination, "ForecastArn"=>ForecastArn, "ForecastExportJobName"=>ForecastExportJobName); aws_config=aws_config)
create_forecast_export_job(Destination, ForecastArn, ForecastExportJobName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = forecast("CreateForecastExportJob", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Destination"=>Destination, "ForecastArn"=>ForecastArn, "ForecastExportJobName"=>ForecastExportJobName), args)); aws_config=aws_config)

"""
    CreatePredictor()

Creates an Amazon Forecast predictor. In the request, you provide a dataset group and either specify an algorithm or let Amazon Forecast choose the algorithm for you using AutoML. If you specify an algorithm, you also can override algorithm-specific hyperparameters. Amazon Forecast uses the chosen algorithm to train a model using the latest version of the datasets in the specified dataset group. The result is called a predictor. You then generate a forecast using the CreateForecast operation. After training a model, the CreatePredictor operation also evaluates it. To see the evaluation metrics, use the GetAccuracyMetrics operation. Always review the evaluation metrics before deciding to use the predictor to generate a forecast. Optionally, you can specify a featurization configuration to fill and aggregate the data fields in the TARGET_TIME_SERIES dataset to improve model training. For more information, see FeaturizationConfig. For RELATED_TIME_SERIES datasets, CreatePredictor verifies that the DataFrequency specified when the dataset was created matches the ForecastFrequency. TARGET_TIME_SERIES datasets don't have this restriction. Amazon Forecast also verifies the delimiter and timestamp format. For more information, see howitworks-datasets-groups.  AutoML  If you want Amazon Forecast to evaluate each algorithm and choose the one that minimizes the objective function, set PerformAutoML to true. The objective function is defined as the mean of the weighted p10, p50, and p90 quantile losses. For more information, see EvaluationResult. When AutoML is enabled, the following properties are disallowed:    AlgorithmArn     HPOConfig     PerformHPO     TrainingParameters    To get a list of all of your predictors, use the ListPredictors operation.  Before you can use the predictor to create a forecast, the Status of the predictor must be ACTIVE, signifying that training has completed. To get the status, use the DescribePredictor operation.

# Required Parameters
- `FeaturizationConfig`: The featurization configuration.
- `ForecastHorizon`: Specifies the number of time-steps that the model is trained to predict. The forecast horizon is also called the prediction length. For example, if you configure a dataset for daily data collection (using the DataFrequency parameter of the CreateDataset operation) and set the forecast horizon to 10, the model returns predictions for 10 days. The maximum forecast horizon is the lesser of 500 time-steps or 1/3 of the TARGET_TIME_SERIES dataset length.
- `InputDataConfig`: Describes the dataset group that contains the data to use to train the predictor.
- `PredictorName`: A name for the predictor.

# Optional Parameters
- `AlgorithmArn`: The Amazon Resource Name (ARN) of the algorithm to use for model training. Required if PerformAutoML is not set to true.  Supported algorithms:     arn:aws:forecast:::algorithm/ARIMA     arn:aws:forecast:::algorithm/Deep_AR_Plus  Supports hyperparameter optimization (HPO)    arn:aws:forecast:::algorithm/ETS     arn:aws:forecast:::algorithm/NPTS     arn:aws:forecast:::algorithm/Prophet
- `EncryptionConfig`: An AWS Key Management Service (KMS) key and the AWS Identity and Access Management (IAM) role that Amazon Forecast can assume to access the key.
- `EvaluationParameters`: Used to override the default evaluation parameters of the specified algorithm. Amazon Forecast evaluates a predictor by splitting a dataset into training data and testing data. The evaluation parameters define how to perform the split and the number of iterations.
- `HPOConfig`: Provides hyperparameter override values for the algorithm. If you don't provide this parameter, Amazon Forecast uses default values. The individual algorithms specify which hyperparameters support hyperparameter optimization (HPO). For more information, see aws-forecast-choosing-recipes. If you included the HPOConfig object, you must set PerformHPO to true.
- `PerformAutoML`: Whether to perform AutoML. When Amazon Forecast performs AutoML, it evaluates the algorithms it provides and chooses the best algorithm and configuration for your training dataset. The default value is false. In this case, you are required to specify an algorithm. Set PerformAutoML to true to have Amazon Forecast perform AutoML. This is a good option if you aren't sure which algorithm is suitable for your training data. In this case, PerformHPO must be false.
- `PerformHPO`: Whether to perform hyperparameter optimization (HPO). HPO finds optimal hyperparameter values for your training data. The process of performing HPO is known as running a hyperparameter tuning job. The default value is false. In this case, Amazon Forecast uses default hyperparameter values from the chosen algorithm. To override the default values, set PerformHPO to true and, optionally, supply the HyperParameterTuningJobConfig object. The tuning job specifies a metric to optimize, which hyperparameters participate in tuning, and the valid range for each tunable hyperparameter. In this case, you are required to specify an algorithm and PerformAutoML must be false. The following algorithm supports HPO:   DeepAR+
- `Tags`: The optional metadata that you apply to the predictor to help you categorize and organize them. Each tag consists of a key and an optional value, both of which you define. The following basic restrictions apply to tags:   Maximum number of tags per resource - 50.   For each resource, each tag key must be unique, and each tag key can have only one value.   Maximum key length - 128 Unicode characters in UTF-8.   Maximum value length - 256 Unicode characters in UTF-8.   If your tagging schema is used across multiple services and resources, remember that other services may have restrictions on allowed characters. Generally allowed characters are: letters, numbers, and spaces representable in UTF-8, and the following characters: + - = . _ : / @.   Tag keys and values are case sensitive.   Do not use aws:, AWS:, or any upper or lowercase combination of such as a prefix for keys as it is reserved for AWS use. You cannot edit or delete tag keys with this prefix. Values can have this prefix. If a tag value has aws as its prefix but the key does not, then Forecast considers it to be a user tag and will count against the limit of 50 tags. Tags with only the key prefix of aws do not count against your tags per resource limit.
- `TrainingParameters`: The hyperparameters to override for model training. The hyperparameters that you can override are listed in the individual algorithms. For the list of supported algorithms, see aws-forecast-choosing-recipes.
"""

create_predictor(FeaturizationConfig, ForecastHorizon, InputDataConfig, PredictorName; aws_config::AWSConfig=global_aws_config()) = forecast("CreatePredictor", Dict{String, Any}("FeaturizationConfig"=>FeaturizationConfig, "ForecastHorizon"=>ForecastHorizon, "InputDataConfig"=>InputDataConfig, "PredictorName"=>PredictorName); aws_config=aws_config)
create_predictor(FeaturizationConfig, ForecastHorizon, InputDataConfig, PredictorName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = forecast("CreatePredictor", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("FeaturizationConfig"=>FeaturizationConfig, "ForecastHorizon"=>ForecastHorizon, "InputDataConfig"=>InputDataConfig, "PredictorName"=>PredictorName), args)); aws_config=aws_config)

"""
    DeleteDataset()

Deletes an Amazon Forecast dataset that was created using the CreateDataset operation. You can only delete datasets that have a status of ACTIVE or CREATE_FAILED. To get the status use the DescribeDataset operation.  Forecast does not automatically update any dataset groups that contain the deleted dataset. In order to update the dataset group, use the operation, omitting the deleted dataset's ARN.

# Required Parameters
- `DatasetArn`: The Amazon Resource Name (ARN) of the dataset to delete.

"""

delete_dataset(DatasetArn; aws_config::AWSConfig=global_aws_config()) = forecast("DeleteDataset", Dict{String, Any}("DatasetArn"=>DatasetArn); aws_config=aws_config)
delete_dataset(DatasetArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = forecast("DeleteDataset", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("DatasetArn"=>DatasetArn), args)); aws_config=aws_config)

"""
    DeleteDatasetGroup()

Deletes a dataset group created using the CreateDatasetGroup operation. You can only delete dataset groups that have a status of ACTIVE, CREATE_FAILED, or UPDATE_FAILED. To get the status, use the DescribeDatasetGroup operation. This operation deletes only the dataset group, not the datasets in the group.

# Required Parameters
- `DatasetGroupArn`: The Amazon Resource Name (ARN) of the dataset group to delete.

"""

delete_dataset_group(DatasetGroupArn; aws_config::AWSConfig=global_aws_config()) = forecast("DeleteDatasetGroup", Dict{String, Any}("DatasetGroupArn"=>DatasetGroupArn); aws_config=aws_config)
delete_dataset_group(DatasetGroupArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = forecast("DeleteDatasetGroup", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("DatasetGroupArn"=>DatasetGroupArn), args)); aws_config=aws_config)

"""
    DeleteDatasetImportJob()

Deletes a dataset import job created using the CreateDatasetImportJob operation. You can delete only dataset import jobs that have a status of ACTIVE or CREATE_FAILED. To get the status, use the DescribeDatasetImportJob operation.

# Required Parameters
- `DatasetImportJobArn`: The Amazon Resource Name (ARN) of the dataset import job to delete.

"""

delete_dataset_import_job(DatasetImportJobArn; aws_config::AWSConfig=global_aws_config()) = forecast("DeleteDatasetImportJob", Dict{String, Any}("DatasetImportJobArn"=>DatasetImportJobArn); aws_config=aws_config)
delete_dataset_import_job(DatasetImportJobArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = forecast("DeleteDatasetImportJob", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("DatasetImportJobArn"=>DatasetImportJobArn), args)); aws_config=aws_config)

"""
    DeleteForecast()

Deletes a forecast created using the CreateForecast operation. You can delete only forecasts that have a status of ACTIVE or CREATE_FAILED. To get the status, use the DescribeForecast operation. You can't delete a forecast while it is being exported. After a forecast is deleted, you can no longer query the forecast.

# Required Parameters
- `ForecastArn`: The Amazon Resource Name (ARN) of the forecast to delete.

"""

delete_forecast(ForecastArn; aws_config::AWSConfig=global_aws_config()) = forecast("DeleteForecast", Dict{String, Any}("ForecastArn"=>ForecastArn); aws_config=aws_config)
delete_forecast(ForecastArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = forecast("DeleteForecast", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ForecastArn"=>ForecastArn), args)); aws_config=aws_config)

"""
    DeleteForecastExportJob()

Deletes a forecast export job created using the CreateForecastExportJob operation. You can delete only export jobs that have a status of ACTIVE or CREATE_FAILED. To get the status, use the DescribeForecastExportJob operation.

# Required Parameters
- `ForecastExportJobArn`: The Amazon Resource Name (ARN) of the forecast export job to delete.

"""

delete_forecast_export_job(ForecastExportJobArn; aws_config::AWSConfig=global_aws_config()) = forecast("DeleteForecastExportJob", Dict{String, Any}("ForecastExportJobArn"=>ForecastExportJobArn); aws_config=aws_config)
delete_forecast_export_job(ForecastExportJobArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = forecast("DeleteForecastExportJob", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ForecastExportJobArn"=>ForecastExportJobArn), args)); aws_config=aws_config)

"""
    DeletePredictor()

Deletes a predictor created using the CreatePredictor operation. You can delete only predictor that have a status of ACTIVE or CREATE_FAILED. To get the status, use the DescribePredictor operation.

# Required Parameters
- `PredictorArn`: The Amazon Resource Name (ARN) of the predictor to delete.

"""

delete_predictor(PredictorArn; aws_config::AWSConfig=global_aws_config()) = forecast("DeletePredictor", Dict{String, Any}("PredictorArn"=>PredictorArn); aws_config=aws_config)
delete_predictor(PredictorArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = forecast("DeletePredictor", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("PredictorArn"=>PredictorArn), args)); aws_config=aws_config)

"""
    DescribeDataset()

Describes an Amazon Forecast dataset created using the CreateDataset operation. In addition to listing the parameters specified in the CreateDataset request, this operation includes the following dataset properties:    CreationTime     LastModificationTime     Status

# Required Parameters
- `DatasetArn`: The Amazon Resource Name (ARN) of the dataset.

"""

describe_dataset(DatasetArn; aws_config::AWSConfig=global_aws_config()) = forecast("DescribeDataset", Dict{String, Any}("DatasetArn"=>DatasetArn); aws_config=aws_config)
describe_dataset(DatasetArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = forecast("DescribeDataset", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("DatasetArn"=>DatasetArn), args)); aws_config=aws_config)

"""
    DescribeDatasetGroup()

Describes a dataset group created using the CreateDatasetGroup operation. In addition to listing the parameters provided in the CreateDatasetGroup request, this operation includes the following properties:    DatasetArns - The datasets belonging to the group.    CreationTime     LastModificationTime     Status

# Required Parameters
- `DatasetGroupArn`: The Amazon Resource Name (ARN) of the dataset group.

"""

describe_dataset_group(DatasetGroupArn; aws_config::AWSConfig=global_aws_config()) = forecast("DescribeDatasetGroup", Dict{String, Any}("DatasetGroupArn"=>DatasetGroupArn); aws_config=aws_config)
describe_dataset_group(DatasetGroupArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = forecast("DescribeDatasetGroup", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("DatasetGroupArn"=>DatasetGroupArn), args)); aws_config=aws_config)

"""
    DescribeDatasetImportJob()

Describes a dataset import job created using the CreateDatasetImportJob operation. In addition to listing the parameters provided in the CreateDatasetImportJob request, this operation includes the following properties:    CreationTime     LastModificationTime     DataSize     FieldStatistics     Status     Message - If an error occurred, information about the error.

# Required Parameters
- `DatasetImportJobArn`: The Amazon Resource Name (ARN) of the dataset import job.

"""

describe_dataset_import_job(DatasetImportJobArn; aws_config::AWSConfig=global_aws_config()) = forecast("DescribeDatasetImportJob", Dict{String, Any}("DatasetImportJobArn"=>DatasetImportJobArn); aws_config=aws_config)
describe_dataset_import_job(DatasetImportJobArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = forecast("DescribeDatasetImportJob", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("DatasetImportJobArn"=>DatasetImportJobArn), args)); aws_config=aws_config)

"""
    DescribeForecast()

Describes a forecast created using the CreateForecast operation. In addition to listing the properties provided in the CreateForecast request, this operation lists the following properties:    DatasetGroupArn - The dataset group that provided the training data.    CreationTime     LastModificationTime     Status     Message - If an error occurred, information about the error.

# Required Parameters
- `ForecastArn`: The Amazon Resource Name (ARN) of the forecast.

"""

describe_forecast(ForecastArn; aws_config::AWSConfig=global_aws_config()) = forecast("DescribeForecast", Dict{String, Any}("ForecastArn"=>ForecastArn); aws_config=aws_config)
describe_forecast(ForecastArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = forecast("DescribeForecast", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ForecastArn"=>ForecastArn), args)); aws_config=aws_config)

"""
    DescribeForecastExportJob()

Describes a forecast export job created using the CreateForecastExportJob operation. In addition to listing the properties provided by the user in the CreateForecastExportJob request, this operation lists the following properties:    CreationTime     LastModificationTime     Status     Message - If an error occurred, information about the error.

# Required Parameters
- `ForecastExportJobArn`: The Amazon Resource Name (ARN) of the forecast export job.

"""

describe_forecast_export_job(ForecastExportJobArn; aws_config::AWSConfig=global_aws_config()) = forecast("DescribeForecastExportJob", Dict{String, Any}("ForecastExportJobArn"=>ForecastExportJobArn); aws_config=aws_config)
describe_forecast_export_job(ForecastExportJobArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = forecast("DescribeForecastExportJob", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ForecastExportJobArn"=>ForecastExportJobArn), args)); aws_config=aws_config)

"""
    DescribePredictor()

Describes a predictor created using the CreatePredictor operation. In addition to listing the properties provided in the CreatePredictor request, this operation lists the following properties:    DatasetImportJobArns - The dataset import jobs used to import training data.    AutoMLAlgorithmArns - If AutoML is performed, the algorithms that were evaluated.    CreationTime     LastModificationTime     Status     Message - If an error occurred, information about the error.

# Required Parameters
- `PredictorArn`: The Amazon Resource Name (ARN) of the predictor that you want information about.

"""

describe_predictor(PredictorArn; aws_config::AWSConfig=global_aws_config()) = forecast("DescribePredictor", Dict{String, Any}("PredictorArn"=>PredictorArn); aws_config=aws_config)
describe_predictor(PredictorArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = forecast("DescribePredictor", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("PredictorArn"=>PredictorArn), args)); aws_config=aws_config)

"""
    GetAccuracyMetrics()

Provides metrics on the accuracy of the models that were trained by the CreatePredictor operation. Use metrics to see how well the model performed and to decide whether to use the predictor to generate a forecast. For more information, see metrics. This operation generates metrics for each backtest window that was evaluated. The number of backtest windows (NumberOfBacktestWindows) is specified using the EvaluationParameters object, which is optionally included in the CreatePredictor request. If NumberOfBacktestWindows isn't specified, the number defaults to one. The parameters of the filling method determine which items contribute to the metrics. If you want all items to contribute, specify zero. If you want only those items that have complete data in the range being evaluated to contribute, specify nan. For more information, see FeaturizationMethod.  Before you can get accuracy metrics, the Status of the predictor must be ACTIVE, signifying that training has completed. To get the status, use the DescribePredictor operation.

# Required Parameters
- `PredictorArn`: The Amazon Resource Name (ARN) of the predictor to get metrics for.

"""

get_accuracy_metrics(PredictorArn; aws_config::AWSConfig=global_aws_config()) = forecast("GetAccuracyMetrics", Dict{String, Any}("PredictorArn"=>PredictorArn); aws_config=aws_config)
get_accuracy_metrics(PredictorArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = forecast("GetAccuracyMetrics", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("PredictorArn"=>PredictorArn), args)); aws_config=aws_config)

"""
    ListDatasetGroups()

Returns a list of dataset groups created using the CreateDatasetGroup operation. For each dataset group, this operation returns a summary of its properties, including its Amazon Resource Name (ARN). You can retrieve the complete set of properties by using the dataset group ARN with the DescribeDatasetGroup operation.

# Optional Parameters
- `MaxResults`: The number of items to return in the response.
- `NextToken`: If the result of the previous request was truncated, the response includes a NextToken. To retrieve the next set of results, use the token in the next request. Tokens expire after 24 hours.
"""

list_dataset_groups(; aws_config::AWSConfig=global_aws_config()) = forecast("ListDatasetGroups"; aws_config=aws_config)
list_dataset_groups(args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = forecast("ListDatasetGroups", args; aws_config=aws_config)

"""
    ListDatasetImportJobs()

Returns a list of dataset import jobs created using the CreateDatasetImportJob operation. For each import job, this operation returns a summary of its properties, including its Amazon Resource Name (ARN). You can retrieve the complete set of properties by using the ARN with the DescribeDatasetImportJob operation. You can filter the list by providing an array of Filter objects.

# Optional Parameters
- `Filters`: An array of filters. For each filter, you provide a condition and a match statement. The condition is either IS or IS_NOT, which specifies whether to include or exclude the datasets that match the statement from the list, respectively. The match statement consists of a key and a value.  Filter properties     Condition - The condition to apply. Valid values are IS and IS_NOT. To include the datasets that match the statement, specify IS. To exclude matching datasets, specify IS_NOT.    Key - The name of the parameter to filter on. Valid values are DatasetArn and Status.    Value - The value to match.   For example, to list all dataset import jobs whose status is ACTIVE, you specify the following filter:  \"Filters\": [ { \"Condition\": \"IS\", \"Key\": \"Status\", \"Value\": \"ACTIVE\" } ]
- `MaxResults`: The number of items to return in the response.
- `NextToken`: If the result of the previous request was truncated, the response includes a NextToken. To retrieve the next set of results, use the token in the next request. Tokens expire after 24 hours.
"""

list_dataset_import_jobs(; aws_config::AWSConfig=global_aws_config()) = forecast("ListDatasetImportJobs"; aws_config=aws_config)
list_dataset_import_jobs(args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = forecast("ListDatasetImportJobs", args; aws_config=aws_config)

"""
    ListDatasets()

Returns a list of datasets created using the CreateDataset operation. For each dataset, a summary of its properties, including its Amazon Resource Name (ARN), is returned. To retrieve the complete set of properties, use the ARN with the DescribeDataset operation.

# Optional Parameters
- `MaxResults`: The number of items to return in the response.
- `NextToken`: If the result of the previous request was truncated, the response includes a NextToken. To retrieve the next set of results, use the token in the next request. Tokens expire after 24 hours.
"""

list_datasets(; aws_config::AWSConfig=global_aws_config()) = forecast("ListDatasets"; aws_config=aws_config)
list_datasets(args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = forecast("ListDatasets", args; aws_config=aws_config)

"""
    ListForecastExportJobs()

Returns a list of forecast export jobs created using the CreateForecastExportJob operation. For each forecast export job, this operation returns a summary of its properties, including its Amazon Resource Name (ARN). To retrieve the complete set of properties, use the ARN with the DescribeForecastExportJob operation. You can filter the list using an array of Filter objects.

# Optional Parameters
- `Filters`: An array of filters. For each filter, you provide a condition and a match statement. The condition is either IS or IS_NOT, which specifies whether to include or exclude the forecast export jobs that match the statement from the list, respectively. The match statement consists of a key and a value.  Filter properties     Condition - The condition to apply. Valid values are IS and IS_NOT. To include the forecast export jobs that match the statement, specify IS. To exclude matching forecast export jobs, specify IS_NOT.    Key - The name of the parameter to filter on. Valid values are ForecastArn and Status.    Value - The value to match.   For example, to list all jobs that export a forecast named electricityforecast, specify the following filter:  \"Filters\": [ { \"Condition\": \"IS\", \"Key\": \"ForecastArn\", \"Value\": \"arn:aws:forecast:us-west-2:<acct-id>:forecast/electricityforecast\" } ]
- `MaxResults`: The number of items to return in the response.
- `NextToken`: If the result of the previous request was truncated, the response includes a NextToken. To retrieve the next set of results, use the token in the next request. Tokens expire after 24 hours.
"""

list_forecast_export_jobs(; aws_config::AWSConfig=global_aws_config()) = forecast("ListForecastExportJobs"; aws_config=aws_config)
list_forecast_export_jobs(args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = forecast("ListForecastExportJobs", args; aws_config=aws_config)

"""
    ListForecasts()

Returns a list of forecasts created using the CreateForecast operation. For each forecast, this operation returns a summary of its properties, including its Amazon Resource Name (ARN). To retrieve the complete set of properties, specify the ARN with the DescribeForecast operation. You can filter the list using an array of Filter objects.

# Optional Parameters
- `Filters`: An array of filters. For each filter, you provide a condition and a match statement. The condition is either IS or IS_NOT, which specifies whether to include or exclude the forecasts that match the statement from the list, respectively. The match statement consists of a key and a value.  Filter properties     Condition - The condition to apply. Valid values are IS and IS_NOT. To include the forecasts that match the statement, specify IS. To exclude matching forecasts, specify IS_NOT.    Key - The name of the parameter to filter on. Valid values are DatasetGroupArn, PredictorArn, and Status.    Value - The value to match.   For example, to list all forecasts whose status is not ACTIVE, you would specify:  \"Filters\": [ { \"Condition\": \"IS_NOT\", \"Key\": \"Status\", \"Value\": \"ACTIVE\" } ]
- `MaxResults`: The number of items to return in the response.
- `NextToken`: If the result of the previous request was truncated, the response includes a NextToken. To retrieve the next set of results, use the token in the next request. Tokens expire after 24 hours.
"""

list_forecasts(; aws_config::AWSConfig=global_aws_config()) = forecast("ListForecasts"; aws_config=aws_config)
list_forecasts(args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = forecast("ListForecasts", args; aws_config=aws_config)

"""
    ListPredictors()

Returns a list of predictors created using the CreatePredictor operation. For each predictor, this operation returns a summary of its properties, including its Amazon Resource Name (ARN). You can retrieve the complete set of properties by using the ARN with the DescribePredictor operation. You can filter the list using an array of Filter objects.

# Optional Parameters
- `Filters`: An array of filters. For each filter, you provide a condition and a match statement. The condition is either IS or IS_NOT, which specifies whether to include or exclude the predictors that match the statement from the list, respectively. The match statement consists of a key and a value.  Filter properties     Condition - The condition to apply. Valid values are IS and IS_NOT. To include the predictors that match the statement, specify IS. To exclude matching predictors, specify IS_NOT.    Key - The name of the parameter to filter on. Valid values are DatasetGroupArn and Status.    Value - The value to match.   For example, to list all predictors whose status is ACTIVE, you would specify:  \"Filters\": [ { \"Condition\": \"IS\", \"Key\": \"Status\", \"Value\": \"ACTIVE\" } ]
- `MaxResults`: The number of items to return in the response.
- `NextToken`: If the result of the previous request was truncated, the response includes a NextToken. To retrieve the next set of results, use the token in the next request. Tokens expire after 24 hours.
"""

list_predictors(; aws_config::AWSConfig=global_aws_config()) = forecast("ListPredictors"; aws_config=aws_config)
list_predictors(args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = forecast("ListPredictors", args; aws_config=aws_config)

"""
    ListTagsForResource()

Lists the tags for an Amazon Forecast resource.

# Required Parameters
- `ResourceArn`: The Amazon Resource Name (ARN) that identifies the resource for which to list the tags. Currently, the supported resources are Forecast dataset groups, datasets, dataset import jobs, predictors, forecasts, and forecast export jobs.

"""

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

"""
    TagResource()

Associates the specified tags to a resource with the specified resourceArn. If existing tags on a resource are not specified in the request parameters, they are not changed. When a resource is deleted, the tags associated with that resource are also deleted.

# Required Parameters
- `ResourceArn`: The Amazon Resource Name (ARN) that identifies the resource for which to list the tags. Currently, the supported resources are Forecast dataset groups, datasets, dataset import jobs, predictors, forecasts, and forecast export jobs.
- `Tags`: The tags to add to the resource. A tag is an array of key-value pairs. The following basic restrictions apply to tags:   Maximum number of tags per resource - 50.   For each resource, each tag key must be unique, and each tag key can have only one value.   Maximum key length - 128 Unicode characters in UTF-8.   Maximum value length - 256 Unicode characters in UTF-8.   If your tagging schema is used across multiple services and resources, remember that other services may have restrictions on allowed characters. Generally allowed characters are: letters, numbers, and spaces representable in UTF-8, and the following characters: + - = . _ : / @.   Tag keys and values are case sensitive.   Do not use aws:, AWS:, or any upper or lowercase combination of such as a prefix for keys as it is reserved for AWS use. You cannot edit or delete tag keys with this prefix. Values can have this prefix. If a tag value has aws as its prefix but the key does not, then Forecast considers it to be a user tag and will count against the limit of 50 tags. Tags with only the key prefix of aws do not count against your tags per resource limit.

"""

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

"""
    UntagResource()

Deletes the specified tags from a resource.

# Required Parameters
- `ResourceArn`: The Amazon Resource Name (ARN) that identifies the resource for which to list the tags. Currently, the supported resources are Forecast dataset groups, datasets, dataset import jobs, predictors, forecasts, and forecast exports.
- `TagKeys`: The keys of the tags to be removed.

"""

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

"""
    UpdateDatasetGroup()

Replaces the datasets in a dataset group with the specified datasets.  The Status of the dataset group must be ACTIVE before you can use the dataset group to create a predictor. Use the DescribeDatasetGroup operation to get the status.

# Required Parameters
- `DatasetArns`: An array of the Amazon Resource Names (ARNs) of the datasets to add to the dataset group.
- `DatasetGroupArn`: The ARN of the dataset group.

"""

update_dataset_group(DatasetArns, DatasetGroupArn; aws_config::AWSConfig=global_aws_config()) = forecast("UpdateDatasetGroup", Dict{String, Any}("DatasetArns"=>DatasetArns, "DatasetGroupArn"=>DatasetGroupArn); aws_config=aws_config)
update_dataset_group(DatasetArns, DatasetGroupArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = forecast("UpdateDatasetGroup", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("DatasetArns"=>DatasetArns, "DatasetGroupArn"=>DatasetGroupArn), args)); aws_config=aws_config)


text:
using Test, QSimulator
import QSimulator: index, unique_tol
using SpecialFunctions: besselj, erf

@testset "unitary propagator time independent" begin
    # For a constant Hamiltonian compare exponentiation to full unitary_propagator
    # first, create a block diagonal Hamiltonian matrix
    m1 = [[0,1] [1,0]]
    m2 = [[0,1im,0] [-1im,.1,2+1im] [0,2-1im,0]]
    m3 = [3]
    mat = cat(m1, m2, m3, dims=[1,2])

    # Make a CompositeQSystem from the Hamiltonian
    lh = LiteralHermitian("label", HermitianSpec(mat))
    cqs = CompositeQSystem([lh])
    add_hamiltonian!(cqs, lh)
    times = range(0, stop=10, length=100)

    # compare the unitary propagator to matrix exponentiation
    us_prop = unitary_propagator(cqs, times)
    us_expm = [exp(-2π *1im * mat * t) for t in times]
    @test all(isapprox(u_expm, u_prop; atol=1e-4) for (u_expm, u_prop) in zip(us_expm, us_prop))
end

# parameters for an iSWAP interaction with linear frequency modulation
freq_fixed = 4.0
anharm = -0.2
drive_freq = 0.3

dims = (3,3)
basis = TensorProductBasis(dims)
ψ₀₁ = TensorProductBasisState(basis, (0,1))
ψ₁₀ = TensorProductBasisState(basis, (1,0))

# start with the tunable transmon at zero frquency and add frequency term with parametric_drive
q0 = DuffingTransmon("q0", dims[1], DuffingSpec(0.0, anharm))
q1 = DuffingTransmon("q1", dims[2], DuffingSpec(freq_fixed, anharm))
cqs = CompositeQSystem([q0, q1])
add_hamiltonian!(cqs, q1)

# park the tunable `drive_freq` above the tunable and linearly modulate its frequency with an
# amplitude equal to the modulation frequency
a = freq_fixed + drive_freq
b = drive_freq
add_hamiltonian!(cqs, parametric_drive(q0, t -> a + b * cos(2π * drive_freq * t)), q0)
g = 0.01
add_hamiltonian!(cqs, .5 * g * X_Y([q0, q1]), [q0, q1])
g_eff = g * besselj(1, b/drive_freq)
t_final = 1/(4 * g_eff)

@testset "unitary state time dependent" begin
    # compare state evolution to closed form RWA calculation
    num_times = 25
    times = range(0, stop=t_final, length=num_times)
    ψs = unitary_state(cqs, times, vec(ψ₁₀))
    pop₁₀ = [abs2(ψ[index(ψ₁₀)]) for ψ in ψs]
    pop₀₁ = [abs2(ψ[index(ψ₀₁)]) for ψ in ψs]
    pop₁₀_RWA = cos.(2π*g_eff*times).^2
    pop₀₁_RWA = 1 .- pop₁₀_RWA
    @test isapprox(pop₁₀, pop₁₀_RWA, rtol=.03)
    @test isapprox(pop₀₁, pop₀₁_RWA, rtol=.03)
end

@testset "unitary propagator time dependent" begin
    # compare consistency of state evolution and propagator evolution
    times = range(0, stop=t_final, length=3)
    us_full = unitary_propagator(cqs, times)
    ψ₀ = TensorProductBasisState(basis, (1,0))
    ψs = unitary_state(cqs, times, vec(ψ₀))
    pop_10_state = [abs2(ψ[index(ψ₀)]) for ψ in ψs]
    pop_10_prop = [abs2(vec(ψ₀)' * u * vec(ψ₀)) for u in us_full]
    @test isapprox(pop_10_state, pop_10_prop, rtol=1e-4)
    # test helper function for saving at a point
    us_end = unitary_propagator(cqs, times[end])
    @test us_end == us_full[end]
    ψ_end = unitary_state(cqs, times[end], vec(ψ₀))
    @test ψ_end == ψs[end]
end

@testset "choose_times_floquet and decompose_times_floquet" begin
    t_period = 1/drive_freq
    dt = t_final/10
    times = choose_times_floquet(t_final/2, t_final, t_period, dt)
    @test times[1] > 0
    @test times[end] <= t_final
    @test t_final/2 in times
    prepend!(times, 0.0)
    @test times[1] == 0
    quotients, unique_remainders, unique_inds = decompose_times_floquet(times, t_period)
    @test length(quotients) == length(times)
    @test length(unique_remainders) <= length(times)
    @test length(unique_inds) == length(times)
    @test isapprox(t_period * quotients + unique_remainders[unique_inds], times)
end

@testset "floquet with pulseshape" begin
    cqs = CompositeQSystem([q0, q1])
    add_hamiltonian!(cqs, q1)
    add_hamiltonian!(cqs, .5 * g * X_Y([q0, q1]), [q0, q1])
    # create pulseshape
    rise_time = .1 * t_final
    fwhm = 0.25 * rise_time
    t1 = fwhm
    t2 = t_final - fwhm
    σ = 0.5 * fwhm / sqrt(2*log(2))
    function p(t)
        envelope = 0.5 * (erf((t - t1)/σ) - erf((t - t2)/σ)) # erf_squared
        drive = a + b * cos(2π * drive_freq * t)
        return envelope * drive + (1 - envelope) * (a+b)
    end
    times = collect(range(0.0, stop=t_final, length=500))
    add_hamiltonian!(cqs, parametric_drive(q0, p), q0)
    t_period = 1/drive_freq
    prop = floquet_rise_fall_propagator(unitary_propagator, t_period, rise_time, rise_time)
    us_floquet_pulseshape = prop(cqs, times)
    us_unitary = unitary_propagator(cqs, times)
    @test all(isapprox(u_unitary, u_floquet, rtol=1e-5) for (u_unitary, u_floquet) in zip(us_unitary, us_floquet_pulseshape))
end

@testset "me_propagator" begin
    # compare master equation state and propagator evolution for consistency with on-resonance CW
    # microwave
    dims = 3
    qubit_freq = 5.0
    anharm = -0.2
    q0 = DuffingTransmon("q0", dims, DuffingSpec(qubit_freq, anharm))
    cqs = CompositeQSystem([q0])
    add_hamiltonian!(cqs, q0)
    add_hamiltonian!(cqs, dipole_drive(q0, t -> 0.02*cos(2π*qubit_freq * t)), q0)
    T1 = 50. # in ns
    γ = 1/(2π * T1) # in GHz
    add_lindblad!(cqs, decay(q0, γ), [q0])

    times = range(0,stop=100,length=101)
    ψ0 = ComplexF64[1; 0; 0]
    ρ0 = ψ0 * ψ0'
    us_prop = me_propagator(cqs, times)
    ρs_prop = [reshape(u * vec(ρ0), dims, dims) for u in us_prop]
    ρs = me_state(cqs, times, ρ0)
    # TODO: bring uncomment and add a test for these
    # prop = floquet_propagator(me_propagator, 1/qubit_freq)
    # us_floquet = prop(cqs, times)
    # ρs_floquet = [reshape(u * vec(ρ0), dims, dims) for u in us_floquet]

    @test all(isapprox(ρ_prop, ρ_state, rtol=1e-4) for (ρ_prop, ρ_state) in zip(ρs_prop, ρs))

    # test helper function for saving at a point
    us_end = me_propagator(cqs, times[end])
    @test us_end == us_prop[end]
    ρ_end = me_state(cqs, times[end], ρ0)
    @test ρ_end == ρs[end]
end

@testset "decay and dephasing" begin
    # compare master equation free evolution decay under T1 and T2 to exponential predictions
    dims = 3
    qubit_freq = 5.0
    anharm = -0.2
    q0 = DuffingTransmon("q0", dims, DuffingSpec(qubit_freq, anharm))
    cqs = CompositeQSystem([q0])
    add_hamiltonian!(cqs, q0)
    T1 = 50.0 # in ns
    γ1 = 1/(2π * T1) # in GHz
    Tϕ = 200.0 # ns
    γϕ = 1/(2π * Tϕ) # in GHz
    T2 = 1/(.5/T1 + 1/Tϕ)
    add_lindblad!(cqs, decay(q0, γ1), [q0])
    add_lindblad!(cqs, dephasing(q0, γϕ), [q0])

    times = range(0, stop=100, length=101)
    ψ0 = ComplexF64[1; 1; 0]/sqrt(2)
    ρ0 = ψ0 * ψ0'
    ρs = me_state(cqs, times, ρ0)

    analytical_T1 = exp.(-times/T1)/2
    analytical_T2 = exp.(-times/T2)/2

    # check diagonal and off-diagonal against exponential decay with T1/T2 rates
    @test all(isapprox(ρ[2,2], check_T1, rtol=1e-10) for (ρ,check_T1) in zip(ρs, analytical_T1))
    @test all(isapprox(ρ[1,2], check_T2, rtol=1e-2) for (ρ,check_T2) in zip(ρs, analytical_T2))
end

@testset "unique_tol" begin
    l0 = [1.0,2.0,3.0]
    l1 = l0 .+ 1e-5
    l2 = [l0; l1]
    @test unique(l2) == l2
    a, inds = unique_tol(l2, 1e-6)
    @test a == l2
    @test inds == [1,2,3,4,5,6]
    a, inds = unique_tol(l2, 1e-4)
    @test a == l0
    @test inds == [1,2,3,1,2,3]
end

ext: jl


text:
# Styles - mainly for switching between hexagonal and rectangular layouts.
abstract type Style end

# Style API
links(x::Style) = x.links
iolinks(x::Style) = x.io_links

# For unifying filters for creating source/sink rules.
filter_proc(x) = search_metadata!(x, typekey(), MTypes.proc, in)
filter_io(x) = search_metadata!(
    x,
    typekey(),
    [MTypes.proc, MTypes.input, MTypes.output],
    oneofin
)

filter_memproc(x) = search_metadata!(x, typekey(), MTypes.memoryproc, in)
filter_memory(n) = x -> search_metadata!(x, typekey(), MTypes.memory(n), in)

cartesian(s::Style, x::Address) = cartesian(s, Tuple(x))
cartesian(s::Style, x::Tuple) = cartesian(s, x...)

include("styles/rectangular.jl")
include("styles/five.jl")
include("styles/hexagonal.jl")


text:
## General markdown rendering  –––––––––––––––––––––––––––––––––––––

# noneH_addnewline add a new line if mdstyle is not a H1-6  but italic, bold, or normal
function println_mdstyle(io::IO, mdstyle::ASCIIString, item, noneH_addnewline = true)
    if mdstyle in MDHTAGS
        println(io, "$mdstyle $item")
    else
        println(io, "$mdstyle$item$mdstyle")
        noneH_addnewline && println(io)
    end
end

function save(file::AbstractString, mime::MIME"text/md", doc::Metadata, config::Config)
    ents = Entries(config)
    # Write the main file.
    isfile(file) || mkpath(dirname(file))
    open(file, "w") do f
        info("writing documentation to $(file)")
        headermd(f, doc, config)
        ents = mainsetup(f, mime, doc, ents, file, config)
    end
    return ents
end

function process_entries(io::IO, mime::MIME"text/md", grpname::AbstractString,
                                                entries::Dict, config::Config)
    if has_items(entries)
        config.md_subheader == :simple && println_mdstyle(io, config.mdstyle_subheader, grpname)
        println(io)
        for k in config.category_order
            if length(entries[k]) > 0
                config.md_subheader == :category && println_mdstyle(io, config.mdstyle_subheader,
                                                              "$(ucfirst(string(k)))s [$grpname]\n")
                for (modname, obj, ent, anchorname) in entries[k]
                    writemd(io, modname, obj, ent, anchorname, config)
                end
            end
        end
    end
end

function writemime(io::IO, mime::MIME"text/md", manual::AbstractString)
    println(io, manual)
end

function writemd{category}(io::IO, modname, obj, ent::Entry{category},
                           anchorname::AbstractString, config::Config)
    objname = writeobj(obj, ent)
    println(io, "---\n")
    println(io, """""")
    println_mdstyle(io, config.mdstyle_objname,
                    string(objname, config.md_permalink ? " [¶](#$anchorname)" : ""))
    writemd(io, docs(ent))
    println(io)
    if has_output_metadata(ent, config)
        for m in config.metadata_order
            if haskey(ent.data, m)
                println_mdstyle(io, config.mdstyle_meta, "$m:", false)
                writemd(io, Meta{m}(ent.data[m]))
                println(io)
            end
        end
    end
end

function writemd(io::IO, md::Meta)
    println(io, md.content)
end

function writemd(io::IO, m::Meta{:source})
    path = last(split(m.content[2], r"v[\d\.]+(/|\\)"))
    println(io, "[$(path):$(m.content[1])]($(url(m)))")
end

function headermd(io::IO, doc::Metadata, config::Config)
    println_mdstyle(io, config.mdstyle_header, doc.modname)
    println(io)
end

## Docs-specific rendering

function writemd(io::IO, docs::Docile.Interface.Docs{:md})
    println(io, docs.data)
end

### API-Index ----------------------------------------------------------------------------

function save(file::AbstractString, mime::MIME"text/md", index::Index, c::Config)
    # Write the API-Index file.
    genindexfiledir = dirname(abspath(file))
    isfile(file) || mkpath(genindexfiledir)
    open(file, "w") do f
        info("writing API-Index to $(file)")
        println_mdstyle(f, c.mdstyle_header, "API-INDEX\n")
        println(f)

        for ent in index.entries
            for i in 1:length(ent.sourcepaths)
                relsourcepath = relpath(ent.sourcepaths[i], genindexfiledir)
                println_mdstyle(f, c.mdstyle_index_mod, "$(c.md_index_modprefix)$(ent.modulenames[i])\n")
                process_api_index(f, "Exported", ent.exported, relsourcepath, c);
                process_api_index(f, "Internal", ent.internal, relsourcepath, c)
            end
        end
    end
end

function process_api_index(io::IO, grpname::AbstractString, entries::Dict,
                           relsourcepath::AbstractString, config::Config)
    if has_items(entries)
        config.md_subheader == :simple && (println(io, "---\n");
                                       println_mdstyle(io, config.mdstyle_subheader, "$grpname\n"))
        for k in config.category_order
            if length(entries[k]) > 0
                if config.md_subheader == :category
                    println(io, "---\n")
                    println_mdstyle(io, config.mdstyle_subheader, "$(ucfirst(string(k)))s [$grpname]\n")
                end
                for (modname, obj, ent, anchorname) in entries[k]
                    description = split(data(docs(ent)), '\n')[1]
                    println(io, "[$(writeobj(obj, ent))]($relsourcepath#$anchorname)  $description\n")
                end
            end
        end
    end
end


text:
# The following variables need to be defined before `include`-ing this file:
# `testset_name_suffix`
# `sz_values`
# `n_values`
# `k_values`
# `m_values`

@time @testset "_mul!: C, A, B $(testset_name_suffix)" begin
    for threading in [Gaius.singlethreaded, Gaius.multithreaded]
        for sz in sz_values
            for n in n_values
                for k in k_values
                    for m in m_values
                        A = randn(Float64, n, k)
                        B = randn(Float64, k, m)
                        C1 = zeros(Float64, n, m)
                        C2 = zeros(Float64, n, m)
                        Gaius._mul!(    threading, C1, A, B, sz)
                        Gaius._mul_add!(threading, C2, A, B, sz, Val(1))
                        @test A * B ≈ C1
                        @test A * B ≈ C2
                    end
                end
            end
        end
    end
end

@time @testset "_mul!: C::VecTypes, A::MatTypes, B::VecTypes $(testset_name_suffix)" begin
    for threading in [Gaius.singlethreaded, Gaius.multithreaded]
        for sz in sz_values
            for n in n_values
                for k in k_values
                    for m in m_values
                        A = randn(Float64, n, k)
                        B = randn(Float64, k)
                        C1 = zeros(Float64, n)
                        C2 = zeros(Float64, n)
                        Gaius._mul!(    threading, C1, A, B, sz)
                        Gaius._mul_add!(threading, C2, A, B, sz, Val(1))
                        @test A * B ≈ C1
                        @test A * B ≈ C2
                    end
                end
            end
        end
    end
end

@time @testset "_mul!: C::CoVecTypes, A::CoVecTypes, B::MatTypes $(testset_name_suffix)" begin
    for threading in [Gaius.singlethreaded, Gaius.multithreaded]
        for sz in sz_values
            for n in n_values
                for k in k_values
                    for m in m_values
                        A = adjoint(randn(Float64, n))
                        B = randn(Float64, n, m)
                        C1 = adjoint(zeros(Float64, m))
                        C2 = adjoint(zeros(Float64, m))
                        Gaius._mul!(    threading, C1, A, B, sz)
                        Gaius._mul_add!(threading, C2, A, B, sz, Val(1))
                        @test A * B ≈ C1
                        @test A * B ≈ C2
                    end
                end
            end
        end
    end
end


text:
# Contains functions for simulating IRFs and exponential decays

struct IrfSimulationSettings
    # Configuration for simulating IRF
    t::TcspcTimeAxis
    N::Unsigned
    fwhm::AbstractFloat
    offset::AbstractFloat
    # Inner constructor for argument validation
    function IrfSimulationSettings(t::TcspcTimeAxis,
        N::Integer,fwhm::AbstractFloat,
        offset::AbstractFloat)
        if fwhm < 0
            error("fwhm is less than 0")
        end
        if offset < 0
            error("offset is less than 0")
        end
        new(t,N,fwhm,offset)
    end
end

function simulate_irf(settings::IrfSimulationSettings)
    # Generates a Gaussian instrument response function

    σ = settings.fwhm/(2 * sqrt(2 * log(2)))
    gaussDist = Normal(settings.offset, σ)
    # Generate photons
    photons = rand(gaussDist,settings.N)
    # Fit histogram to photons at time points
    bins = time_bins(settings.t)
    h = fit(Histogram,photons,bins)
    # Weights contain the number of counts per bin, which is what we want
    return sim_poisson(h.weights)
end

function simulate_irf(tax::TcspcTimeAxis,
    N::Integer,fwhm::AbstractFloat,
    offs::AbstractFloat)
    sett = IrfSimulationSettings(tax,N,fwhm,offs)
    simulate_irf(sett)
end

function simulate_irf(start::AbstractFloat,
    stop::AbstractFloat,nbins::Integer,
    ψ::AbstractFloat,
    N::Integer,fwhm::AbstractFloat,
    offs::AbstractFloat)
    tax = TcspcTimeAxis(start,stop,nbins,ψ)
    simulate_irf(tax,N,fwhm,offs)
end

function simulate_irf(tcal::AbstractFloat,nbins::Integer,
    ψ::AbstractFloat, N::Integer,fwhm::AbstractFloat,
    offs::AbstractFloat)
    # Open method for dispatch
    tax = TcspcTimeAxis(tcal,nbins,ψ)
    simulate_irf(tax,N,fwhm,offs)
end


text:
grid    = [ 0.0  1.0  0.0
            0.5  1.0  0.0
            1.0  1.0  0.0
            0.0  1.0  4.0
            0.5  1.0  4.0
            1.0  1.0  4.0 ]
h5file  = "temp.h5"

@testset "ParameterSpace" begin

    μ = Parameter(:μ, 0.0, 1.0, 3)
    ν = Parameter(:ν, 1.0, 1.0, 1)
    σ = Parameter(:σ, 0.0, 4.0, 2)

    params = (μ, ν, σ)
    pkeys  = (:μ, :ν, :σ)
    pgrid  = [NamedTuple{pkeys}(Tuple(grid[i,:])) for i in axes(grid,1)]

    p1 = ParameterSpace(NamedTuple(params...), sample(CartesianParameterSampler(), params...))
    p2 = ParameterSpace(NamedTuple(params...))
    p3 = ParameterSpace(params...)

    @test p1 == p2 == p3
    @test p1[:] == p2[:] == p3[:] == pgrid

    for i in axes(grid,1)
        @test p1[i] == p2[i] == p3[i] == pgrid[i]
    end

    @test p1.samples.μ == p2.samples.μ == p3.samples.μ == grid[:,1]
    @test p1.samples.ν == p2.samples.ν == p3.samples.ν == grid[:,2]
    @test p1.samples.σ == p2.samples.σ == p3.samples.σ == grid[:,3]

    h5save(p1, h5file; mode="w")
    @test isfile(h5file)

    p2 = h5load(ParameterSpace, h5file)
    rm(h5file)
    @test p1 == p2

end


text:
using SPICE:
    SpiceError,
    bodfnd,
    bodn2c,
    bodvcd,
    eul2m,
    eul2xf,
    furnsh,
    tipbod,
    tisbod

furnsh(joinpath(@__DIR__, "..", "gen", "gm_de431.tpc"),
       joinpath(@__DIR__, "..", "gen", "pck00010.tpc"))

@testset "Celestial Bodies" begin
    @testset for body_name in AstroBase.Bodies.ALL_NAMES
        body = @eval $(Symbol(body_name))()
        id = naifid(body)
        name = string(body)
        name = name == "Luna" ? "Moon" : name

        @testset "NAIF ID" begin
            @test id == bodn2c(name)
            @test from_naifid(naifid(body)) == body
        end

        if bodfnd(id, "GM")
            @testset "Gravitational parameter" begin
                μ = grav_param(body)
                @test μ ≈ bodvcd(id, "GM")[1]
            end
        end

        if bodfnd(id, "PM")
            @testset "Rotational elements" begin
                ep = TDBEpoch(2019, 5, 6)
                et = value(seconds(j2000(ep)))
                eulang = [reverse(euler_angles(body, ep))...; reverse(euler_rates(body, ep))...]
                p_act = eul2m(eulang[1:3]..., 3, 1, 3)
                p_exp = tipbod("J2000", id, et)
                @testset for i in eachindex(p_act, p_exp)
                    @test p_act[i] ≈ p_exp[i] atol=1e-8
                end
                s_act = eul2xf(eulang, 3, 1, 3)
                s_exp = tisbod("J2000", id, et)
                @testset for i in eachindex(s_act, s_exp)
                    @test s_act[i] ≈ s_exp[i] atol=1e-8
                end
            end
        end
    end
    @test AstroBase.Bodies.path_ids(luna, earth) == [301, 3, 399]
    @test AstroBase.Bodies.path_ids(luna, io) == [301, 3, 0, 5, 501]
end


text:
module LabelledArrays

using LinearAlgebra, StaticArrays

include("slarray.jl")
include("larray.jl")
include("slsliced.jl")
include("lsliced.jl")
include("display.jl")

export SLArray, LArray, SLVector, LVector, @SLVector, @LArray, @LVector, @SLArray

export @SLSliced, @LSliced

export symbols, dimSymbols, rowSymbols, colSymbols

end # module


text:
#
# FIXME this is obsolete and superseded by
# `vs_[xx]_tests.jl` direct tests against online calculators.
#
using Test
using ScottishTaxBenefitModel
using .ModelHousehold: Household, Person, People_Dict, is_single,
    default_bu_allocation, get_benefit_units, get_head, get_spouse, search,
    pers_is_disabled, pers_is_carer
using .ExampleHouseholdGetter
using .Definitions
using .LegacyMeansTestedBenefits:
    calc_legacy_means_tested_benefits!, tariff_income,
    LMTResults, is_working_hours, make_lmt_benefit_applicability, calc_premia,
    working_disabled, calc_allowances,
    apply_2_child_policy, calc_incomes, calc_NDDs

using .Intermediate: MTIntermediate, make_intermediate

using .STBParameters: LegacyMeansTestedBenefitSystem, IncomeRules, HoursLimits
using .Results: LMTResults, LMTCanApplyFor, init_household_result

using .ExampleHelpers

using Dates
using DataFrames
using CSV

## FIXME don't need both
lmt = LegacyMeansTestedBenefitSystem{Float64}()
sys = get_system( scotland=true )

"""
Extract a household from
"""
function spreadsheet_ss_example( key :: AbstractString ) :: NamedTuple
    re = r"([A-Z0-9a-z\-]+)_([0-9]+)k"
    m = match( re, key )
    fam = m[1]
    n = m[2]
    examples = get_all_examples()
    name = ""
    subtype = ""
    m2 = match( r"(.*)-(.*)", fam )
    if m2 !== nothing
        fam = m2[1]
        subtype = m2[2]
    end
    hh = nothing
    rent = 600/4
    ct = 123.25/4
    earn = (1000*parse( Float64, n ))/52.0
    earn = round(earn, digits=2)

    if fam == "B"
        name = "Basic Case"
        hh = examples[cpl_w_2_children_hh]
        bu = get_benefit_units(hh)[1]
        spouse = get_spouse( bu )
        head = get_head( bu )
        head.age = 40
        head.usual_hours_worked = 40
        head.income[wages]=earn

    elseif fam == "K3"
        name = "3 Kids"
        hh = examples[cpl_w_2_children_hh]
    elseif fam == "SP"
        name = "Single Parent"
        hh = examples[single_parent_hh]
    elseif fam == "SE2"
        name = "Single Earner"
        hh = examples[cpl_w_2_children_hh]
    elseif fam == "2C"
        name = "Basic; 2 child limit test"
        hh = examples[cpl_w_2_children_hh]
    elseif fam == "2E"
        name = "2 Earner"
        hh = examples[cpl_w_2_children_hh]
    elseif fam == "CC"
        name = "Child Care"
        hh = examples[cpl_w_2_children_hh]
    elseif fam == "DC"
        name = "Disabled Child"
        hh = examples[cpl_w_2_children_hh]
    elseif fam == "DA"
        name = "Disabled Adult"
        hh = examples[cpl_w_2_children_hh]
    elseif fam == "CL"
        name = "Childless"
        hh = examples[childless_couple_hh]
    else
        error( "unknown key $fam " )
    end
    name = "$name :: $(earn)p.w."
    hh.gross_rent = rent
    hh.council_tax = ct
    return ( name=name, hh=hh )
end

@testset "Complete SS Tests - Legacy System" begin
    sys = get_system( scotland = true )
    df=CSV.File( "$(@__DIR__)/../docs/uc_test_cases_main_results_transposed.csv")|>DataFrame
    keys = split("B_7k,B_4k,B_12k,B_17k,B_22k,B_30k,B_50k,K3_7k,K3_12k,K3_12k,SP_7k,SP_12k,SP_30k,2C-a_7k,2C-b_7k,2C-c_7k,2C-c_22k,SE2_17k,2E_17k,2E_2k,SP-CC_7k,SP-CC_17k,SP-CC_22k,DC-a_7k,DC-b_7k,DC-b_22k,DA-a_7k,DA-b_7k,DA-b_22k,CL_7k,CL_12k,CL_22k", "," )
    for k in keys
        println( "on key $k ")
        name,hh = spreadsheet_ss_example( k )
        println( "name=$name" )
        res = df[df.Key.==k,:][1,:]
        println( res.CTB_NEW )
        hhres = init_household_result( hh )
        intermed = make_intermediate(
            hh,
            sys.hours_limits,
            sys.age_limits,
            sys.child_limits )
        calc_legacy_means_tested_benefits!(
            hhres,
            hh,
            intermed,
            sys.lmt,
            sys.age_limits,
            sys.hours_limits,
            sys.nmt_bens,
            sys.hr )
    end
end

max_stars_repo_name: grahamstark/ScottishTaxBenefitModel

max_issues_repo_name: grahamstark/ScottishTaxBenefitModel

max_forks_repo_name: grahamstark/ScottishTaxBenefitModel


text:
function _precompile_()
    ccall(:jl_generating_output, Cint, ()) == 1 || return nothing
    Base.precompile(Tuple{getfield(Core, Symbol("#kw#Type")),NamedTuple{(:attributes, :notes),Tuple{Attributes,Array{Note,1}}},Type{Measure}})
    Base.precompile(Tuple{getfield(Core, Symbol("#kw#Type")),NamedTuple{(:channel, :program, :volume, :pan, :id),Tuple{Int64,Int64,Int64,Int64,String}},Type{MidiInstrument}})
    Base.precompile(Tuple{getfield(Core, Symbol("#kw#Type")),NamedTuple{(:measures, :id),Tuple{Array{Measure,1},String}},Type{Part}})
    Base.precompile(Tuple{getfield(Core, Symbol("#kw#Type")),NamedTuple{(:name, :midiinstrument, :id),Tuple{String,MidiInstrument,String}},Type{ScorePart}})
    Base.precompile(Tuple{getfield(Core, Symbol("#kw#Type")),NamedTuple{(:partlist, :parts),Tuple{PartList,Array{Part,1}}},Type{ScorePartwise}})
    Base.precompile(Tuple{getfield(Core, Symbol("#kw#Type")),NamedTuple{(:pitch, :duration),Tuple{Pitch,Int64}},Type{Note}})
    Base.precompile(Tuple{getfield(Core, Symbol("#kw#Type")),NamedTuple{(:pitch, :duration, :chord),Tuple{Pitch,Int64,Chord}},Type{Note}})
    Base.precompile(Tuple{getfield(Core, Symbol("#kw#Type")),NamedTuple{(:rest, :duration),Tuple{Rest,Int64}},Type{Note}})
    Base.precompile(Tuple{getfield(Core, Symbol("#kw#Type")),NamedTuple{(:scoreparts,),Tuple{Array{ScorePart,1}}},Type{PartList}})
    Base.precompile(Tuple{getfield(Core, Symbol("#kw#Type")),NamedTuple{(:time, :divisions, :clef, :staves, :key),Tuple{Time,Int64,Array{Clef,1},Int64,Key}},Type{Attributes}})
    Base.precompile(Tuple{typeof(Base.vect),Clef,Vararg{Clef,N} where N})
    Base.precompile(Tuple{typeof(Base.vect),Note,Vararg{Note,N} where N})
    Base.precompile(Tuple{typeof(Base.vect),Part,Vararg{Part,N} where N})
    Base.precompile(Tuple{typeof(Base.vect),ScorePart,Vararg{ScorePart,N} where N})
    Base.precompile(Tuple{typeof(iterate),Array{Note,1}})
    Base.precompile(Tuple{typeof(println),Base.PipeEndpoint,Pitch})
    Base.precompile(Tuple{typeof(println),Pitch})
    Base.precompile(Tuple{typeof(readmusicxml),String})
    Base.precompile(Tuple{typeof(vcat),Measure,Measure})
    Base.precompile(Tuple{typeof(writemusicxml),String,Vararg{Any,N} where N})
end


text:
"""
    AbsoluteValue()

Ensures that the first variable is the absolute value of the second one.
"""
struct AbsoluteValue <: MOI.AbstractVectorSet
end

MOI.dimension(set::AbsoluteValue) = 2
copy(set::AbsoluteValue) = set
Base.:(==)(::AbsoluteValue, ::AbsoluteValue) = true


text:
using Test
using PolynomialBasis
using ImplicitDomainQuadrature
# using Revise
using CutCell
include("useful_routines.jl")

L = 1.0
W = 1.0
lambda1, mu1 = 1.0, 2.0
K1 = (lambda1+2mu1/3)
lambda2, mu2 = 2.0, 4.0
theta0 = -0.067
e22 = K1*theta0/(lambda1+2mu1)
penaltyfactor = 1e2
nelmts = 1
dx = 1.0 / nelmts
penalty = penaltyfactor / dx * (lambda1 + mu1)
stiffness = CutCell.HookeStiffness(lambda1, mu1, lambda2, mu2)
transfstress = CutCell.plane_strain_transformation_stress(lambda1, mu1, theta0)

polyorder = 1
numqp = required_quadrature_order(polyorder) + 2

basis = TensorProductBasis(2, polyorder)
mesh = CutCell.Mesh([0.0, 0.0], [L, W], [nelmts, nelmts], basis)
levelset = InterpolatingPolynomial(1, basis)
levelsetcoeffs = ones(CutCell.number_of_nodes(mesh))

cutmesh = CutCell.CutMesh(levelset, levelsetcoeffs, mesh)
cellquads = CutCell.CellQuadratures(levelset, levelsetcoeffs, cutmesh, numqp)
interfacequads = CutCell.InterfaceQuadratures(levelset, levelsetcoeffs, cutmesh, numqp)
facequads = CutCell.FaceQuadratures(levelset, levelsetcoeffs, cutmesh, numqp)

bilinearforms = CutCell.BilinearForms(basis, cellquads, stiffness, cutmesh)

sysmatrix = CutCell.SystemMatrix()
sysrhs = CutCell.SystemRHS()

CutCell.assemble_bilinear_form!(sysmatrix,bilinearforms,cutmesh)
CutCell.assemble_bulk_transformation_linear_form!(
    sysrhs,
    transfstress,
    basis,
    cellquads,
    cutmesh,
)

matrix = CutCell.make_sparse(sysmatrix, cutmesh)
rhs = CutCell.rhs(sysrhs, cutmesh)

CutCell.apply_dirichlet_bc!(matrix,rhs,[1,2],1,0.0,2)
CutCell.apply_dirichlet_bc!(matrix,rhs,[1],2,0.,2)
CutCell.apply_dirichlet_bc!(matrix,rhs,[3,4],1,0.0,2)

sol = matrix\rhs
disp = reshape(sol,2,:)

testdisp = [0.0  0.0  0.0  0.0
            0.0  e22  0.0  e22]
@test allapprox(disp,testdisp,1e2eps())


text:
"""
    AlgoVibInFluidsModule

Module for algorithms used in models of free vibration of objects partially or fully immersed in inviscid fluids.
"""
module AlgoVibInFluidsModule

using FinEtools.FTypesModule: FInt, FFlt, FCplxFlt, FFltVec, FIntVec, FFltMat, FIntMat, FMat, FVec, FDataDict
using FinEtools.AlgoBaseModule: dcheck!
using Arpack: eigs
using SparseArrays: spzeros
using LinearAlgebra: mul!, eigen, qr, dot, cholesky, norm, diagm, I
my_A_mul_B!(C, A, B) = mul!(C, A, B)
using FinEtools.FieldModule: AbstractField, ndofs, setebc!, numberdofs!, applyebc!, scattersysvec!
using FinEtools.NodalFieldModule: NodalField, nnodes
using FinEtools.FESetModule: nodesperelem, connasarray
using FinEtools.IntegRuleModule: TriRule
using FinEtools.FEMMBaseModule: associategeometry!, distribloads, fieldfromintegpoints, elemfieldfromintegpoints
using FinEtoolsDeforLinear.FEMMDeforLinearBaseModule: stiffness, mass, nzebcloadsstiffness, thermalstrainloads, inspectintegpoints
using FinEtoolsDeforLinear.FEMMDeforLinearMSModule: stiffness, mass, nzebcloadsstiffness, thermalstrainloads, inspectintegpoints
using FinEtoolsDeforLinear.DeforModelRedModule: stresscomponentmap
using FinEtoolsDeforLinear.AlgoDeforLinearModule
using FinEtoolsVibInFluids.LaplBEM
using FinEtools.ForceIntensityModule: ForceIntensity
using FinEtools.MeshModificationModule: meshboundary
using FinEtools.MeshExportModule.VTK: vtkexportmesh

"""
    AlgoVibInFluidsModule.exportfluidpressuremode(modeldata::FDataDict)

Algorithm for exporting of the fluid pressure mode for visualization in Paraview.

# Argument
- `modeldata` = dictionary with values for keys

The meaning of the key-value pairs:
- `"fens"`  = finite element node set
- `"regions"`  = array of region dictionaries
- `"geom"` = geometry field
- `"u"` = displacement field
- `"postprocessing"` = dictionary  with values for keys
  + `"boundary_only"` = should only the boundary of the  regions be rendered?
                      Default is render the interior.
  + `"file"` = name of the  postprocessing file
  + `"quantity"` = quantity to be exported (default `:Cauchy`)
  + `"component"` = which component of the quantity?
  + `"outputcsys"` = output coordinate system

For each region (connected piece of the domain made of a particular material),
mandatory, the  region dictionary  contains values for keys:
* `"femm"` = finite element mmodel machine (mandatory);

# Output
- `modeldata` updated with
  + `modeldata["postprocessing"]["exported"]` = array of data dictionaries, one for
        each exported file. The data is stored with the keys:
    * `"file"` - name of exported file
    * `"field"` - elemental field
"""
function exportfluidpressuremode(modeldata::FDataDict)
    modeldata_recognized_keys = ["fens", "regions", "geom", "u",
    "dT", "postprocessing"]
    postprocessing_recognized_keys = ["boundary_only", "file", "quantity",
    "component", "outputcsys" ]
    # Defaults
    boundary_only = false;
    ffile = "pressmode"
    dcheck!(modeldata, modeldata_recognized_keys)

    fens = get(()->error("Must get fens!"), modeldata, "fens")
    geom = get(()->error("Must get geometry field!"), modeldata, "geom");
    u = get(()->error("Must get displacement field!"), modeldata, "u");
    pressmodes = get(()->error("Must get pressure modes!"), modeldata, "pressmodes");
    wet_boundary_fes = get(()->error("Must get wet boundary finite element mesh!"), modeldata, "wet_boundary_fes");
    wet_W = get(()->error("Must get wet mode shapes!"), modeldata, "wet_W");

    # Collect pressure modes and mode shapes
    if !("postprocessing" in keys(modeldata))
    	modeldata["postprocessing"] = FDataDict()
    end
    modeldata["postprocessing"]["exported"] = Array{FDataDict, 1}()
    rfile = ffile * "-" * "-pressmodes" * ".vtk";
    scalars = []; vectors = []
    for mode in 1:size(pressmodes, 2)
    	push!(scalars, ("pm$mode", deepcopy(pressmodes[:, mode])))
    	scattersysvec!(u, wet_W[:,mode])
    	push!(vectors, ("mode_$(mode)", deepcopy(u.values)))
    end

    # Export the file
    vtkexportmesh(rfile, fens, wet_boundary_fes; scalars=scalars, vectors=vectors)
    push!(modeldata["postprocessing"]["exported"], FDataDict("file"=>rfile, "type"=>"pressure modes"))

    return modeldata
end

"""
    AlgoVibInFluidsModule.modal(modeldata::FDataDict)

Modal (free-vibration) analysis solver for solids partially or entirely submerged in fluid.

# Argument
- `modeldata` = dictionary with values for keys

Those recognized by the `modal()` algorithm of AlgoDeforLinearModule, and
- `"rhow"`  = mass density of the fluid medium
- `"wet_boundary_fes"`  = finite element set for the wet boundary

# Output
`modeldata`= the dictionary on input is augmented with
- `"geom"` = the nodal field that is the geometry
- `"u"` = the nodal field that is the computed displacement
- `"neigvs"` = Number of computed eigenvectors
- `"W"` = Computed eigenvectors, neigvs columns
- `"omega"` =  Computed angular frequencies, array of length neigvs
- `"raw_eigenvalues"` = Raw computed eigenvalues
"""
function modal(modeldata::FDataDict)

	# Run the in-vacuum free-vibration analysis
	modeldata = AlgoDeforLinearModule.modal(modeldata)

	# Retrieve the input data and computed solution of the dry eigenvalue problem
	fens = modeldata["fens"] # nodes
	geom = modeldata["geom"]; # geometry field
	u = modeldata["u"]; # displacement field
	neigvs = modeldata["neigvs"]; # number of eigenvalues
	v = modeldata["W"]; # dry eigenvectors
	d = modeldata["omega"];#  Computed angular frequencies

	wet_boundary_fes = get(()->error("Must get wet boundary finite element mesh!"), modeldata, "wet_boundary_fes");
	rhow = get(()->error("Must get fluid mass density!"), modeldata, "rhow");

    nnperel = nodesperelem(wet_boundary_fes)

    # Calculate the panel unit normals
    pnormals = LaplBEM.allnormals(LaplBEM.allelxs(fens.xyz, connasarray(wet_boundary_fes)))

    # Find the normal components of the displacement for all panels
    vn = fill(0.0, count(wet_boundary_fes), neigvs)
    uk = fill(0.0, 3)
    for mode in 1:neigvs
    	for i in 1:count(wet_boundary_fes)
    		vn[i, mode] = 0.0
    		for k in wet_boundary_fes.conn[i]
    			for m in 1:3
    				dof = u.dofnums[k, m]
    				uk[m] = (dof != 0 ? v[dof, mode] : 0.0)
    			end
    			vn[i, mode] += dot(pnormals[i], uk)
    		end
    		vn[i, mode] /= nnperel
    	end
    end

    # Evaluate the double layer and single-layer potential matrices
    A = fill(0.0, count(wet_boundary_fes), count(wet_boundary_fes))
    A = LaplBEM.doublelayer!(A, fens.xyz, connasarray(wet_boundary_fes), TriRule(3))
    B = fill(0.0, count(wet_boundary_fes), count(wet_boundary_fes))
    B = LaplBEM.singlelayer!(B, fens.xyz, connasarray(wet_boundary_fes), TriRule(3), TriRule(3))

    # Solve for the pressure modes
    pp = A \ (B * vn)

    # Compute the panel areas
    areas = fill(0.0, count(wet_boundary_fes))
    n = fill(0.0, 3)
    for i in 1:count(wet_boundary_fes)
    	ix = collect(wet_boundary_fes.conn[i])
    	LaplBEM.trinml!(n, @view fens.xyz[ix, :])
    	areas[i] = norm(n) / 2
    end

    # Compute the effective stiffness and mass matrices
    rK = diagm(vec(d.^2))     # squares of angular frequencies
    rM = I
    raM = fill(0.0, neigvs, neigvs);
    for i in 1:neigvs
    	for j in 1:neigvs
            raM[i,j] = rhow*dot(vn[:,i].*areas, pp[:,j]);
        end
    end
    raM = (raM +raM')/2;# it should be symmetric, but make sure

    # Compute  the eigenvalues and eigenvectors of the effective eigenvalue problem
    decomp = eigen(rK, rM+raM)

    # Order the eigenvalues by magnitude
    ix = sortperm(decomp.values);

    # Evaluate the wet vibration modes
    wv = v*decomp.vectors[:, ix];

    modeldata["pressmodes"] = pp;
    #  Computed eigenvectors: we are ignoring the imaginary part here
    #  because the modal analysis is presumed to have been performed for
    #  an undamped structure
    modeldata["wet_W"] = real(wv[:,ix]);
    #  Computed angular frequencies
    modeldata["wet_omega"] = sqrt.(decomp.values[ix]);

    return modeldata
end

"""
    AlgoVibInFluidsModule.exportmode(modeldata::FDataDict)

Algorithm for exporting of the mode shape for visualization in Paraview.

# Argument
- `modeldata` = dictionary with values for keys

The meaning of the key-value pairs:
- `"fens"`  = finite element node set
- `"regions"`  = array of region dictionaries
- `"geom"` = geometry field
- `"u"` = displacement field
- `"wet_W"` = Computed wet free-vibration eigenvectors, `neigvs` columns
- `"wet_omega"` =  Computed free-vibration angular frequencies, array of length `neigvs`
- `"postprocessing"` = dictionary  with values for keys
  + `"boundary_only"` = should only the boundary of the  regions be rendered?
                      Default is render the interior.
  + `"file"` = name of the  postprocessing file
  + `"mode"` = which mode should be visualized?
  + `"component"` = which component of the quantity?
  + `"outputcsys"` = output coordinate system

For each region (connected piece of the domain made of a particular material),
mandatory, the  region dictionary  contains values for keys:
* `"femm"` = finite element mmodel machine (mandatory);

# Output
- `modeldata` updated with
  + `modeldata["postprocessing"]["exported"]` = see `exportdeformation()`
"""
function exportmode(modeldata::FDataDict)
    modeldata_recognized_keys = ["fens", "regions", "geom", "u",
    "omega", "W",
    "postprocessing"]
    postprocessing_recognized_keys = ["boundary_only", "file", "mode"]
    mode = 1;
    dcheck!(modeldata, modeldata_recognized_keys)

    # Let's have a look at what's been specified
    postprocessing = get(modeldata, "postprocessing", nothing);
    if (postprocessing != nothing)
        dcheck!(postprocessing, postprocessing_recognized_keys)
        mode =  get(postprocessing, "mode", mode);
    end

    omega = modeldata["wet_omega"]

    # Scatter the desired mode
    W = modeldata["wet_W"]
    if typeof(mode)<:Int
        @assert 0 < mode <= length(omega) "Invalid mode number $mode"
        scattersysvec!(modeldata["u"], W[:,mode])
    else
        us = Tuple{String, AbstractField}[]
        u = modeldata["u"]
        for ixxxx in mode
            @assert 0 < ixxxx <= length(omega) "Invalid mode number $ixxxx"
            scattersysvec!(u, W[:,ixxxx])
            push!(us, ("mode_$(ixxxx)", deepcopy(u)))
        end
        modeldata["us"] = us
    end

    return AlgoDeforLinearModule.exportdeformation(modeldata)
end

end # module

max_stars_repo_name: PetrKryslUCSD/FinEtoolsVibInFluids

max_issues_repo_name: PetrKryslUCSD/FinEtoolsVibInFluids

max_forks_repo_name: PetrKryslUCSD/FinEtoolsVibInFluids


text:
#! /usr/bin/julia

# Rosetta Code, URL decoding

using URIParser

enc = "http%3A%2F%2Ffoo%20bar%2F"

dcd = unescape(enc)

println(enc, " => ", dcd)

max_stars_repo_name: MichaeLeroy/rosetta-code

max_issues_repo_name: MichaeLeroy/rosetta-code

max_forks_repo_name: MichaeLeroy/rosetta-code


text:
import Base: copy, copyto!, ==
import Random: rand, seed!
import RandomNumbers: gen_seed, union_uint, seed_type, unsafe_copyto!, unsafe_compare

"""
```julia
ARS1x{R} <: R123Generator1x{UInt128}
ARS1x([seed, R=7])
```

ARS1x is one kind of ARS Counter-Based RNGs. It generates one `UInt128` number at a time.

`seed` is an `Integer` which will be automatically converted to `UInt128`.

`R` denotes to the Rounds which should be at least 1 and no more than 10. With 7 rounds (by default), it has
a considerable safety margin over the minimum number of rounds with no known statistical flaws, but still has
excellent performance.

Only available when [`R123_USE_AESNI`](@ref).
"""
mutable struct ARS1x{R} <: R123Generator1x{UInt128}
    x::UInt128
    ctr::UInt128
    key::UInt128
end

function ARS1x(seed::Integer=gen_seed(UInt128), R::Integer=7)
    @assert 1 <= R <= 10
    r = ARS1x{Int(R)}(0, 0, 0)
    seed!(r, seed)
end

function seed!(r::ARS1x, seed::Integer=gen_seed(UInt128))
    r.key = seed % UInt128
    r.ctr = 0
    random123_r(r)
    r
end

@inline seed_type(::Type{ARS1x{R}}) where R = UInt128

for R = 1:10
    @eval @inline function ars1xm128i(r, ::Type{Val{$R}})
        p = Ptr{UInt128}(pointer_from_objref(r))
        ccall(($("ars1xm128i$R"), librandom123), Nothing, (
        Ptr{UInt128}, Ptr{UInt128}, Ptr{UInt128}
        ), p + 16, p + 32, p)
        unsafe_load(p, 1)
    end
end

copyto!(dest::ARS1x{R}, src::ARS1x{R}) where R = unsafe_copyto!(dest, src, UInt128, 3)

copy(src::ARS1x{R}) where R = ARS1x{R}(src.x, src.key, src.ctr)

==(r1::ARS1x{R}, r2::ARS1x{R}) where R = unsafe_compare(r1, r2, UInt128, 3)

@inline function random123_r(r::ARS1x{R}) where R
    ars1xm128i(r, Val{R})
    (r.x,)
end

"""
```julia
ARS4x{R} <: R123Generator4x{UInt32}
ARS4x([seed, R=7])
```

ARS4x is one kind of ARS Counter-Based RNGs. It generates four `UInt32` numbers at a time.

`seed` is a `Tuple` of four `Integer`s which will all be automatically converted to `UInt32`.

`R` denotes to the Rounds which must be at least 1 and no more than 10. With 7 rounds (by default), it has a
considerable safety margin over the minimum number of rounds with no known statistical flaws, but still has
excellent performance.

Only available when [`R123_USE_AESNI`](@ref).
"""
mutable struct ARS4x{R} <: R123Generator4x{UInt32}
    x1::UInt32
    x2::UInt32
    x3::UInt32
    x4::UInt32
    ctr1::UInt128
    key::UInt128
    p::Int
end

function ARS4x(seed::NTuple{4, Integer}=gen_seed(UInt32, 4), R::Integer=7)
    @assert 1 <= R <= 10
    r = ARS4x{Int(R)}(0, 0, 0, 0, 0, 0, 0)
    seed!(r, seed)
end

function seed!(r::ARS4x, seed::NTuple{4, Integer}=gen_seed(UInt32, 4))
    r.key = union_uint(map(x -> x % UInt32, seed))
    r.ctr1 = 0
    p = 0
    random123_r(r)
    r
end

@inline seed_type(::Type{ARS4x{R}}) where R = NTuple{4, UInt32}

@inline function random123_r(r::ARS4x{R}) where R
    ars1xm128i(r, Val{R})
    (r.x1, r.x2, r.x3, r.x4)
end

function copyto!(dest::ARS4x{R}, src::ARS4x{R}) where R
    unsafe_copyto!(dest, src, UInt128, 3)
    dest.p = src.p
    dest
end

copy(src::ARS4x{R}) where R = ARS4x{R}(src.x1, src.x2, src.x3, src.x4, src.key, src.ctr1, src.p)

==(r1::ARS4x{R}, r2::ARS4x{R}) where R = unsafe_compare(r1, r2, UInt128, 3) && r1.p == r2.p


text:
function truncate(str::T,n::Int=30) where T<:AbstractString
    if length(str) > n
        return "$(str[1:n-3])..."
    end
    return str
end

"""
    edit(f::File)

Save `f` to a temporary file and open with `edit`.
"""
function edit(f::File)
    # Save file to tmp
    path,io = mktemp()
    for l in f.data
        write(io,l,"\n")
    end
    close(io)
    # Edit File
    edit(path)
    rm(path)
end

"""
    edit(r<:Reference)

Save `r` to a temporary file and open with `edit`.
"""
function edit(r::T) where T<:Reference
    # Save file to tmp
    path,io = mktemp()
    writeToFile(io,value(r))
    close(io)
    # Edit File
    edit(path)
    # Reload edited stuff
    _edit = readlines(path)
    # Replace old with new
    replace!(r,_edit)
    rm(path)
end

"""
    peek(r<:Reference,n::Int=10)

Output n lines around r as string.

"""
function peek(l::Line,n::Int=10)
    lns = collect(max(l.ln-n,1):min(l.ln+n,length(l.file.data)))
    return peek(l.file,lns,[l.ln,])
end

function peek(r::Range,n::Int=10)
    from = max(r.from-n,1)
    to   = min(r.to+n,length(r.file.data))
    lns = vcat(collect(from:r.from+1),
               collect(r.to-1:to))
    return peek(r.file,lns,collect(r.from:r.to))
end

function peek(f::File,lns::Vector{Int},ln::Vector{Int})
    ln_str_length = length(string(lns[end]))
    ln_counter = 0
    str_with_ln = map(f.data[lns]) do _l
        ln_counter += 1
        if lns[ln_counter] in ln
            indicator = ">"
        else
            indicator = indicator_for_reference_at_ln(f,lns[ln_counter])
        end
        string(lpad(string(lns[ln_counter]),ln_str_length),"$indicator| ",_l)
    end
    println(join(str_with_ln,"\n"))
end

function indicator_for_reference_at_ln(f::File,ln::Int)
    for r in f.references
        if isa(r,Line) && r.ln == ln
            return "-"
        elseif isa(r,Range) && ln in r
            return "*"
        end
    end
    return " "
end


text:
#########
# AngularMomentum
# Applies the partial derivative with respect to the last angular variable in the coordinate system.
# For example, in polar coordinates (r, θ) in ℝ² or cylindrical coordinates (r, θ, z) in ℝ³, we apply ∂ / ∂θ = (x ∂ / ∂y - y ∂ / ∂x).
# In spherical coordinates (ρ, θ, φ) in ℝ³, we apply ∂ / ∂φ = (x ∂ / ∂y - y ∂ / ∂x).
#########

struct AngularMomentum{T,Ax<:Inclusion} <: LazyQuasiMatrix{T}
    axis::Ax
end

AngularMomentum{T}(axis::Inclusion) where T = AngularMomentum{T,typeof(axis)}(axis)
AngularMomentum{T}(domain) where T = AngularMomentum{T}(Inclusion(domain))
AngularMomentum(axis) = AngularMomentum{eltype(eltype(axis))}(axis)

axes(A::AngularMomentum) = (A.axis, A.axis)
==(a::AngularMomentum, b::AngularMomentum) = a.axis == b.axis
copy(A::AngularMomentum) = AngularMomentum(copy(A.axis))

^(A::AngularMomentum, k::Integer) = ApplyQuasiArray(^, A, k)

@simplify function *(A::AngularMomentum, P::SphericalHarmonic)
    # Spherical harmonics are the eigenfunctions of the angular momentum operator on the unit sphere
    T = real(eltype(P))
    k = mortar(Base.OneTo.(1:2:∞))
    m = T.((-1) .^ (k .- 1) .* k .÷ 2)
    P * Diagonal(im .* m)
end

#=
@simplify function *(A::AngularMomentum, P::RealSphericalHarmonic)
    # The angular momentum operator applied to real spherical harmonics negates orders
    T = real(eltype(P))
    n = mortar(Fill.(oneto(∞),1:2:∞))
    k = mortar(Base.OneTo.(0:2:∞))
    m = T.(iseven.(k) .* (k .÷ 2))
    dat = PseudoBlockArray(Vcat(
        (-m)', # n, k-1
        (0 .* m)', # n, k
        (m)', # n, k+1
        ), (blockedrange(Fill(3, 1)), axes(n,1)))
    P * _BandedBlockBandedMatrix(dat', axes(k,1), (0,0), (1,1))
end
=#