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

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

Retrieves a list of traces specified by ID. Each trace is a collection of segment documents
that originates from a single request. Use GetTraceSummaries to get a list of trace IDs.

# Arguments
- `trace_ids`: Specify the trace IDs of requests for which to retrieve segments.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"NextToken"`: Pagination token.
"""
batch_get_traces(TraceIds; aws_config::AbstractAWSConfig=global_aws_config()) = xray("POST", "/Traces", Dict{String, Any}("TraceIds"=>TraceIds); aws_config=aws_config)
batch_get_traces(TraceIds, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = xray("POST", "/Traces", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("TraceIds"=>TraceIds), params)); aws_config=aws_config)

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

Creates a group resource with a name and a filter expression.

# Arguments
- `group_name`: The case-sensitive name of the new group. Default is a reserved name and
  names must be unique.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"FilterExpression"`: The filter expression defining criteria by which to group traces.
- `"InsightsConfiguration"`: The structure containing configurations related to insights.
  The InsightsEnabled boolean can be set to true to enable insights for the new group or
  false to disable insights for the new group.   The NotifcationsEnabled boolean can be set
  to true to enable insights notifications for the new group. Notifications may only be
  enabled on a group with InsightsEnabled set to true.
- `"Tags"`: A map that contains one or more tag keys and tag values to attach to an X-Ray
  group. For more information about ways to use tags, see Tagging AWS resources in the AWS
  General Reference. The following restrictions apply to tags:   Maximum number of
  user-applied tags per resource: 50   Maximum tag key length: 128 Unicode characters
  Maximum tag value length: 256 Unicode characters   Valid values for key and value: a-z,
  A-Z, 0-9, space, and the following characters: _ . : / = + - and @   Tag keys and values
  are case sensitive.   Don't use aws: as a prefix for keys; it's reserved for AWS use.
"""
create_group(GroupName; aws_config::AbstractAWSConfig=global_aws_config()) = xray("POST", "/CreateGroup", Dict{String, Any}("GroupName"=>GroupName); aws_config=aws_config)
create_group(GroupName, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = xray("POST", "/CreateGroup", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("GroupName"=>GroupName), params)); aws_config=aws_config)

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

Creates a rule to control sampling behavior for instrumented applications. Services
retrieve rules with GetSamplingRules, and evaluate each rule in ascending order of priority
for each request. If a rule matches, the service records a trace, borrowing it from the
reservoir size. After 10 seconds, the service reports back to X-Ray with GetSamplingTargets
to get updated versions of each in-use rule. The updated rule contains a trace quota that
the service can use instead of borrowing from the reservoir.

# Arguments
- `sampling_rule`: The rule definition.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Tags"`: A map that contains one or more tag keys and tag values to attach to an X-Ray
  sampling rule. For more information about ways to use tags, see Tagging AWS resources in
  the AWS General Reference. The following restrictions apply to tags:   Maximum number of
  user-applied tags per resource: 50   Maximum tag key length: 128 Unicode characters
  Maximum tag value length: 256 Unicode characters   Valid values for key and value: a-z,
  A-Z, 0-9, space, and the following characters: _ . : / = + - and @   Tag keys and values
  are case sensitive.   Don't use aws: as a prefix for keys; it's reserved for AWS use.
"""
create_sampling_rule(SamplingRule; aws_config::AbstractAWSConfig=global_aws_config()) = xray("POST", "/CreateSamplingRule", Dict{String, Any}("SamplingRule"=>SamplingRule); aws_config=aws_config)
create_sampling_rule(SamplingRule, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = xray("POST", "/CreateSamplingRule", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("SamplingRule"=>SamplingRule), params)); aws_config=aws_config)

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

Deletes a group resource.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"GroupARN"`: The ARN of the group that was generated on creation.
- `"GroupName"`: The case-sensitive name of the group.
"""
delete_group(; aws_config::AbstractAWSConfig=global_aws_config()) = xray("POST", "/DeleteGroup"; aws_config=aws_config)
delete_group(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = xray("POST", "/DeleteGroup", params; aws_config=aws_config)

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

Deletes a sampling rule.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"RuleARN"`: The ARN of the sampling rule. Specify a rule by either name or ARN, but not
  both.
- `"RuleName"`: The name of the sampling rule. Specify a rule by either name or ARN, but
  not both.
"""
delete_sampling_rule(; aws_config::AbstractAWSConfig=global_aws_config()) = xray("POST", "/DeleteSamplingRule"; aws_config=aws_config)
delete_sampling_rule(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = xray("POST", "/DeleteSamplingRule", params; aws_config=aws_config)

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

Retrieves the current encryption configuration for X-Ray data.

"""
get_encryption_config(; aws_config::AbstractAWSConfig=global_aws_config()) = xray("POST", "/EncryptionConfig"; aws_config=aws_config)
get_encryption_config(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = xray("POST", "/EncryptionConfig", params; aws_config=aws_config)

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

Retrieves group resource details.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"GroupARN"`: The ARN of the group that was generated on creation.
- `"GroupName"`: The case-sensitive name of the group.
"""
get_group(; aws_config::AbstractAWSConfig=global_aws_config()) = xray("POST", "/GetGroup"; aws_config=aws_config)
get_group(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = xray("POST", "/GetGroup", params; aws_config=aws_config)

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

Retrieves all active group details.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"NextToken"`: Pagination token.
"""
get_groups(; aws_config::AbstractAWSConfig=global_aws_config()) = xray("POST", "/Groups"; aws_config=aws_config)
get_groups(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = xray("POST", "/Groups", params; aws_config=aws_config)

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

Retrieves the summary information of an insight. This includes impact to clients and root
cause services, the top anomalous services, the category, the state of the insight, and the
start and end time of the insight.

# Arguments
- `insight_id`: The insight's unique identifier. Use the GetInsightSummaries action to
  retrieve an InsightId.

"""
get_insight(InsightId; aws_config::AbstractAWSConfig=global_aws_config()) = xray("POST", "/Insight", Dict{String, Any}("InsightId"=>InsightId); aws_config=aws_config)
get_insight(InsightId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = xray("POST", "/Insight", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("InsightId"=>InsightId), params)); aws_config=aws_config)

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

X-Ray reevaluates insights periodically until they're resolved, and records each
intermediate state as an event. You can review an insight's events in the Impact Timeline
on the Inspect page in the X-Ray console.

# Arguments
- `insight_id`: The insight's unique identifier. Use the GetInsightSummaries action to
  retrieve an InsightId.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"MaxResults"`: Used to retrieve at most the specified value of events.
- `"NextToken"`: Specify the pagination token returned by a previous request to retrieve
  the next page of events.
"""
get_insight_events(InsightId; aws_config::AbstractAWSConfig=global_aws_config()) = xray("POST", "/InsightEvents", Dict{String, Any}("InsightId"=>InsightId); aws_config=aws_config)
get_insight_events(InsightId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = xray("POST", "/InsightEvents", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("InsightId"=>InsightId), params)); aws_config=aws_config)

"""
    get_insight_impact_graph(end_time, insight_id, start_time)
    get_insight_impact_graph(end_time, insight_id, start_time, params::Dict{String,<:Any})

Retrieves a service graph structure filtered by the specified insight. The service graph is
limited to only structural information. For a complete service graph, use this API with the
GetServiceGraph API.

# Arguments
- `end_time`: The estimated end time of the insight, in Unix time seconds. The EndTime is
  exclusive of the value provided. The time range between the start time and end time can't
  be more than six hours.
- `insight_id`: The insight's unique identifier. Use the GetInsightSummaries action to
  retrieve an InsightId.
- `start_time`: The estimated start time of the insight, in Unix time seconds. The
  StartTime is inclusive of the value provided and can't be more than 30 days old.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"NextToken"`: Specify the pagination token returned by a previous request to retrieve
  the next page of results.
"""
get_insight_impact_graph(EndTime, InsightId, StartTime; aws_config::AbstractAWSConfig=global_aws_config()) = xray("POST", "/InsightImpactGraph", Dict{String, Any}("EndTime"=>EndTime, "InsightId"=>InsightId, "StartTime"=>StartTime); aws_config=aws_config)
get_insight_impact_graph(EndTime, InsightId, StartTime, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = xray("POST", "/InsightImpactGraph", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("EndTime"=>EndTime, "InsightId"=>InsightId, "StartTime"=>StartTime), params)); aws_config=aws_config)

"""
    get_insight_summaries(end_time, start_time)
    get_insight_summaries(end_time, start_time, params::Dict{String,<:Any})

Retrieves the summaries of all insights in the specified group matching the provided filter
values.

# Arguments
- `end_time`: The end of the time frame in which the insights ended. The end time can't be
  more than 30 days old.
- `start_time`: The beginning of the time frame in which the insights started. The start
  time can't be more than 30 days old.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"GroupARN"`: The Amazon Resource Name (ARN) of the group. Required if the GroupName
  isn't provided.
- `"GroupName"`: The name of the group. Required if the GroupARN isn't provided.
- `"MaxResults"`: The maximum number of results to display.
- `"NextToken"`: Pagination token.
- `"States"`: The list of insight states.
"""
get_insight_summaries(EndTime, StartTime; aws_config::AbstractAWSConfig=global_aws_config()) = xray("POST", "/InsightSummaries", Dict{String, Any}("EndTime"=>EndTime, "StartTime"=>StartTime); aws_config=aws_config)
get_insight_summaries(EndTime, StartTime, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = xray("POST", "/InsightSummaries", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("EndTime"=>EndTime, "StartTime"=>StartTime), params)); aws_config=aws_config)

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

Retrieves all sampling rules.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"NextToken"`: Pagination token.
"""
get_sampling_rules(; aws_config::AbstractAWSConfig=global_aws_config()) = xray("POST", "/GetSamplingRules"; aws_config=aws_config)
get_sampling_rules(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = xray("POST", "/GetSamplingRules", params; aws_config=aws_config)

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

Retrieves information about recent sampling results for all sampling rules.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"NextToken"`: Pagination token.
"""
get_sampling_statistic_summaries(; aws_config::AbstractAWSConfig=global_aws_config()) = xray("POST", "/SamplingStatisticSummaries"; aws_config=aws_config)
get_sampling_statistic_summaries(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = xray("POST", "/SamplingStatisticSummaries", params; aws_config=aws_config)

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

Requests a sampling quota for rules that the service is using to sample requests.

# Arguments
- `sampling_statistics_documents`: Information about rules that the service is using to
  sample requests.

"""
get_sampling_targets(SamplingStatisticsDocuments; aws_config::AbstractAWSConfig=global_aws_config()) = xray("POST", "/SamplingTargets", Dict{String, Any}("SamplingStatisticsDocuments"=>SamplingStatisticsDocuments); aws_config=aws_config)
get_sampling_targets(SamplingStatisticsDocuments, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = xray("POST", "/SamplingTargets", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("SamplingStatisticsDocuments"=>SamplingStatisticsDocuments), params)); aws_config=aws_config)

"""
    get_service_graph(end_time, start_time)
    get_service_graph(end_time, start_time, params::Dict{String,<:Any})

Retrieves a document that describes services that process incoming requests, and downstream
services that they call as a result. Root services process incoming requests and make calls
to downstream services. Root services are applications that use the AWS X-Ray SDK.
Downstream services can be other applications, AWS resources, HTTP web APIs, or SQL
databases.

# Arguments
- `end_time`: The end of the timeframe for which to generate a graph.
- `start_time`: The start of the time frame for which to generate a graph.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"GroupARN"`: The Amazon Resource Name (ARN) of a group based on which you want to
  generate a graph.
- `"GroupName"`: The name of a group based on which you want to generate a graph.
- `"NextToken"`: Pagination token.
"""
get_service_graph(EndTime, StartTime; aws_config::AbstractAWSConfig=global_aws_config()) = xray("POST", "/ServiceGraph", Dict{String, Any}("EndTime"=>EndTime, "StartTime"=>StartTime); aws_config=aws_config)
get_service_graph(EndTime, StartTime, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = xray("POST", "/ServiceGraph", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("EndTime"=>EndTime, "StartTime"=>StartTime), params)); aws_config=aws_config)

"""
    get_time_series_service_statistics(end_time, start_time)
    get_time_series_service_statistics(end_time, start_time, params::Dict{String,<:Any})

Get an aggregation of service statistics defined by a specific time range.

# Arguments
- `end_time`: The end of the time frame for which to aggregate statistics.
- `start_time`: The start of the time frame for which to aggregate statistics.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"EntitySelectorExpression"`: A filter expression defining entities that will be
  aggregated for statistics. Supports ID, service, and edge functions. If no selector
  expression is specified, edge statistics are returned.
- `"ForecastStatistics"`: The forecasted high and low fault count values. Forecast enabled
  requests require the EntitySelectorExpression ID be provided.
- `"GroupARN"`: The Amazon Resource Name (ARN) of the group for which to pull statistics
  from.
- `"GroupName"`: The case-sensitive name of the group for which to pull statistics from.
- `"NextToken"`: Pagination token.
- `"Period"`: Aggregation period in seconds.
"""
get_time_series_service_statistics(EndTime, StartTime; aws_config::AbstractAWSConfig=global_aws_config()) = xray("POST", "/TimeSeriesServiceStatistics", Dict{String, Any}("EndTime"=>EndTime, "StartTime"=>StartTime); aws_config=aws_config)
get_time_series_service_statistics(EndTime, StartTime, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = xray("POST", "/TimeSeriesServiceStatistics", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("EndTime"=>EndTime, "StartTime"=>StartTime), params)); aws_config=aws_config)

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

Retrieves a service graph for one or more specific trace IDs.

# Arguments
- `trace_ids`: Trace IDs of requests for which to generate a service graph.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"NextToken"`: Pagination token.
"""
get_trace_graph(TraceIds; aws_config::AbstractAWSConfig=global_aws_config()) = xray("POST", "/TraceGraph", Dict{String, Any}("TraceIds"=>TraceIds); aws_config=aws_config)
get_trace_graph(TraceIds, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = xray("POST", "/TraceGraph", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("TraceIds"=>TraceIds), params)); aws_config=aws_config)

"""
    get_trace_summaries(end_time, start_time)
    get_trace_summaries(end_time, start_time, params::Dict{String,<:Any})

Retrieves IDs and annotations for traces available for a specified time frame using an
optional filter. To get the full traces, pass the trace IDs to BatchGetTraces. A filter
expression can target traced requests that hit specific service nodes or edges, have
errors, or come from a known user. For example, the following filter expression targets
traces that pass through api.example.com:  service(\"api.example.com\")  This filter
expression finds traces that have an annotation named account with the value 12345:
annotation.account = \"12345\"  For a full list of indexed fields and keywords that you can
use in filter expressions, see Using Filter Expressions in the AWS X-Ray Developer Guide.

# Arguments
- `end_time`: The end of the time frame for which to retrieve traces.
- `start_time`: The start of the time frame for which to retrieve traces.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"FilterExpression"`: Specify a filter expression to retrieve trace summaries for
  services or requests that meet certain requirements.
- `"NextToken"`: Specify the pagination token returned by a previous request to retrieve
  the next page of results.
- `"Sampling"`: Set to true to get summaries for only a subset of available traces.
- `"SamplingStrategy"`: A parameter to indicate whether to enable sampling on trace
  summaries. Input parameters are Name and Value.
- `"TimeRangeType"`: A parameter to indicate whether to query trace summaries by TraceId or
  Event time.
"""
get_trace_summaries(EndTime, StartTime; aws_config::AbstractAWSConfig=global_aws_config()) = xray("POST", "/TraceSummaries", Dict{String, Any}("EndTime"=>EndTime, "StartTime"=>StartTime); aws_config=aws_config)
get_trace_summaries(EndTime, StartTime, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = xray("POST", "/TraceSummaries", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("EndTime"=>EndTime, "StartTime"=>StartTime), params)); aws_config=aws_config)

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

Returns a list of tags that are applied to the specified AWS X-Ray group or sampling rule.

# Arguments
- `resource_arn`: The Amazon Resource Number (ARN) of an X-Ray group or sampling rule.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"NextToken"`: A pagination token. If multiple pages of results are returned, use the
  NextToken value returned with the current page of results as the value of this parameter to
  get the next page of results.
"""
list_tags_for_resource(ResourceARN; aws_config::AbstractAWSConfig=global_aws_config()) = xray("POST", "/ListTagsForResource", Dict{String, Any}("ResourceARN"=>ResourceARN); aws_config=aws_config)
list_tags_for_resource(ResourceARN, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = xray("POST", "/ListTagsForResource", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ResourceARN"=>ResourceARN), params)); aws_config=aws_config)

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

Updates the encryption configuration for X-Ray data.

# Arguments
- `type`: The type of encryption. Set to KMS to use your own key for encryption. Set to
  NONE for default encryption.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"KeyId"`: An AWS KMS customer master key (CMK) in one of the following formats:    Alias
  - The name of the key. For example, alias/MyKey.    Key ID - The KMS key ID of the key. For
  example, ae4aa6d49-a4d8-9df9-a475-4ff6d7898456. AWS X-Ray does not support asymmetric CMKs.
     ARN - The full Amazon Resource Name of the key ID or alias. For example,
  arn:aws:kms:us-east-2:123456789012:key/ae4aa6d49-a4d8-9df9-a475-4ff6d7898456. Use this
  format to specify a key in a different account.   Omit this key if you set Type to NONE.
"""
put_encryption_config(Type; aws_config::AbstractAWSConfig=global_aws_config()) = xray("POST", "/PutEncryptionConfig", Dict{String, Any}("Type"=>Type); aws_config=aws_config)
put_encryption_config(Type, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = xray("POST", "/PutEncryptionConfig", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Type"=>Type), params)); aws_config=aws_config)

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

Used by the AWS X-Ray daemon to upload telemetry.

# Arguments
- `telemetry_records`:

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"EC2InstanceId"`:
- `"Hostname"`:
- `"ResourceARN"`:
"""
put_telemetry_records(TelemetryRecords; aws_config::AbstractAWSConfig=global_aws_config()) = xray("POST", "/TelemetryRecords", Dict{String, Any}("TelemetryRecords"=>TelemetryRecords); aws_config=aws_config)
put_telemetry_records(TelemetryRecords, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = xray("POST", "/TelemetryRecords", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("TelemetryRecords"=>TelemetryRecords), params)); aws_config=aws_config)

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

Uploads segment documents to AWS X-Ray. The X-Ray SDK generates segment documents and sends
them to the X-Ray daemon, which uploads them in batches. A segment document can be a
completed segment, an in-progress segment, or an array of subsegments. Segments must
include the following fields. For the full segment document schema, see AWS X-Ray Segment
Documents in the AWS X-Ray Developer Guide.  Required segment document fields     name -
The name of the service that handled the request.    id - A 64-bit identifier for the
segment, unique among segments in the same trace, in 16 hexadecimal digits.    trace_id - A
unique identifier that connects all segments and subsegments originating from a single
client request.    start_time - Time the segment or subsegment was created, in floating
point seconds in epoch time, accurate to milliseconds. For example, 1480615200.010 or
1.480615200010E9.    end_time - Time the segment or subsegment was closed. For example,
1480615200.090 or 1.480615200090E9. Specify either an end_time or in_progress.
in_progress - Set to true instead of specifying an end_time to record that a segment has
been started, but is not complete. Send an in-progress segment when your application
receives a request that will take a long time to serve, to trace that the request was
received. When the response is sent, send the complete segment to overwrite the in-progress
segment.   A trace_id consists of three numbers separated by hyphens. For example,
1-58406520-a006649127e371903a2de979. This includes:  Trace ID Format    The version number,
for instance, 1.   The time of the original request, in Unix epoch time, in 8 hexadecimal
digits. For example, 10:00AM December 2nd, 2016 PST in epoch time is 1480615200 seconds, or
58406520 in hexadecimal.   A 96-bit identifier for the trace, globally unique, in 24
hexadecimal digits.

# Arguments
- `trace_segment_documents`: A string containing a JSON document defining one or more
  segments or subsegments.

"""
put_trace_segments(TraceSegmentDocuments; aws_config::AbstractAWSConfig=global_aws_config()) = xray("POST", "/TraceSegments", Dict{String, Any}("TraceSegmentDocuments"=>TraceSegmentDocuments); aws_config=aws_config)
put_trace_segments(TraceSegmentDocuments, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = xray("POST", "/TraceSegments", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("TraceSegmentDocuments"=>TraceSegmentDocuments), params)); aws_config=aws_config)

"""
    tag_resource(resource_arn, tags)
    tag_resource(resource_arn, tags, params::Dict{String,<:Any})

Applies tags to an existing AWS X-Ray group or sampling rule.

# Arguments
- `resource_arn`: The Amazon Resource Number (ARN) of an X-Ray group or sampling rule.
- `tags`: A map that contains one or more tag keys and tag values to attach to an X-Ray
  group or sampling rule. For more information about ways to use tags, see Tagging AWS
  resources in the AWS General Reference. The following restrictions apply to tags:   Maximum
  number of user-applied tags per resource: 50   Maximum tag key length: 128 Unicode
  characters   Maximum tag value length: 256 Unicode characters   Valid values for key and
  value: a-z, A-Z, 0-9, space, and the following characters: _ . : / = + - and @   Tag keys
  and values are case sensitive.   Don't use aws: as a prefix for keys; it's reserved for AWS
  use. You cannot edit or delete system tags.

"""
tag_resource(ResourceARN, Tags; aws_config::AbstractAWSConfig=global_aws_config()) = xray("POST", "/TagResource", Dict{String, Any}("ResourceARN"=>ResourceARN, "Tags"=>Tags); aws_config=aws_config)
tag_resource(ResourceARN, Tags, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = xray("POST", "/TagResource", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ResourceARN"=>ResourceARN, "Tags"=>Tags), params)); aws_config=aws_config)

"""
    untag_resource(resource_arn, tag_keys)
    untag_resource(resource_arn, tag_keys, params::Dict{String,<:Any})

Removes tags from an AWS X-Ray group or sampling rule. You cannot edit or delete system
tags (those with an aws: prefix).

# Arguments
- `resource_arn`: The Amazon Resource Number (ARN) of an X-Ray group or sampling rule.
- `tag_keys`: Keys for one or more tags that you want to remove from an X-Ray group or
  sampling rule.

"""
untag_resource(ResourceARN, TagKeys; aws_config::AbstractAWSConfig=global_aws_config()) = xray("POST", "/UntagResource", Dict{String, Any}("ResourceARN"=>ResourceARN, "TagKeys"=>TagKeys); aws_config=aws_config)
untag_resource(ResourceARN, TagKeys, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = xray("POST", "/UntagResource", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ResourceARN"=>ResourceARN, "TagKeys"=>TagKeys), params)); aws_config=aws_config)

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

Updates a group resource.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"FilterExpression"`: The updated filter expression defining criteria by which to group
  traces.
- `"GroupARN"`: The ARN that was generated upon creation.
- `"GroupName"`: The case-sensitive name of the group.
- `"InsightsConfiguration"`: The structure containing configurations related to insights.
  The InsightsEnabled boolean can be set to true to enable insights for the group or false to
  disable insights for the group.   The NotifcationsEnabled boolean can be set to true to
  enable insights notifications for the group. Notifications can only be enabled on a group
  with InsightsEnabled set to true.
"""
update_group(; aws_config::AbstractAWSConfig=global_aws_config()) = xray("POST", "/UpdateGroup"; aws_config=aws_config)
update_group(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = xray("POST", "/UpdateGroup", params; aws_config=aws_config)

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

Modifies a sampling rule's configuration.

# Arguments
- `sampling_rule_update`: The rule and fields to change.

"""
update_sampling_rule(SamplingRuleUpdate; aws_config::AbstractAWSConfig=global_aws_config()) = xray("POST", "/UpdateSamplingRule", Dict{String, Any}("SamplingRuleUpdate"=>SamplingRuleUpdate); aws_config=aws_config)
update_sampling_rule(SamplingRuleUpdate, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = xray("POST", "/UpdateSamplingRule", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("SamplingRuleUpdate"=>SamplingRuleUpdate), params)); aws_config=aws_config)


text:
# devec.m
# Luca Brugnolini 2014
# Based on Kilian code
# For a vector (m*n,1), returns A (m,n) (see Hamilton p. 265)
# ------NOTE: pass the function the number of rows in the matrix A!!!
# code: --> A = devec(v,m)

function devec(v,m);

l = size(v,1);
n = itrunc(l/m);
A = zeros(n,n);

  for i = 1:n;
      A[:,i] =  v[((i-1)*m)+1:i*m]

  end;

    return A

end

ext: jl


text:
using ProgressLogging

using Term.progress
import Term.console: clear, cursor_position
import Term.progress: SPINNERS
import Term: tprintln, Panel, install_term_logger

install_term_logger()

function simple(; kwargs...)
    pbar = ProgressBar(; refresh_rate=60, expand=false, width=150, kwargs...)
    j1 = addjob!(pbar; N=100, description="First")

    with(pbar) do
        for i in 1:100
            update!(j1)
            sleep(0.01)
        end
    end
end

function multi_nested()
    pbar = ProgressBar(; refresh_rate=60, expand=false, width=150)
    with(pbar) do
        outer = addjob!(pbar; N=3, description="outer")
        for i in 1:3
            println("iii", i)
            inner = addjob!(pbar, N=100, description="inner $i")
            for j in 1:100
                update!(inner)
                sleep(0.005)
            end

            update!(outer)
            removejob!(pbar, inner)
            sleep(1)
        end
    end
end

function multi_nested_double()
    pbar = ProgressBar(; refresh_rate=60, expand=false, width=150)
    with(pbar) do
        outer = addjob!(pbar; N=3, description="outer")
        for i in 1:3
            println(i)
            inner = addjob!(pbar, N=100, description="inner $i")
            inner2 = addjob!(pbar, N=100, description="inner $i v2")
            for j in 1:100
                update!(inner)
                update!(inner2)
                sleep(0.005)
            end

            update!(outer)
            removejob!(pbar, inner)
        end
    end
end

function multi(; kwargs...)
    pbar = ProgressBar(; refresh_rate=60, expand=false, width=150, kwargs...)
    j1 = addjob!(pbar; N=50, description="First")
    j2 = addjob!(pbar; N=75, description="Second")
    j3 = addjob!(pbar; N=100, description="Third")

    text = [
        "   [italic white]Let",
        "   [green]the",
        "   [bright_blue]texts",
        "   [white]be",
        Panel("[bold red underline]shown!"; fit=true)
    ]
    idx = 1
    with(pbar) do
        for i in 1:100
            i % 20 == 0 && begin
                tprintln(text[idx])
                idx += 1
            end

            update!(j1)
            update!(j2)
            update!(j3)
            sleep(0.025)
        end
    end
end

function spinner()
    for spinner in keys(SPINNERS)
        columns_kwargs = Dict(
            :SpinnerColumn => Dict(:spinnertype => spinner, :style=>"bold green"),
            :CompletedColumn => Dict(:style => "dim")
        )

        pbar = ProgressBar(; columns=:spinner, columns_kwargs=columns_kwargs)
        with(pbar) do
            job = addjob!(pbar; description="[orange1]$spinner...")
            for i in 1:500
                update!(job)
                sleep(.0025)
            end
        end
    end
end

function mixed()
    columns_kwargs = Dict(
        :SpinnerColumn => Dict(:style=>"bold green"),
        :CompletedColumn => Dict(:style => "dim")
    )

    pbar = ProgressBar(; columns_kwargs=columns_kwargs)
    with(pbar) do
        j1 = addjob!(pbar; N=length(keys(SPINNERS)))

        for spinner in keys(SPINNERS)
            update!(j1)
            job = addjob!(pbar; description="...",)
            for i in 1:500
                update!(job)
                sleep(.001)
            end
        end
    end
end

function transientjobs()
    columns_kwargs = Dict(
        :SpinnerColumn => Dict(:style=>"bold green"),
        :CompletedColumn => Dict(:style => "dim")
    )

    pbar = ProgressBar(; columns_kwargs=columns_kwargs)
    with(pbar) do
        j1 = addjob!(pbar; N=length(keys(SPINNERS)))

        for spinner in keys(SPINNERS)
            println(spinner)
            update!(j1)
            job = addjob!(pbar; N=500, description="...", transient=true)
            for i in 1:500
                update!(job)
                sleep(.001)
            end
        end
    end
end

function progresslogging()
    @progress "outer...." for i in 1:6
        @progress "inner... $i" for j in  1:100
            sleep(0.01)
        end
    end
end

function _track()
    @track for i in 1:10
        sleep(0.1)
    end
end

clear()
println("starting")
print("_"^150)

# simple(; transient=false, columns=:detailed)
# multi(; transient=false)
# multi_nested()
# multi_nested_double()
# spinner()
# mixed()
# transientjobs()
# progresslogging()
_track()

println("done")


text:
#=
Copyright (c) 2015, Intel Corporation

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice,
      this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of Intel Corporation nor the names of its contributors
      may be used to endorse or promote products derived from this software
      without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
=#

# This file describes all the possible exceptions that may be raised during
# the execution of Sparse Accelerator, as well as their handlers.
# Usually, an exception handler prints out a nice diagnostic message, and
# returns to the original user code without optimizing it.

type UndescribedFunction <: Exception
    module_name     :: AbstractString
    function_name   :: AbstractString
    parameter_types :: Tuple
    ast             :: Any    # The ast that causes this exception.
end

type NonDistributiveFunction <: Exception
    module_name     :: AbstractString
    function_name   :: AbstractString
    parameter_types :: Tuple
end

type UnhandledExpr <: Exception
    head
    args
end

type ConflictPermutation <: Exception
    from   :: Any # InterDependenceGraphVertex
    vertex :: Any # InterDependenceGraphVertex
    color  :: Int
end

type UnresolvedFunction <: Exception
    head
    args
end

type UnhandledModuleOrFunctionName <: Exception
    arg
end

type UnknownCallFormat <: Exception
    head
    args
    parameter_types :: Tuple
end

type UnknownExprDistributivity <: Exception
    head
    args
end

type UnknownASTDistributivity <: Exception
    ast
    typ
end

type UnknownTypeToReorder <: Exception
    sym
    typ
end

type AsymmetricMatrixMarketFile <: Exception
    filename
end

type PostPatternReplacementFailure <: Exception
    pattern
end

type MatrixPropertiesUnavail <: Exception
    symexpr
end

max_stars_repo_name: IntelLabs/Sparso

max_issues_repo_name: IntelLabs/Sparso

max_forks_repo_name: IntelLabs/Sparso


text:
immutable NoncentralF <: ContinuousUnivariateDistribution
    ndf::Float64
    ddf::Float64
    ncp::Float64
    function NonCentralF(n::Real, d::Real, nc::Real)
		if n > 0.0 && d > 0.0 && nc >= 0.0
			new(float64(n), float64(d), float64(nc))
		else
			error("ndf and ddf must be > 0 and ncp >= 0")
		end
    end
end

@_jl_dist_3p NoncentralF nf

insupport(d::logNormal, x::Number) = isreal(x) && isfinite(x) && 0.0 <= x


text:
using FrechetDiff
using Documenter

makedocs(
    modules = [FrechetDiff],
    sitename = "FrechetDiff.jl",
    pages = [
        "Introduction" => "index.md",
        "Examples" => "examples.md",
        "How it works" => "howitworks.md",
        "Limitations" => "limitations.md",
    ],
    format = Documenter.HTML(),
)

deploydocs(
    repo = "github.com/cafaxo/FrechetDiff.jl.git",
)


text:
m = [1+1im 2+2im 3+3im;
     4+4im 5+5im 6+6im;
     7+7im 8+8im 9+9im]

v = [1.0,2.0,3.0]

qm = QuArray(m)
qv = QuArray(v)

@assert coeffs(qm*qm) == m*m
@assert coeffs(qm'*qm) == m'*m
@assert coeffs(qm*qm') == m*m'
@assert coeffs(qm'*qm') == m'*m'
@assert rawcoeffs(qm'*qm') == m*m

@assert coeffs(qm*qv) == m*v
@assert rawcoeffs(qv'*qm') == m*v
@assert coeffs(qv'*qm') == v'*m'
@assert coeffs(qm'*qv) == m'*v
@assert coeffs(qv'*qm) == v'*m

@assert qv'*qv == dot(v,v)
@assert coeffs(qv*qv') == v*v'

@assert qv'*qm*qv == first(v'*m*v)

@assert coeffs(2*im*qv) == 2*im*v
@assert coeffs(qv/2) == v/2
@assert coeffs(scale(2,qv)) == 2*v
@assert coeffs(qm' * -im) == -im * m'
@assert norm(qv) == norm(v)
@test_approx_eq coeffs(normalize(qv)) coeffs(qv)/norm(v)

# a simple test of the `==` operator
@assert qm*3im == scale!(3im, copy(qm))

# tests for Matrix Division
v1 =  [0.5+0*im, 0.+0.*im]
qv1 = normalize!(QuArray(v1))
@assert coeffs(\(sigmax,qv1)) == [0.+0.*im, 1.+0.*im]
@assert coeffs(\(sigmaz, sigmax)) == [0. 1.;-1. 0.]

# Trace
# Pauli matrices sigmax, sigmay, sigmaz are traceless
# Ref : http://en.wikipedia.org/wiki/Pauli_matrices#Algebraic_properties
@assert trace(sigmax) == zero(eltype(sigmax))
@assert trace(sigmax) == trace(sigmaz)

# Dot product
# Being defined both for vectors and dual vectors
# Related Ref : https://github.com/JuliaLang/julia/issues/11064
@assert dot(qv,qv) == dot(qv',qv')
# dot(A,B)=trace(A'*B) for the case of sigmax, sigmay results in no trace.
@assert dot(sigmax, sigmay) == trace(sigmaz)

# Vectorize
@assert vec(qv) == vec(qv')

# Expectation value
@assert expectationvalue(qv1, sigmax) == qv1'*sigmax*qv1
@assert expectationvalue(qm, lowerop(3)) == trace(qm*lowerop(3))


text:
#! format: off
# this file is automatically generated by SnoopCompile

function _precompile_()
    ccall(:jl_generating_output, Cint, ()) == 1 || return nothing
    let fbody = try Base.bodyfunction(which(fit!, (LinearMixedModel,))) catch missing end
    if !ismissing(fbody)
        precompile(fbody, (Bool,Bool,Nothing,Int64,typeof(fit!),LinearMixedModel,))
    end
end   # time: 6.582904
    Base.precompile(Tuple{typeof(fit!),GeneralizedLinearMixedModel})   # time: 6.0995073
    Base.precompile(Tuple{Type{LinearMixedModel},AbstractArray,Tuple,FormulaTerm,Vector{Any},Nothing})   # time: 2.2513552
    let fbody = try Base.bodyfunction(which(fit!, (LinearMixedModel{Float64},))) catch missing end
    if !ismissing(fbody)
        precompile(fbody, (Bool,Bool,Nothing,Int64,typeof(fit!),LinearMixedModel{Float64},))
    end
end   # time: 2.1690955
    isdefined(MixedModels, Symbol("#22#23")) && Base.precompile(Tuple{getfield(MixedModels, Symbol("#22#23"))})   # time: 0.70335937
    Base.precompile(Tuple{Type{LinearMixedModel},Vector{Float64},Tuple{Matrix{Float64}, ReMat{Float64, 2}},FormulaTerm{ContinuousTerm{Float64}, Tuple{MatrixTerm{Tuple{InterceptTerm{true}, ContinuousTerm{Float64}}}, RandomEffectsTerm}},Vector{Any},Nothing})   # time: 0.6737979
    Base.precompile(Tuple{typeof(deviance!),GeneralizedLinearMixedModel,Int64})   # time: 0.6433022
    Base.precompile(Tuple{Type{LinearMixedModel},Vector{Float64},FeTerm{Float64, Matrix{Float64}},Vector{AbstractReMat{Float64}},FormulaTerm{ContinuousTerm{Float64}, Tuple{MatrixTerm{Tuple{InterceptTerm{true}, ContinuousTerm{Float64}}}, RandomEffectsTerm}},Vector{Any},Nothing})   # time: 0.42538697
    Base.precompile(Tuple{typeof(deviance!),GeneralizedLinearMixedModel{Float64, Bernoulli{Float64}},Int64})   # time: 0.3716886
    Base.precompile(Tuple{typeof(fit!),GeneralizedLinearMixedModel{Float64, Bernoulli{Float64}}})   # time: 0.1559177
    Base.precompile(Tuple{typeof(adjA),Vector{Int32},Matrix{Float64}})   # time: 0.11642844
    Base.precompile(Tuple{typeof(apply_schema),Term,MultiSchema{FullRank},UnionAll})   # time: 0.0992202
    Base.precompile(Tuple{typeof(fit),Type{GeneralizedLinearMixedModel},FormulaTerm,NamedTuple,Bernoulli,LogitLink})   # time: 0.09839547
    Base.precompile(Tuple{typeof(scaleinflate!),UniformBlockDiagonal{Float64},ReMat{Float64, 2}})   # time: 0.07856259
    Base.precompile(Tuple{typeof(*),Adjoint{Float64, ReMat{Float64, 2}},ReMat{Float64, 2}})   # time: 0.064247385
    let fbody = try Base.bodyfunction(which(fit, (Type{LinearMixedModel},FormulaTerm,NamedTuple,))) catch missing end
    if !ismissing(fbody)
        precompile(fbody, (Any,Any,Bool,Bool,Any,Any,typeof(fit),Type{LinearMixedModel},FormulaTerm,NamedTuple,))
    end
end   # time: 0.0641711
    Base.precompile(Tuple{typeof(apply_schema),Tuple{RandomEffectsTerm, RandomEffectsTerm},MultiSchema{FullRank},Type{LinearMixedModel}})   # time: 0.062291622
    Base.precompile(Tuple{typeof(apply_schema),RandomEffectsTerm,MultiSchema{FullRank},Type{<:MixedModel}})   # time: 0.05415768
    Base.precompile(Tuple{typeof(rmulΛ!),Matrix{Float64},ReMat{Float64, 2}})   # time: 0.03744466
    Base.precompile(Tuple{typeof(rdiv!),Matrix{Float64},UpperTriangular{Float64, Adjoint{Float64, UniformBlockDiagonal{Float64}}}})   # time: 0.037409946
    Base.precompile(Tuple{typeof(LD),UniformBlockDiagonal{Float64}})   # time: 0.029826526
    Base.precompile(Tuple{typeof(*),Adjoint{Float64, ReMat{Float64, 1}},ReMat{Float64, 1}})   # time: 0.02977296
    Base.precompile(Tuple{typeof(GLM.wrkresp!),SubArray{Float64, 1, Matrix{Float64}, Tuple{Base.Slice{Base.OneTo{Int64}}, Int64}, true},GLM.GlmResp{Vector{Float64}, Bernoulli{Float64}, LogitLink}})   # time: 0.022571307
    Base.precompile(Tuple{typeof(scaleinflate!),Diagonal{Float64, Vector{Float64}},ReMat{Float64, 1}})   # time: 0.014116756
    Base.precompile(Tuple{typeof(cholUnblocked!),UniformBlockDiagonal{Float64},Type{Val{:L}}})   # time: 0.011265205
    Base.precompile(Tuple{Core.Type{MixedModels.GeneralizedLinearMixedModel{Float64, Distributions.Bernoulli}},LinearMixedModel,Any,Any,Vector,Any,Any,Any,Any,Any,Any,Any,Any,Any,Any})   # time: 0.010291444
    Base.precompile(Tuple{typeof(apply_schema),RandomEffectsTerm,MultiSchema{FullRank},Type{LinearMixedModel}})   # time: 0.009160354
    Base.precompile(Tuple{Type{FeTerm},Matrix{Float64},Any})   # time: 0.008526229
    Base.precompile(Tuple{typeof(apply_schema),Term,MultiSchema{FullRank},Type})   # time: 0.008067499
    Base.precompile(Tuple{typeof(apply_schema),Tuple{RandomEffectsTerm, RandomEffectsTerm},MultiSchema,Type})   # time: 0.006452216
    Base.precompile(Tuple{typeof(*),Adjoint{Float64, FeMat{Float64, Matrix{Float64}}},ReMat{Float64, 2}})   # time: 0.005299216
    Base.precompile(Tuple{typeof(reweight!),ReMat{Float64, 1},Vector{Float64}})   # time: 0.00500359
    Base.precompile(Tuple{typeof(reweight!),ReMat{Float64, 2},Vector{Float64}})   # time: 0.004945764
    Base.precompile(Tuple{typeof(_pushALblock!),Vector{AbstractMatrix{Float64}},Vector{AbstractMatrix{Float64}},Diagonal{Float64, Vector{Float64}}})   # time: 0.004846841
    Base.precompile(Tuple{typeof(apply_schema),Tuple{RandomEffectsTerm, RandomEffectsTerm},MultiSchema{FullRank},Type{<:MixedModel}})   # time: 0.004639013
    Base.precompile(Tuple{typeof(_pushALblock!),Vector{AbstractMatrix{Float64}},Vector{AbstractMatrix{Float64}},UniformBlockDiagonal{Float64}})   # time: 0.004212355
    isdefined(MixedModels, Symbol("#obj#92")) && Base.precompile(Tuple{getfield(MixedModels, Symbol("#obj#92")),Vector{Float64},Vector{Float64}})   # time: 0.00415707
    Base.precompile(Tuple{typeof(reweight!),LinearMixedModel{Float64},Vector{Float64}})   # time: 0.003799728
    Base.precompile(Tuple{typeof(copyto!),UniformBlockDiagonal{Float64},UniformBlockDiagonal{Float64}})   # time: 0.003437127
    Base.precompile(Tuple{typeof(cholUnblocked!),Matrix{Float64},Type{Val{:L}}})   # time: 0.002697967
    isdefined(MixedModels, Symbol("#97#99")) && Base.precompile(Tuple{getfield(MixedModels, Symbol("#97#99")),ReMat{Float64, 1}})   # time: 0.002630397
    Base.precompile(Tuple{typeof(apply_schema),ConstantTerm{Int64},MultiSchema{FullRank},UnionAll})   # time: 0.002451962
    Base.precompile(Tuple{typeof(apply_schema),ConstantTerm{Int64},MultiSchema{FullRank},Type})   # time: 0.002029733
    Base.precompile(Tuple{typeof(rmulΛ!),Matrix{Float64},ReMat{Float64, 1}})   # time: 0.00186467
    Base.precompile(Tuple{typeof(getproperty),LinearMixedModel,Symbol})   # time: 0.001859925
    isdefined(MixedModels, Symbol("#59#61")) && Base.precompile(Tuple{getfield(MixedModels, Symbol("#59#61")),ReMat{Float64, 1}})   # time: 0.00181014
    isdefined(MixedModels, Symbol("#58#60")) && Base.precompile(Tuple{getfield(MixedModels, Symbol("#58#60")),ReMat{Float64, 2}})   # time: 0.001746027
    Base.precompile(Tuple{typeof(mul!),Vector{Float64},ReMat{Float64, 1},Vector{Float64},Float64,Float64})   # time: 0.001642233
    Base.precompile(Tuple{typeof(cholUnblocked!),Diagonal{Float64, Vector{Float64}},Type{Val{:L}}})   # time: 0.001591365
    isdefined(MixedModels, Symbol("#59#61")) && Base.precompile(Tuple{getfield(MixedModels, Symbol("#59#61")),ReMat{Float64, 2}})   # time: 0.001566984
    Base.precompile(Tuple{Type{RandomEffectsTerm},Any,Any})   # time: 0.001504504
    isdefined(MixedModels, Symbol("#58#60")) && Base.precompile(Tuple{getfield(MixedModels, Symbol("#58#60")),ReMat{Float64, 1}})   # time: 0.001407624
    Base.precompile(Tuple{typeof(*),Adjoint{Float64, FeMat{Float64, Matrix{Float64}}},ReMat{Float64, 1}})   # time: 0.001186352
    Base.precompile(Tuple{Type{MultiSchema},FullRank})   # time: 0.001066192
    Base.precompile(Tuple{Type{ReMat{Float64, 2}},CategoricalTerm{DummyCoding, String, 17},Vector{Int32},Vector{String},Vector{String},Matrix{Float64},Matrix{Float64},LowerTriangular{Float64, Matrix{Float64}},Vector{Int64},SparseMatrixCSC{Float64, Int32},Matrix{Float64}})   # time: 0.001038076
end


text:
using BinaryBuilder

# Collection of sources required to build Ogg
sources = [
    "JuliaInterop"
]

# Bash recipe for building across all platforms
function getscript(version)
    shortversion = version[1:3]
    return """
    Julia_PREFIX=\$prefix

    # Build libcxxwrap
    cd \$WORKSPACE/srcdir/libcxxwrap-julia*
    mkdir build && cd build
    cmake -DJulia_PREFIX=\$Julia_PREFIX -DCMAKE_BUILD_TYPE=Release -DCMAKE_TOOLCHAIN_FILE=/opt/\$target/\$target.toolchain -DCMAKE_CXX_FLAGS="-march=x86-64" -DCMAKE_INSTALL_PREFIX=\${prefix} ..
    VERBOSE=ON cmake --build . --config Release --target install

    export JLCXX_DIR=\$prefix
    \$Julia_PREFIX/bin/julia -e 'using Pkg; pkg"add CxxWrap#master"; Pkg.build(); using CxxWrap'

    if [[ "\$target" == "x86_64-linux-gnu" ]]; then
        ctest -V
    fi
    """
end

# These are the platforms we will build for by default, unless further
# platforms are passed in on the command line
platforms = Platform[]
_abis(p) = (:gcc7,:gcc8)
_archs(p) = (:x86_64, :i686)
_archs(::Type{Linux}) = (:x86_64,)
for p in (Linux,Windows)
    for a in _archs(p)
        for abi in _abis(p)
            push!(platforms, p(a, compiler_abi=CompilerABI(abi,:cxx11)))
        end
    end
end
push!(platforms, MacOS(:x86_64))

# The products that we will ensure are always built
products = prefix -> [
    LibraryProduct(prefix, "libcxxwrap", :libcxxwrap),
]

# Dependencies that must be installed before this package can be built
dependencies = [
   "https://github.com/JuliaPackaging/JuliaBuilder/releases/download/v1.0.0-2/build_Julia.v1.0.0.jl"
]

# Build the tarballs, and possibly a `build.jl` as well.
version_number = get(ENV, "TRAVIS_TAG", "")
if version_number == ""
    version_number = "v0.99"
end

build_tarballs(ARGS, "libcxxwrap-julia-1.0", VersionNumber(version_number), sources, getscript("1.0.0"), platforms, products, dependencies)

max_stars_repo_name: r-barnes/libcxxwrap-julia

max_issues_repo_name: r-barnes/libcxxwrap-julia

max_forks_repo_name: r-barnes/libcxxwrap-julia


text:
const Romu32 = 0xc61d672b    # 3_323_815_723

function romu_quad32(state::RomuQuad32State)
    w, x, y, z = state.wstate, state.xstate, state.ystate, state.zstate
    state.wstate = Romu32 * z
    state.xstate = z + rol(w, 26)
    state.ystate = y - x
    y += w
    state.zstate = rol(y, 9)
    return state
end

function romu_trio32(state::RomuTrio32State)
    x, y, z = state.xstate, state.ystate, state.zstate
    state.xstate = Romu32 * z
    x = y - x
    state.ystate = rol(x, 6)
    z -= y
    state.zstate = rol(z, 22)
    return state
end

function romu_mono32(state::RomuMono32State)
    x = state.xstate
    x = x >> 16
    x = x * Romu32
    x = rol(x, 12)
    state.xstate = x
    return state
end

#=

//===== RomuQuad32 ================================================================================
//
// 32-bit arithmetic: Good for general purpose use.
// Est. capacity >= 2^62 bytes. Register pressure = 7. State size = 128 bits.

uint32_t wState, xState, yState, zState;  // set to nonzero seed

uint32_t romuQuad32 () {
   uint32_t wp = wState, xp = xState, yp = yState, zp = zState;
   wState = 3323815723u * zp;  // a-mult
   xState = zp + ROTL(wp,26);  // b-rotl, c-add
   yState = yp - xp;           // d-sub
   zState = yp + wp;           // e-add
   zState = ROTL(zState,9);    // f-rotl
   return xp;
}

//===== RomuTrio32 ===============================================================================
//
// 32-bit arithmetic: Good for general purpose use, except for huge jobs.
// Est. capacity >= 2^53 bytes. Register pressure = 5. State size = 96 bits.

uint32_t xState, yState, zState;  // set to nonzero seed

uint32_t romuTrio32_random () {
   uint32_t xp = xState, yp = yState, zp = zState;
   xState = 3323815723u * zp;
   yState = yp - xp; yState = ROTL(yState,6);
   zState = zp - yp; zState = ROTL(zState,22);
   return xp;
}

//===== RomuMono32 ===============================================================================
//
// 32-bit arithmetic: Suitable only up to 2^26 output-values. Outputs 16-bit numbers.
// Fixed period of (2^32)-47. Must be seeded using the romuMono32_init function.
// Capacity = 2^27 bytes. Register pressure = 2. State size = 32 bits.

uint32_t state;

void romuMono32_init (uint32_t seed) {
   state = (seed & 0x1fffffffu) + 1156979152u;  // Accepts 29 seed-bits.
}

uint16_t romuMono32_random () {
   uint16_t result = state >> 16;
   state *= 3611795771u;  state = ROTL(state,12);
   return result;
}
=#


text:
using Revise

using Juno, UnPack
using CSV, DataFrames, Serialization, Dates, Statistics, StatsBase, BenchmarkTools
using LinearAlgebra, Distributions, Distributed, VegaLite, Random
using CodecZlib, CodecZstd, GLM, XLSX, InteractiveUtils, Base.Iterators
using Optim, Pkg, SparseArrays#, BlackBoxOptim
using MCMCChains
using CUDA, GPUArrays
using Transducers, BangBang, LineSearches, LoopVectorization,Zygote

using Finometrics
using CUDA: CuVector, CuMatrix, CuArray

function oddball(N::Int = 10_000_000)
  df = DataFrame(g=rand(1:(N÷100) |> collect, N), x=rand(N))
  preconditioner = demeanξ ∘ quantiles
  df[!,:upperlower] = Vector{Union{Missing,Float64}}(undef, size(df,1))

  gdf = groupby(df, :g)
  Threads.@threads for i ∈ 1:length(gdf)
    oddball(gdf[i], preconditioner)
  end
end

@inline quantiles(ξraw::AbstractVector{<:Union{Real,Missing}}) = (
  length(ξraw) .- competerank(ξraw,rev=true) .+ 1)./length(ξraw)

@inline demeanξ(ξraw::AbstractVector{<:Union{Real, Missing}}) = ξraw .- mean(skipmissing(ξraw))

function oddball(df::AbstractDataFrame, preconditioner; thresholds = (lower=0.33, upper=0.67))

  ξ = preconditioner(df[:,:x])
  ranks::Vector{Float64} = ξ |> quantiles
  df[:,:upperlower] .= ((ranks .≥ thresholds.upper) .- (ranks .< thresholds.lower))
  (minimum(df.upperlower) ≈ -1.0 * maximum(df.upperlower)) || error("Ranking Failed!!
    $((ranks .≥ thresholds.upper) .- (ranks .< thresholds.lower))
    typeof:$(typeof((ranks .≥ thresholds.upper) .- (ranks .< thresholds.lower)))")

end

@time oddball()

max_stars_repo_name: clintonTE/CCA

max_issues_repo_name: clintonTE/CCA

max_forks_repo_name: clintonTE/CCA


text:
using Combinatorics: permutations

export Miller, MillerBravais, ReciprocalMiller, ReciprocalMillerBravais
export family, @m_str

"Represent the Miller indices or Miller–Bravais indices."
abstract type Indices <: AbstractVector{Int} end
abstract type AbstractMiller <: Indices end
"""
    Miller(i, j, k)

Represent the Miller indices in the real space (crystal directions).
"""
struct Miller <: AbstractMiller
    data::SVector{3,Int}
    Miller(v) = new(iszero(v) ? v : v .÷ gcd(v))
end
Miller(i, j, k) = Miller([i, j, k])
"""
    ReciprocalMiller(i, j, k)

Represent the Miller indices in the reciprocal space (planes).
"""
struct ReciprocalMiller <: AbstractMiller
    data::SVector{3,Int}
    ReciprocalMiller(v) = new(iszero(v) ? v : v .÷ gcd(v))
end
ReciprocalMiller(i, j, k) = ReciprocalMiller([i, j, k])
abstract type AbstractMillerBravais <: Indices end
"""
    MillerBravais(i, j, k, l)

Represent the Miller–Bravais indices in the real space (crystal directions).
"""
struct MillerBravais <: AbstractMillerBravais
    data::SVector{4,Int}
    function MillerBravais(v)
        @assert v[3] == -v[1] - v[2] "the 3rd index of `MillerBravais` should equal to the negation of the first two!"
        return new(iszero(v) ? v : v .÷ gcd(v))
    end
end
MillerBravais(i, j, k, l) = MillerBravais([i, j, k, l])
"""
    ReciprocalMillerBravais(i, j, k, l)

Represent the Miller–Bravais indices in the reciprocal space (planes).
"""
struct ReciprocalMillerBravais <: AbstractMillerBravais
    data::SVector{4,Int}
    function ReciprocalMillerBravais(v)
        @assert v[3] == -v[1] - v[2] "the 3rd index of `MillerBravais` should equal to the negation of the first two!"
        return new(iszero(v) ? v : v .÷ gcd(v))
    end
end
ReciprocalMillerBravais(i, j, k, l) = ReciprocalMillerBravais([i, j, k, l])

# This is a helper function and should not be exported!
function _indices_str(r::Regex, s::AbstractString)
    m = match(r, strip(s))
    if m === nothing
        throw(ArgumentError("not a valid expression!"))
    else
        brackets = first(m.captures) * last(m.captures)
        indices = map(filter(x -> x !== nothing, m.captures[2:(end-1)])) do index
            parse(Int, index)
        end
        if brackets in ("()", "{}")
            if m[4] === nothing
                return ReciprocalMiller(indices...)
            else
                return ReciprocalMillerBravais(indices...)
            end
        elseif brackets ∈ ("[]", "<>")
            if m[4] === nothing
                return Miller(indices...)
            else
                return MillerBravais(indices...)
            end
        else
            @assert false "this should never happen!"
        end
    end
end

"""
    m_str(s)

Generate the Miller indices or Miller–Bravais indices quickly.

# Examples
```jldoctest
julia> m"[-1, 0, 1]"
3-element Miller:
 -1
  0
  1

julia> m"<2, -1, -1, 3>"
4-element MillerBravais:
  2
 -1
 -1
  3

julia> m"(-1, 0, 1)"
3-element ReciprocalMiller:
 -1
  0
  1

julia> m"(1, 0, -1, 0)"
4-element ReciprocalMillerBravais:
  1
  0
 -1
  0
```
"""
macro m_str(s)
    r =
        r"([({[<])\s*([-+]?[0-9]+)[\s,]+([-+]?[0-9]+)[\s,]+([-+]?[0-9]+)?[\s,]+([-+]?[0-9]+)[\s,]*([>\]})])"
    return _indices_str(r, s)
end

"""
    family(x::Union{Miller,MillerBravais,ReciprocalMiller,ReciprocalMillerBravais})

List the all the directions/planes that are equivalent to `x` by symmetry.
"""
function family(mb::T) where {T<:AbstractMillerBravais}
    perm = collect(permutations(mb[1:3]))  # Permute the first 3 indices for equivalent basis vectors
    negate = -perm  # Use negative indices
    pool = unique(append!(perm, negate))
    allowed = filter(v -> v[3] == -v[1] - v[2], pool)
    return map(allowed) do x
        T(x..., mb[4])  # Add the 4th index back
    end
end
function family(m::T) where {T<:AbstractMiller}
    mb = convert(T <: Miller ? MillerBravais : ReciprocalMillerBravais, m)  # Real or reciprocal space
    vec = family(mb)
    return map(x -> convert(T, x), vec)
end

Base.size(::AbstractMiller) = (3,)
Base.size(::AbstractMillerBravais) = (4,)

Base.IndexStyle(::Type{<:Indices}) = IndexLinear()

Base.getindex(x::Indices, i) = getindex(x.data, i)

Base.convert(::Type{T}, x::T) where {T<:Indices} = x
Base.convert(::Type{Miller}, mb::MillerBravais) =
    Miller(2 * mb[1] + mb[2], 2 * mb[2] + mb[1], mb[4])
Base.convert(::Type{ReciprocalMiller}, mb::ReciprocalMillerBravais) =
    ReciprocalMiller(mb[1], mb[2], mb[4])
Base.convert(::Type{MillerBravais}, m::Miller) =
    MillerBravais(2 * m[1] - m[2], 2 * m[2] - m[1], -(m[1] + m[2]), 3 * m[3])
Base.convert(::Type{ReciprocalMillerBravais}, m::ReciprocalMiller) =
    ReciprocalMillerBravais(m[1], m[2], -(m[1] + m[2]), m[3])

Base.show(io::IO, x::Union{Miller,MillerBravais}) = print(io, '<', join(x.data, " "), '>')
Base.show(io::IO, x::Union{ReciprocalMiller,ReciprocalMillerBravais}) =
    print(io, '{', join(x.data, " "), '}')


text:
const JLFORMATARGS =
    (indent = 4, margin = 92, overwrite = true, verbose = false, always_for_in = false)

function format_file(file::AbstractString; kwargs...)
    JuliaFormatter.format_file(file; JLFORMATARGS..., kwargs...)
end

function format(paths...; kwargs...)
    JuliaFormatter.format(paths...; JLFORMATARGS..., kwargs...)
end

function format(pkg::Module; kwargs...)
    JuliaFormatter.format(pkgdir(pkg); JLFORMATARGS..., kwargs...)
end

cdtempdir(f) = mktempdir(dir->cd(f, dir))

# copied from Documenter.jl
function genkeys(; user = "\$USER", repo = "\$REPO", comment = "lyceumdevs@gmail.com")
    # Error checking. Do the required programs exist?
    success(`which which`) || error("'which' not found.")
    success(`which ssh-keygen`) || error("'ssh-keygen' not found.")

    directory = pwd()
    filename = tempname()

    isfile(filename) &&
    error("temporary file '$(filename)' already exists in working directory")
    isfile("$(filename).pub") &&
    error("temporary file '$(filename).pub' already exists in working directory")

    # Generate the ssh key pair.
    success(`ssh-keygen -N "" -C $comment -f $filename`) ||
    error("failed to generate a SSH key pair.")

    # Prompt user to add public key to github then remove the public key.
    let url = "https://github.com/$user/$repo/settings/keys"
        @info("add the public key below to $url with read/write access:")
        println("\n", read("$filename.pub", String))
        rm("$filename.pub")
    end

    # Base64 encode the private key and prompt user to add it to travis. The key is
    # *not* encoded for the sake of security, but instead to make it easier to
    # copy/paste it over to travis without having to worry about whitespace.
    let travis_url = "https://travis-ci.com/$user/$repo/settings",
        github_url = "https://github.com/$user/$repo/settings/secrets"

        @info(
            "add a secure environment variable named to " *
            "$(travis_url) (if you deploy using Travis CI) or " *
            "$(github_url) (if you deploy using GitHub Actions) with value:"
        )
        println("\n", base64encode(read(filename, String)), "\n")
        rm(filename)
    end
end

function snooppkg(pkg::Module; overwrite::Bool = false) #flags::Vector{String}=String[])
    @warn "Switch to using snoopi"

    d = pkgdir(pkg)
    name = nameof(pkg)
    flags = ["--project=$d"]
    precompfile = joinpath(d, "src", "precompile.jl")
    logfile = "/tmp/$(name)_snoop.log"
    if isfile(precompfile) && !overwrite
        error("$precompfile already exists but overwrite was false")
    end

    ex = quote
        using $name
        include(joinpath($d, "test", "runtests.jl"))
    end

    SnoopCompile.snoopc(flags, logfile, ex)
    data = SnoopCompile.read(logfile)
    pc = SnoopCompile.parcel(reverse!(data[2]))
    SnoopCompile.write("/tmp/precompile", pc)
    cp("/tmp/precompile/precompile_$(name).jl", precompfile)
end

regspec(reg::RegistrySpec) = regspec(reg.uuid, name=reg.name, url=reg.url, path=reg.path)
function regspec(uuid::UUID)
    registries = Pkg.Types.collect_registries()
    idx = findfirst(r -> r.uuid == uuid, registries)
    isnothing(idx) ? nothing : registries[idx]
end

function regspec(uuid; name = nothing, url = nothing, path = nothing)
    uuid = isa(uuid, UUID) ? uuid : UUID(uuid)
    spec = regspec(uuid)
    if isnothing(spec)
        isnothing(name) ||
        isnothing(url) || isnothing(path) && error("Registry not found. Must specify spec")
        return RegistrySpec(uuid = uuid, name = name, url = url, path = path)
    else
        return RegistrySpec(
            name = isnothing(spec.name) ? name : spec.name,
            uuid = isnothing(spec.uuid) ? uuid : spec.uuid,
            url = githttpsurl(isnothing(spec.url) ? url : spec.url),
            path = isnothing(spec.path) ? path : spec.path,
        )
    end
end

pkgdir(pkg::Module) = normpath(joinpath(dirname(Base.pathof(pkg)), ".."))

hasmanifest(pkgdir::String) = !isnothing(Pkg.Operations.manifestfile_path(pkgdir, strict=true))
hasproject(pkgdir::String) = !isnothing(Pkg.Operations.projectfile_path(pkgdir, strict=true))

function parsetomls(pkgdir::String)
    manifestpath = Pkg.Operations.manifestfile_path(pkgdir, strict = true)
    projectpath = Pkg.Operations.projectfile_path(pkgdir, strict = true)
    (project = _parsetoml(projectpath), manifest = _parsetoml(manifestpath))
end
function _parsetoml(tomlpath)
    if isnothing(tomlpath) || !isfile(tomlpath)
        return nothing
    else
        string = read(tomlpath, String)
        (path = tomlpath, string = string, dict = Pkg.TOML.parse(string))
    end
end

function with_sandbox_env(
    fn::Function,
    project::AbstractString = Base.active_project();
    copyall::Bool = false,
    extra_load_paths::Vector{<:AbstractString} = AbstractString[],
    default_load_path = false,
    tempdir = true
)
    if isdir(project)
        project = Pkg.Operations.projectfile_path(project, strict = true)
        isnothing(project) && throw(ArgumentError("No project file found in $project"))
    end

    old_dir = pwd()
    old_load_path = copy(LOAD_PATH)
    old_project = Base.active_project()

    mktempdir() do sandbox
        if copyall
            cpinto(dirname(project), sandbox)
        else
            manifest = Pkg.Operations.manifestfile_path(dirname(project), strict = true)
            !isnothing(manifest) && cp(manifest, joinpath(sandbox, basename(manifest)))
            cp(project, joinpath(sandbox, basename(project)))
        end

        try
            cd(sandbox)
            if default_load_path
                empty!(LOAD_PATH)
                Base.init_load_path()
            end
            Pkg.activate(pwd())
            append!(LOAD_PATH, map(normpath, extra_load_paths))
            return fn()
        finally
            cd(old_dir)
            append!(empty!(LOAD_PATH), old_load_path)
            Pkg.activate(old_project)
        end
    end
end

function cpinto(srcdir::AbstractString, dstdir::AbstractString)
    isdir(srcdir) || throw(ArgumentError("Expected a directory for `srcdir`, got $srcdir"))
    isdir(dstdir) || throw(ArgumentError("Expected a directory for `dstdir`, got $dstdir"))
    for file_or_dir in readdir(srcdir)
        cp(joinpath(srcdir, file_or_dir), joinpath(dstdir, file_or_dir))
    end
end

runzshinter(cmd::Cmd) = runzsh(join(cmd.exec, " "))
runzshinter(cmdstr::String) = run(`zsh -ic "$cmdstr; exit"`)

function envinfo(dstpath::AbstractString)
    mktempdir() do dir
        env = Pkg.Types.Context().env
        Pkg.Types.write_project(env.project, joinpath(dir, "Project.toml"))
        Pkg.Types.write_manifest(env.manifest, joinpath(dir, "Manifest.toml"))
        open(joinpath(dir, "versioninfo.txt"), "w") do io
            versioninfo(io)
        end
        Pkg.PlatformEngines.probe_platform_engines!()
        Pkg.PlatformEngines.package(dir, dstpath)
    end
end


text:
using EFTfitter
using IntervalSets
using BAT

@testset "Test inputs with NuisanceCorrelation" begin

    parameters1 = BAT.NamedTupleDist(
        p1 = -20..20,
        p2 = -10..10,
    )

    function testfunc1(params)
        c = [20.12, 5.56, 325.556]
        return c[1] * params.p1^2 + c[2] * params.p1 * params.p2 + c[3] * params.p2^2
    end

    measurements1 = (
        meas1 = Measurement(testfunc1, 111.1,
        uncertainties = (unc1=10.1, unc2=12.2, unc3=13.3), active=true),

        meas2 = Measurement(Observable(testfunc1, min=0, max=1000), 222.2,
        uncertainties = (unc1=20.1, unc2=20.2, unc3=23.3), active=false),

        meas3 = Measurement(Observable(testfunc1, min=0, max=1000), 333.3,
        uncertainties = (unc1=30.1, unc2=30.2, unc3=30.3), active=true),

        meas4 = MeasurementDistribution(Function[testfunc1, testfunc1, testfunc1],
        [10, 20, 30], uncertainties = (unc1=[0.11, 0.12, 0.13], unc2=[0.21, 0.22, 0.23], unc3=[0.31, 0.32, 0.33]),
        active = [true, false, true], bin_names=[Symbol("0_5"), Symbol("5_10"), Symbol("10_20")])
    )

    corr_matrix = to_correlation_matrix(measurements1,
        (:meas1, :meas2, 0.12), # will be ignored later in EFTfitterModel
        (:meas1, :meas3, 0.13),
        (:meas1, :meas4_0_5, 0.141),
        (:meas1, :meas4_5_10, 0.142), # will be ignored later in EFTfitterModel
        (:meas1, :meas4_10_20, 0.143), # will be ignored later in EFTfitterModel
        (:meas4_0_5, :meas4_5_10, 0.412), # will be ignored later in EFTfitterModel
        (:meas4_0_5, :meas4_5_10, 0.413),
        (:meas4_0_5, :meas4_0_5, 0.9) # will be ignored later in EFTfitterModel
    )

    @test corr_matrix ≈ [ 1.0    0.12  0.13  0.141  0.142  0.143;
                         0.12   1.0   0.0   0.0    0.0    0.0;
                         0.13   0.0   1.0   0.0    0.0    0.0;
                         0.141  0.0   0.0   1.0    0.413  0.0;
                         0.142  0.0   0.0   0.413  1.0    0.0;
                         0.143  0.0   0.0   0.0    0.0    1.0] rtol = 0.01

    correlations1 = (
        unc1 = NoCorrelation(active=true),

        # wrong matrix size for number of measurements, will be ignored if active=false:
        unc2 = Correlation([1.0 0.5 0.7;
                            0.5 1.0 0.6;
                            0.7 0.6 1.0], active=false),

        unc3 = Correlation(corr_matrix)
    )

    nuisance_correlations = (
        ρ1 = NuisanceCorrelation(:unc1, :meas1, :meas3, 0..0.5),
        ρ2 = NuisanceCorrelation(:unc1, :meas1, :meas2, truncated(Normal(0, 1), 0, 0.9)),
    )

    model1 = EFTfitterModel(parameters1, measurements1, correlations1, nuisance_correlations)

    @testset "Test EFTfitterModel" begin
        @test length(model1.measurements) == 4
        @test model1.measurements.meas1 == Measurement(Observable(testfunc1, -Inf, Inf), 111.1, (unc1=10.1, unc3=13.3), true)
        @test model1.measurements.meas4_10_20 == Measurement(Observable(testfunc1, -Inf, Inf), 30., (unc1=0.13, unc3=0.33), true)
        @test keys(model1.measurements) == (:meas1, :meas3, :meas4_0_5, :meas4_10_20)

        @test model1.measurementdistributions.meas4.observable == [Observable(testfunc1, -Inf, Inf), Observable(testfunc1, -Inf, Inf)]
        @test model1.measurementdistributions.meas4.value == [10., 30.]
        @test model1.measurementdistributions.meas4.uncertainties == (unc1=[0.11, 0.13], unc3=[0.31, 0.33])
        @test model1.measurementdistributions.meas4.active == [true, true]
        @test model1.measurementdistributions.meas4.bin_names == [Symbol("0_5"), Symbol("10_20")]

        @test length(model1.parameters._internal_distributions) == 3
        @test model1.parameters._internal_distributions.ρ1 == Uniform(0, 0.5)

        @test model1.nuisances == (ρ1=NuisanceCorrelation(:unc1, :meas1, :meas3, Uniform(0, 0.5)),)
    end

    @testset "Test EFTfitterDensity" begin
        eftfitter_density = PosteriorDensity(model1).likelihood
        @test isa(eftfitter_density, EFTfitterDensityNuisance)

        @test eftfitter_density.measured_values == [111.1, 333.3, 10, 30]
        @test eftfitter_density.observable_functions == [testfunc1, testfunc1, testfunc1, testfunc1]
        @test eftfitter_density.observable_mins == [-Inf, 0, -Inf, -Inf]
        @test eftfitter_density.observable_maxs == [Inf, 1000.0, Inf, Inf]
        @test eftfitter_density.check_bounds == true
        @test eftfitter_density.covs ≈ [[102.01    0.0   0.0     0.0;
                                       0.0   906.01  0.0     0.0;
                                       0.0     0.0   0.0121  0.0;
                                       0.0     0.0   0.0     0.0169],
                                      [176.89       52.3887  0.581343  0.627627;
                                      52.3887    918.09    0.0       0.0;
                                       0.581343    0.0     0.0961    0.0;
                                       0.627627    0.0     0.0       0.1089]] rtol=0.001

        @test eftfitter_density.nuisances == [EFTfitter._NuisanceCorrelation(1, 1, 2, :ρ1)]

        @test EFTfitter.get_current_invcov(eftfitter_density, (p1=0.0, p2=0.0, ρ1=0)) ≈ [0.00368812   -0.000105924  -0.0198158    -0.0184004;
                                                                                -0.000105924   0.000551258   0.000569114   0.000528464;
                                                                                -0.0198158     0.000569114   9.34861       0.0988625;
                                                                                -0.0184004     0.000528464   0.0988625     8.04093] rtol=0.01

     @test EFTfitter.get_current_invcov(eftfitter_density, (p1=0.0, p2=0.0, ρ1=0.2)) ≈ [0.00376476   -0.000233614  -0.0202275   -0.0187827
                                                                                -0.000233614   0.000562712   0.00125517   0.00116552;
                                                                                -0.0202275     0.00125517    9.35082      0.100917;
                                                                                -0.0187827     0.00116552    0.100917     8.04283] rtol=0.01
        # test evaluation of correct likelihood value at a few points:
        @test BAT.eval_logval_unchecked(eftfitter_density, (p1=0.0, p2=0.0, ρ1=0)) ≈ -8177.6043 rtol=0.01
        @test BAT.eval_logval_unchecked(eftfitter_density, (p1=10.0, p2=-30.0, ρ1=0)) ≈ -Inf
        @test BAT.eval_logval_unchecked(eftfitter_density, (p1=1.5, p2=-0.9, ρ1=0)) ≈ -1.39839704e6 rtol=0.01
        @test BAT.eval_logval_unchecked(eftfitter_density, (p1=-1.2, p2=-0.8, ρ1=0)) ≈ -877307.384161 rtol=0.01

        @test BAT.eval_logval_unchecked(eftfitter_density, (p1=0.0, p2=0.0, ρ1=0.1)) ≈ -8182.2489 rtol=0.01
        @test BAT.eval_logval_unchecked(eftfitter_density, (p1=10.0, p2=-30.0, ρ1=0.2)) ≈ -Inf
        @test BAT.eval_logval_unchecked(eftfitter_density, (p1=1.5, p2=-0.9, ρ1=0.4)) ≈ -1.39997084e6 rtol=0.01
    end

end


text:
using AsapMapper
using Test
using Plots

include("asap2.jl")
include("models.jl")


text:
const liblapack = Base.liblapack_name

import Base.blasfunc

import Base.LinAlg: BlasFloat, Char, BlasInt, LAPACKException,
    DimensionMismatch, SingularException, PosDefException, chkstride1, chksquare

#Generic LAPACK error handlers
macro assertargsok() #Handle only negative info codes - use only if positive info code is useful!
    :(info[1]<0 && throw(ArgumentError("invalid argument #$(-info[1]) to LAPACK call")))
end
macro lapackerror() #Handle all nonzero info codes
    :(info[1]>0 ? throw(LAPACKException(info[1])) : @assertargsok )
end

macro assertnonsingular()
    :(info[1]>0 && throw(SingularException(info[1])))
end
macro assertposdef()
    :(info[1]>0 && throw(PosDefException(info[1])))
end

#Check that upper/lower (for special matrices) is correctly specified
function chkuplo(uplo::Char)
    (uplo=='U' || uplo=='L') ||
      throw(ArgumentError(string("uplo argument must be 'U' (upper) or 'L' (lower), got $uplo")))
end

#Check that {c}transpose is correctly specified
function chktrans(trans::Char)
    (trans=='N' || trans=='C' || trans=='T') ||
      throw(ArgumentError(string("trans argument must be 'N' (no transpose), 'T' (transpose), or 'C' (conjugate transpose), got $trans")))
end

#Check that left/right hand side multiply is correctly specified
function chkside(side::Char)
    (side=='L' || side=='R') ||
      throw(ArgumentError(string("side argument must be 'L' (left hand multiply) or 'R' (right hand multiply), got $side")))
end

#Check that unit diagonal flag is correctly specified
function chkdiag(diag::Char)
    (diag=='U' || diag=='N') ||
      throw(ArgumentError(string("diag argument must be 'U' (unit diagonal) or 'N' (non-unit diagonal), got $diag")))
end

# (GT) General tridiagonal, decomposition, solver and direct solver
for (gttrf, gttrs, elty) in
    ((:dgttrf_,:dgttrs_,:Float64),
     (:sgttrf_,:sgttrs_,:Float32),
     (:zgttrf_,:zgttrs_,:Complex128),
     (:cgttrf_,:cgttrs_,:Complex64))
    @eval begin
        #       SUBROUTINE DGTTRF( N, DL, D, DU, DU2, IPIV, INFO )
        #       .. Scalar Arguments ..
        #       INTEGER            INFO, N
        #       .. Array Arguments ..
        #       INTEGER            IPIV( * )
        #       DOUBLE PRECISION   D( * ), DL( * ), DU( * ), DU2( * )
        function gttrf!(dl::StridedVector{$elty}, d::StridedVector{$elty}, du::StridedVector{$elty},
                        du2::StridedVector{$elty}, ipiv::StridedVector{BlasInt})
            n    = length(d)
            if length(dl) != n - 1
                throw(DimensionMismatch("Subdiagonal has length $(length(dl)), but should be $(n - 1)"))
            end
            if length(du) != n - 1
                throw(DimensionMismatch("Superdiagonal has length $(length(du)), but should be $(n - 1)"))
            end
            #du2  = similar(d, $elty, n-2)
            #ipiv = similar(d, BlasInt, n)
            info = Array(BlasInt, 1)
            ccall(($(blasfunc(gttrf)), liblapack), Void,
                  (Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{$elty}, Ptr{$elty},
                   Ptr{BlasInt}, Ptr{BlasInt}),
                  &n, dl, d, du, du2, ipiv, info)
            @lapackerror
            dl, d, du, du2, ipiv
        end
        #       SUBROUTINE DGTTRS( TRANS, N, NRHS, DL, D, DU, DU2, IPIV, B, LDB, INFO )
        #       .. Scalar Arguments ..
        #       CHARACTER          TRANS
        #       INTEGER            INFO, LDB, N, NRHS
        #       .. Array Arguments ..
        #       INTEGER            IPIV( * )
        #       DOUBLE PRECISION   B( LDB, * ), D( * ), DL( * ), DU( * ), DU2( * )
        function gttrs!(trans::Char, dl::StridedVector{$elty}, d::StridedVector{$elty},
                        du::StridedVector{$elty}, du2::StridedVector{$elty},
                        ipiv::StridedVector{BlasInt}, B::StridedVecOrMat{$elty})
            chktrans(trans)
            chkstride1(B)
            n = length(d)
            if length(dl) != n - 1
                throw(DimensionMismatch("Subdiagonal has length $(length(dl)), but should be $(n - 1)"))
            end
            if length(du) != n - 1
                throw(DimensionMismatch("Superdiagonal has length $(length(du)), but should be $(n - 1)"))
            end
            if n != size(B,1)
                throw(DimensionMismatch("B has leading dimension $(size(B,1)), but should have $n"))
            end

            info = Array(BlasInt, 1)
            ccall(($(blasfunc(gttrs)), liblapack), Void,
                   (Ptr{UInt8}, Ptr{BlasInt}, Ptr{BlasInt},
                    Ptr{$elty}, Ptr{$elty}, Ptr{$elty}, Ptr{$elty},
                    Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}),
                   &trans, &n, &size(B,2), dl, d, du, du2, ipiv, B, &max(1,stride(B,2)), info)
             @lapackerror
             B
         end
    end
end

## (PT) positive-definite, symmetric, tri-diagonal matrices
## Direct solvers for general tridiagonal and symmetric positive-definite tridiagonal
for (pttrf, elty, relty) in
    ((:dpttrf_,:Float64,:Float64),
     (:spttrf_,:Float32,:Float32),
     (:zpttrf_,:Complex128,:Float64),
     (:cpttrf_,:Complex64,:Float32))
    @eval begin
        #       SUBROUTINE DPTTRF( N, D, E, INFO )
        #       .. Scalar Arguments ..
        #       INTEGER            INFO, N
        #       .. Array Arguments ..
        #       DOUBLE PRECISION   D( * ), E( * )
        function pttrf!(D::StridedVector{$relty}, E::StridedVector{$elty})
            n = length(D)
            if length(E) != n - 1
                throw(DimensionMismatch("E has length $(length(E)), but needs $(n - 1)"))
            end
            info = Array(BlasInt, 1)
            ccall(($(blasfunc(pttrf)), liblapack), Void,
                  (Ptr{BlasInt}, Ptr{$relty}, Ptr{$elty}, Ptr{BlasInt}),
                  &n, D, E, info)
            @lapackerror
            D, E
        end
    end
end

for (pttrs, elty, relty) in
    ((:dpttrs_,:Float64,:Float64),
     (:spttrs_,:Float32,:Float32))
    @eval begin
        #       SUBROUTINE DPTTRS( N, NRHS, D, E, B, LDB, INFO )
        #       .. Scalar Arguments ..
        #       INTEGER            INFO, LDB, N, NRHS
        #       .. Array Arguments ..
        #       DOUBLE PRECISION   B( LDB, * ), D( * ), E( * )
        function pttrs!(D::StridedVector{$relty}, E::StridedVector{$elty}, B::StridedVecOrMat{$elty})
            chkstride1(B)
            n = length(D)
            if length(E) != n - 1
                throw(DimensionMismatch("E has length $(length(E)), but needs $(n - 1)"))
            end
            if n != size(B,1)
                throw(DimensionMismatch("B has first dimension $(size(B,1)) but needs $n"))
            end
            info = Array(BlasInt, 1)
            ccall(($(blasfunc(pttrs)), liblapack), Void,
                  (Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$relty}, Ptr{$elty},
                   Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}),
                  &n, &size(B,2), D, E, B, &max(1,stride(B,2)), info)
            @lapackerror
            B
        end
    end
end
for (pttrs, elty, relty) in
    ((:zpttrs_,:Complex128,:Float64),
     (:cpttrs_,:Complex64,:Float32))
    @eval begin
#       SUBROUTINE ZPTTRS( UPLO, N, NRHS, D, E, B, LDB, INFO )
# *     .. Scalar Arguments ..
#       CHARACTER          UPLO
#       INTEGER            INFO, LDB, N, NRHS
# *     ..
# *     .. Array Arguments ..
#       DOUBLE PRECISION   D( * )
#       COMPLEX*16         B( LDB, * ), E( * )
        function pttrs!(uplo::Char, D::StridedVector{$relty}, E::StridedVector{$elty}, B::StridedVecOrMat{$elty})
            chkstride1(B)
            chkuplo(uplo)
            n = length(D)
            if length(E) != n - 1
                throw(DimensionMismatch("E has length $(length(E)), but needs $(n - 1)"))
            end
            if n != size(B,1)
                throw(DimensionMismatch("B has first dimension $(size(B,1)) but needs $n"))
            end
            info = Array(BlasInt, 1)
            ccall(($(blasfunc(pttrs)), liblapack), Void,
                  (Ptr{UInt8}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$relty}, Ptr{$elty},
                   Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}),
                  &uplo, &n, &size(B,2), D, E, B, &max(1,stride(B,2)), info)
            @lapackerror
            B
        end
    end
end


text:
#
# This file is part of the Actors.jl Julia package,
# MIT license, part of https://github.com/JuliaActors
#

using Actors, Test
import Actors: spawn

fail() = nonexistent()

act = spawn(fail)

@test Actors.diag(act) == :ok
@test Actors.diag(act, :task).state == :runnable
send(act)
sleep(0.1)
@test Actors.info(act) == act.chn.excp.task


text:
# String type

abstract type AbstractStringMethod end

abstract type SimplifiedStringMethod <: AbstractStringMethod end

abstract type SaddleMethod end

abstract type ClimbingImageMethod <: SaddleMethod end


text:
module FourierCore

include("Domain/Domain.jl")
include("Grid/Grid.jl")
include("OverEngineering/OverEngineering.jl")

end # module FourierCore

max_stars_repo_name: sandreza/FourierCore

max_issues_repo_name: sandreza/FourierCore

max_forks_repo_name: sandreza/FourierCore


text:
module UtilitiesTests

if VERSION >= v"0.5.0-dev+7720"
    using Base.Test
else
    using BaseTestNext
    const Test = BaseTestNext
end

import Documenter

module UnitTests
    module SubModule end

    # Does `submodules` collect *all* the submodules?
    module A
        module B
            module C
                module D end
            end
        end
    end

    type T end
    type S{T} end

    "Documenter unit tests."
    Base.length(::T) = 1

    f(x) = x

    const pi = 3.0
end

module OuterModule
module InnerModule
import ..OuterModule
export OuterModule
end
end

@testset "Utilities" begin
    let doc = @doc(length)
        a = Documenter.Utilities.filterdocs(doc, Set{Module}())
        b = Documenter.Utilities.filterdocs(doc, Set{Module}([UnitTests]))
        c = Documenter.Utilities.filterdocs(doc, Set{Module}([Base]))
        d = Documenter.Utilities.filterdocs(doc, Set{Module}([UtilitiesTests]))

        @test !isnull(a)
        @test get(a) === doc
        @test !isnull(b)
        @test contains(stringmime("text/plain", get(b)), "Documenter unit tests.")
        @test !isnull(c)
        @test !contains(stringmime("text/plain", get(c)), "Documenter unit tests.")
        @test isnull(d)
    end

    # Documenter.Utilities.issubmodule
    @test Documenter.Utilities.issubmodule(Main, Main) === true
    @test Documenter.Utilities.issubmodule(UnitTests, UnitTests) === true
    @test Documenter.Utilities.issubmodule(UnitTests.SubModule, Main) === true
    @test Documenter.Utilities.issubmodule(UnitTests.SubModule, UnitTests) === true
    @test Documenter.Utilities.issubmodule(UnitTests.SubModule, Base) === false
    @test Documenter.Utilities.issubmodule(UnitTests, UnitTests.SubModule) === false

    @test UnitTests.A in Documenter.Utilities.submodules(UnitTests.A)
    @test UnitTests.A.B in Documenter.Utilities.submodules(UnitTests.A)
    @test UnitTests.A.B.C in Documenter.Utilities.submodules(UnitTests.A)
    @test UnitTests.A.B.C.D in Documenter.Utilities.submodules(UnitTests.A)
    @test OuterModule in Documenter.Utilities.submodules(OuterModule)
    @test OuterModule.InnerModule in Documenter.Utilities.submodules(OuterModule)
    @test length(Documenter.Utilities.submodules(OuterModule)) == 2

    @test Documenter.Utilities.isabsurl("file.md") === false
    @test Documenter.Utilities.isabsurl("../file.md") === false
    @test Documenter.Utilities.isabsurl(".") === false
    @test Documenter.Utilities.isabsurl("https://example.org/file.md") === true
    @test Documenter.Utilities.isabsurl("http://example.org") === true
    @test Documenter.Utilities.isabsurl("ftp://user:pw@example.org") === true
    @test Documenter.Utilities.isabsurl("/fs/absolute/path") === false

    @test Documenter.Utilities.doccat(UnitTests) == "Module"
    @test Documenter.Utilities.doccat(UnitTests.T) == "Type"
    @test Documenter.Utilities.doccat(UnitTests.S) == "Type"
    @test Documenter.Utilities.doccat(UnitTests.f) == "Function"
    @test Documenter.Utilities.doccat(UnitTests.pi) == "Constant"
end

end


text:
using PyPlot
using JLD
using Printf
using StatsBase
using LinearAlgebra

# use unstructured for most variables
@load "/Users/milan/cams/entropy/distribution_all.jld"

# however, use gridded for temperature as dataset does not seem to be correctly interpolated
Sgrid = load("/Users/milan/cams/entropy/distribution_all_gridded.jld","S")

# copy across
S[varnames .== "t"] = Sgrid[varnames .== "t"]

n = length(S)

## sort and group
aero = Array(1:15)
ozone = [35,44,45]
methane = [25,26,41]
dynamics = [33,34,54,55,53]
clouds = [22,27,28,31,32,51]
hydro = vcat(Array(36:40),46)
nitro = [42,43,52]
oopp = Array(47:50)
ces = vcat(Array(17:21),[23,24,16])
co12 = [29,30]

grouped = vcat(aero,co12,clouds,methane,ces,hydro,dynamics,nitro,ozone,oopp)
groups = [aero,co12,clouds,methane,ces,hydro,dynamics,nitro,ozone,oopp]

ax1names = fill("",55)
ax2names = fill("",55)

groups1 = [aero,hydro,ces]
groups2 = [dynamics,clouds,nitro,oopp,ozone,co12,methane]

j = 33
for group in groups1
    for i in group
        global ax1names[j] = varnames[i]
        global j -= 1
    end
    global j -= 2
end

j = 32
for group in groups2
    for i in group
        global ax2names[j] = varnames[i]
        global j -= 1
    end
    global j -= 1
end

## rescale for minpos-maximum only
Hex = fit(Histogram,rand(Float32,100),[0f0,0.5f0,1f0])
Sn = fill(normalize(Hex,mode=:density),n)               # normalized S

for (i,H) in enumerate(S)
    Hn = normalize(H,mode=:density)                     # Just to get the type
    Hn.weights .= H.weights / sum(H.weights[4:end-2])   # actual normlization
    Sn[i] = Hn
end

## plotting
pygui(true)
fig,(ax1,ax2) = subplots(1,2,figsize=(10,6))
ax1.set_xscale("log")
ax2.set_xscale("log")

ax1y2 = ax1.twinx()
ax2y2 = ax2.twinx()

groups1colors = ["C4","C1","C9"]
groups2colors = ["C2","royalblue","indianred","C5","C6","C8","darkslategray"]
ioffset = 32

for (ig,group) in enumerate(groups1)

    color = groups1colors[ig]

    for i in group
        global yoffset = 0.01*ioffset

        x = (Sn[i].edges[1][4:end-3] + Sn[i].edges[1][5:end-2])/2
        y = yoffset .+ Sn[i].weights[4:end-2]

        # extend line to zero
        xprevmax = Sn[i].edges[1][end-3]       # on smaller than max
        xmax = Sn[i].edges[1][end-2]
        xmax1 = (3*xmax-xprevmax)/2            # just larger than max
        xprevinf = Sn[i].edges[1][end-1]       # floatmax
        x = vcat(0,Sn[i].edges[1][4],x,xmax,xmax1,xprevinf)
        y = vcat(yoffset,yoffset,y,Sn[i].weights[end-1]+yoffset,yoffset,yoffset)

        l = length(y)

        ax1.plot(x,y,color)
        ax1.fill_between(x,y,fill(yoffset,l),color=color,alpha=0.3)
        global ioffset -= 1
    end
    global ioffset -= 2
end

ioffset = 31

for (ig,group) in enumerate(groups2)

    color = groups2colors[ig]

    for i in group
        global yoffset = 0.01*ioffset

        x = (Sn[i].edges[1][4:end-3] + Sn[i].edges[1][5:end-2])/2
        y = yoffset .+ Sn[i].weights[4:end-2]

        # extend line to zero
        xprevmax = Sn[i].edges[1][end-3]       # on smaller than max
        xmax = Sn[i].edges[1][end-2]
        xmax1 = (3*xmax-xprevmax)/2            # just larger than max
        xprevinf = Sn[i].edges[1][end-1]       # floatmax
        x = vcat(0,Sn[i].edges[1][4],x,xmax,xmax1,xprevinf)
        y = vcat(yoffset,yoffset,y,Sn[i].weights[end-1]+yoffset,yoffset,yoffset)

        l = length(y)

        ax2.plot(x,y,color)
        ax2.fill_between(x,y,fill(yoffset,l),color=color,alpha=0.3)
        global ioffset -= 1
    end
    global ioffset -= 1
end

ax1.set_xlim(1e-26,1e-6)
ax1.set_ylim(-0.02,0.35)
ax1y2.set_ylim(-0.02,0.35)

ax2.set_xlim(1e-26,1e3)
ax2.set_ylim(-0.02,0.35)
ax2y2.set_ylim(-0.02,0.35)

ytik = Array(0:0.05:0.35)
ytikm = Array(0:0.01:0.35)

ax1.set_yticks(ytik)
ax1.set_yticklabels([@sprintf("%i%%",y*100) for y in ytik])
ax1.set_yticks(ytikm,minor=true)

ax2.set_yticks(ytik)
ax2.set_yticklabels([])
ax2.set_yticks(ytikm,minor=true)

ax1y2.set_yticks(ytikm)
ax1y2.set_yticklabels(ax1names)
ax2y2.set_yticks(ytikm)
ax2y2.set_yticklabels(ax2names)

ax1.set_xlabel("value")
ax2.set_xlabel("value")
# ax1.set_ylabel("frequency")

ax1.set_title("Histograms of CAMS variables",loc="left")
# ax2y2.set_ylabel("variable")

ax1.text(3e-25,0.323,"Aerosols",color=groups1colors[1])
ax1.text(3e-25,0.153,"Alkanes & alcohols",color=groups1colors[2])
ax1.text(3e-25,0.073,"Alkanes & alcohols",color=groups1colors[3])

ax2.text(2e-25,0.313,"Dynamics & temperature",color=groups2colors[1])
ax2.text(2e-25,0.253,"Clouds & water",color=groups2colors[2])
ax2.text(3e-24,0.183,"N&S oxides",color=groups2colors[3])
ax2.text(2e-25,0.143,"Others",color=groups2colors[4])
ax2.text(2e-25,0.093,"Ozone",color=groups2colors[5])
ax2.text(2e-25,0.053,"Carbon oxides",color=groups2colors[6])
ax2.text(2e-25,0.023,"Methane",color=groups2colors[7])

tight_layout()


text:
precompile(beautify, (Float64,))
precompile(beautify, (ComplexF64,))
precompile(spectrum_split, (Vector{Float64},))
precompile(spectrum_split, (Vector{ComplexF64},))
precompile(class_multab, (FiniteGroup,))
precompile(class_multab, (PermutationGroup,))
precompile(vec_split, (Matrix{Float64}, Matrix{Float64}))
precompile(vec_split, (Matrix{Float64}, Matrix{ComplexF64}))
precompile(vec_split, (Matrix{ComplexF64}, Matrix{Float64}))
precompile(vec_split, (Matrix{ComplexF64}, Matrix{ComplexF64}))
precompile(normalize_chi!, (FiniteGroup, Vector{Float64}))
precompile(normalize_chi!, (FiniteGroup, Vector{ComplexF64}))
precompile(normalize_chi!, (PermutationGroup, Vector{Float64}))
precompile(normalize_chi!, (PermutationGroup, Vector{ComplexF64}))
precompile(burnside, (FiniteGroup, Array{Int64, 3}))
precompile(charactertable, (FiniteGroup,))
precompile(charactertable, (PointGroup,))
precompile(charactertable, (PermutationGroup,))
precompile(regular_rep, (FiniteGroup,))
precompile(regular_rep, (PointGroup,))
precompile(regular_rep, (PermutationGroup,))
precompile(proj_operator, (Vector{Matrix{Float64}}, Vector{Float64}, FiniteGroup))
precompile(proj_operator, (Vector{Matrix{Float64}}, Vector{ComplexF64}, FiniteGroup))
precompile(proj_operator, (Vector{Matrix{ComplexF64}}, Vector{Float64}, FiniteGroup))
precompile(proj_operator, (Vector{Matrix{ComplexF64}}, Vector{ComplexF64}, FiniteGroup))
precompile(proj_operator, (Vector{Matrix{Float64}}, Vector{Float64}, PointGroup))
precompile(proj_operator, (Vector{Matrix{Float64}}, Vector{ComplexF64}, PointGroup))
precompile(proj_operator, (Vector{Matrix{ComplexF64}}, Vector{Float64}, PointGroup))
precompile(proj_operator, (Vector{Matrix{ComplexF64}}, Vector{ComplexF64}, PointGroup))
precompile(proj_operator, (Vector{Matrix{Float64}}, Vector{Float64}, PermutationGroup))
precompile(proj_operator, (Vector{Matrix{Float64}}, Vector{ComplexF64}, PermutationGroup))
precompile(proj_operator, (Vector{Matrix{ComplexF64}}, Vector{Float64}, PermutationGroup))
precompile(proj_operator, (Vector{Matrix{ComplexF64}}, Vector{ComplexF64}, PermutationGroup))
precompile(unitaryeigen, (Matrix{Float64},))
precompile(unitaryeigen, (Matrix{ComplexF64},))
precompile(unitarysqrt, (Matrix{Float64},))
precompile(unitarysqrt, (Matrix{ComplexF64},))
precompile(transform_rep, (Matrix{Float64}, Vector{Matrix{Float64}}, Matrix{Float64}))
precompile(transform_rep, (Matrix{Float64}, Vector{Matrix{ComplexF64}}, Matrix{Float64}))
precompile(transform_rep, (Matrix{ComplexF64}, Vector{Matrix{ComplexF64}}, Matrix{ComplexF64}))
precompile(transform_rep, (Matrix{ComplexF64}, Vector{Matrix{Float64}}, Matrix{ComplexF64}))
precompile(krylov_space, (Vector{Matrix{Float64}}, Vector{Float64}, Int64))
precompile(krylov_space, (Vector{Matrix{ComplexF64}}, Vector{ComplexF64}, Int64))
precompile(find_least_degen, (Vector{Matrix{Float64}}, Int64))
precompile(find_least_degen, (Vector{Matrix{ComplexF64}}, Int64))
precompile(irreps, (PointGroup,))
precompile(irreps, (PointGroup, Vector{Float64}))
precompile(irreps, (PointGroup, Vector{ComplexF64}))