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

"""
    BatchGetTraces()

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.

# Required Parameters
- `TraceIds`: Specify the trace IDs of requests for which to retrieve segments.

# Optional Parameters
- `NextToken`: Pagination token.
"""
batch_get_traces(TraceIds; aws_config::AWSConfig=global_aws_config()) = xray("POST", "/Traces", Dict{String, Any}("TraceIds"=>TraceIds); aws_config=aws_config)
batch_get_traces(TraceIds, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = xray("POST", "/Traces", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("TraceIds"=>TraceIds), args)); aws_config=aws_config)

"""
    CreateGroup()

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

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

# Optional Parameters
- `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::AWSConfig=global_aws_config()) = xray("POST", "/CreateGroup", Dict{String, Any}("GroupName"=>GroupName); aws_config=aws_config)
create_group(GroupName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = xray("POST", "/CreateGroup", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("GroupName"=>GroupName), args)); aws_config=aws_config)

"""
    CreateSamplingRule()

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.

# Required Parameters
- `SamplingRule`: The rule definition.

# Optional Parameters
- `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::AWSConfig=global_aws_config()) = xray("POST", "/CreateSamplingRule", Dict{String, Any}("SamplingRule"=>SamplingRule); aws_config=aws_config)
create_sampling_rule(SamplingRule, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = xray("POST", "/CreateSamplingRule", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("SamplingRule"=>SamplingRule), args)); aws_config=aws_config)

"""
    DeleteGroup()

Deletes a group resource.

# Optional Parameters
- `GroupARN`: The ARN of the group that was generated on creation.
- `GroupName`: The case-sensitive name of the group.
"""
delete_group(; aws_config::AWSConfig=global_aws_config()) = xray("POST", "/DeleteGroup"; aws_config=aws_config)
delete_group(args::AbstractDict{String, Any}; aws_config::AWSConfig=global_aws_config()) = xray("POST", "/DeleteGroup", args; aws_config=aws_config)

"""
    DeleteSamplingRule()

Deletes a sampling rule.

# Optional Parameters
- `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::AWSConfig=global_aws_config()) = xray("POST", "/DeleteSamplingRule"; aws_config=aws_config)
delete_sampling_rule(args::AbstractDict{String, Any}; aws_config::AWSConfig=global_aws_config()) = xray("POST", "/DeleteSamplingRule", args; aws_config=aws_config)

"""
    GetEncryptionConfig()

Retrieves the current encryption configuration for X-Ray data.

"""
get_encryption_config(; aws_config::AWSConfig=global_aws_config()) = xray("POST", "/EncryptionConfig"; aws_config=aws_config)
get_encryption_config(args::AbstractDict{String, Any}; aws_config::AWSConfig=global_aws_config()) = xray("POST", "/EncryptionConfig", args; aws_config=aws_config)

"""
    GetGroup()

Retrieves group resource details.

# Optional Parameters
- `GroupARN`: The ARN of the group that was generated on creation.
- `GroupName`: The case-sensitive name of the group.
"""
get_group(; aws_config::AWSConfig=global_aws_config()) = xray("POST", "/GetGroup"; aws_config=aws_config)
get_group(args::AbstractDict{String, Any}; aws_config::AWSConfig=global_aws_config()) = xray("POST", "/GetGroup", args; aws_config=aws_config)

"""
    GetGroups()

Retrieves all active group details.

# Optional Parameters
- `NextToken`: Pagination token.
"""
get_groups(; aws_config::AWSConfig=global_aws_config()) = xray("POST", "/Groups"; aws_config=aws_config)
get_groups(args::AbstractDict{String, Any}; aws_config::AWSConfig=global_aws_config()) = xray("POST", "/Groups", args; aws_config=aws_config)

"""
    GetInsight()

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.

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

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

"""
    GetInsightEvents()

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.

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

# Optional Parameters
- `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::AWSConfig=global_aws_config()) = xray("POST", "/InsightEvents", Dict{String, Any}("InsightId"=>InsightId); aws_config=aws_config)
get_insight_events(InsightId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = xray("POST", "/InsightEvents", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("InsightId"=>InsightId), args)); aws_config=aws_config)

"""
    GetInsightImpactGraph()

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.

# Required Parameters
- `EndTime`: 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.
- `InsightId`: The insight's unique identifier. Use the GetInsightSummaries action to retrieve an InsightId.
- `StartTime`: 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
- `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::AWSConfig=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, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = xray("POST", "/InsightImpactGraph", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("EndTime"=>EndTime, "InsightId"=>InsightId, "StartTime"=>StartTime), args)); aws_config=aws_config)

"""
    GetInsightSummaries()

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

# Required Parameters
- `EndTime`: The end of the time frame in which the insights ended. The end time can't be more than 30 days old.
- `StartTime`: The beginning of the time frame in which the insights started. The start time can't be more than 30 days old.

# Optional Parameters
- `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::AWSConfig=global_aws_config()) = xray("POST", "/InsightSummaries", Dict{String, Any}("EndTime"=>EndTime, "StartTime"=>StartTime); aws_config=aws_config)
get_insight_summaries(EndTime, StartTime, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = xray("POST", "/InsightSummaries", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("EndTime"=>EndTime, "StartTime"=>StartTime), args)); aws_config=aws_config)

"""
    GetSamplingRules()

Retrieves all sampling rules.

# Optional Parameters
- `NextToken`: Pagination token.
"""
get_sampling_rules(; aws_config::AWSConfig=global_aws_config()) = xray("POST", "/GetSamplingRules"; aws_config=aws_config)
get_sampling_rules(args::AbstractDict{String, Any}; aws_config::AWSConfig=global_aws_config()) = xray("POST", "/GetSamplingRules", args; aws_config=aws_config)

"""
    GetSamplingStatisticSummaries()

Retrieves information about recent sampling results for all sampling rules.

# Optional Parameters
- `NextToken`: Pagination token.
"""
get_sampling_statistic_summaries(; aws_config::AWSConfig=global_aws_config()) = xray("POST", "/SamplingStatisticSummaries"; aws_config=aws_config)
get_sampling_statistic_summaries(args::AbstractDict{String, Any}; aws_config::AWSConfig=global_aws_config()) = xray("POST", "/SamplingStatisticSummaries", args; aws_config=aws_config)

"""
    GetSamplingTargets()

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

# Required Parameters
- `SamplingStatisticsDocuments`: Information about rules that the service is using to sample requests.

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

"""
    GetServiceGraph()

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.

# Required Parameters
- `EndTime`: The end of the timeframe for which to generate a graph.
- `StartTime`: The start of the time frame for which to generate a graph.

# Optional Parameters
- `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::AWSConfig=global_aws_config()) = xray("POST", "/ServiceGraph", Dict{String, Any}("EndTime"=>EndTime, "StartTime"=>StartTime); aws_config=aws_config)
get_service_graph(EndTime, StartTime, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = xray("POST", "/ServiceGraph", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("EndTime"=>EndTime, "StartTime"=>StartTime), args)); aws_config=aws_config)

"""
    GetTimeSeriesServiceStatistics()

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

# Required Parameters
- `EndTime`: The end of the time frame for which to aggregate statistics.
- `StartTime`: The start of the time frame for which to aggregate statistics.

# Optional Parameters
- `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::AWSConfig=global_aws_config()) = xray("POST", "/TimeSeriesServiceStatistics", Dict{String, Any}("EndTime"=>EndTime, "StartTime"=>StartTime); aws_config=aws_config)
get_time_series_service_statistics(EndTime, StartTime, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = xray("POST", "/TimeSeriesServiceStatistics", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("EndTime"=>EndTime, "StartTime"=>StartTime), args)); aws_config=aws_config)

"""
    GetTraceGraph()

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

# Required Parameters
- `TraceIds`: Trace IDs of requests for which to generate a service graph.

# Optional Parameters
- `NextToken`: Pagination token.
"""
get_trace_graph(TraceIds; aws_config::AWSConfig=global_aws_config()) = xray("POST", "/TraceGraph", Dict{String, Any}("TraceIds"=>TraceIds); aws_config=aws_config)
get_trace_graph(TraceIds, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = xray("POST", "/TraceGraph", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("TraceIds"=>TraceIds), args)); aws_config=aws_config)

"""
    GetTraceSummaries()

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.

# Required Parameters
- `EndTime`: The end of the time frame for which to retrieve traces.
- `StartTime`: The start of the time frame for which to retrieve traces.

# Optional Parameters
- `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::AWSConfig=global_aws_config()) = xray("POST", "/TraceSummaries", Dict{String, Any}("EndTime"=>EndTime, "StartTime"=>StartTime); aws_config=aws_config)
get_trace_summaries(EndTime, StartTime, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = xray("POST", "/TraceSummaries", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("EndTime"=>EndTime, "StartTime"=>StartTime), args)); aws_config=aws_config)

"""
    ListTagsForResource()

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

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

# Optional Parameters
- `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::AWSConfig=global_aws_config()) = xray("POST", "/ListTagsForResource", Dict{String, Any}("ResourceARN"=>ResourceARN); aws_config=aws_config)
list_tags_for_resource(ResourceARN, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = xray("POST", "/ListTagsForResource", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ResourceARN"=>ResourceARN), args)); aws_config=aws_config)

"""
    PutEncryptionConfig()

Updates the encryption configuration for X-Ray data.

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

# Optional Parameters
- `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::AWSConfig=global_aws_config()) = xray("POST", "/PutEncryptionConfig", Dict{String, Any}("Type"=>Type); aws_config=aws_config)
put_encryption_config(Type, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = xray("POST", "/PutEncryptionConfig", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Type"=>Type), args)); aws_config=aws_config)

"""
    PutTelemetryRecords()

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

# Required Parameters
- `TelemetryRecords`:

# Optional Parameters
- `EC2InstanceId`:
- `Hostname`:
- `ResourceARN`:
"""
put_telemetry_records(TelemetryRecords; aws_config::AWSConfig=global_aws_config()) = xray("POST", "/TelemetryRecords", Dict{String, Any}("TelemetryRecords"=>TelemetryRecords); aws_config=aws_config)
put_telemetry_records(TelemetryRecords, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = xray("POST", "/TelemetryRecords", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("TelemetryRecords"=>TelemetryRecords), args)); aws_config=aws_config)

"""
    PutTraceSegments()

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.

# Required Parameters
- `TraceSegmentDocuments`: A string containing a JSON document defining one or more segments or subsegments.

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

"""
    TagResource()

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

# Required Parameters
- `ResourceARN`: 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::AWSConfig=global_aws_config()) = xray("POST", "/TagResource", Dict{String, Any}("ResourceARN"=>ResourceARN, "Tags"=>Tags); aws_config=aws_config)
tag_resource(ResourceARN, Tags, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = xray("POST", "/TagResource", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ResourceARN"=>ResourceARN, "Tags"=>Tags), args)); aws_config=aws_config)

"""
    UntagResource()

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

# Required Parameters
- `ResourceARN`: The Amazon Resource Number (ARN) of an X-Ray group or sampling rule.
- `TagKeys`: 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::AWSConfig=global_aws_config()) = xray("POST", "/UntagResource", Dict{String, Any}("ResourceARN"=>ResourceARN, "TagKeys"=>TagKeys); aws_config=aws_config)
untag_resource(ResourceARN, TagKeys, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = xray("POST", "/UntagResource", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ResourceARN"=>ResourceARN, "TagKeys"=>TagKeys), args)); aws_config=aws_config)

"""
    UpdateGroup()

Updates a group resource.

# Optional Parameters
- `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::AWSConfig=global_aws_config()) = xray("POST", "/UpdateGroup"; aws_config=aws_config)
update_group(args::AbstractDict{String, Any}; aws_config::AWSConfig=global_aws_config()) = xray("POST", "/UpdateGroup", args; aws_config=aws_config)

"""
    UpdateSamplingRule()

Modifies a sampling rule's configuration.

# Required Parameters
- `SamplingRuleUpdate`: The rule and fields to change.

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


text:
@testset "Node composition report" begin

fName = "report/nodecomposition"

excelNodeCompositionReport( mpSim, 12, "Junior", "Career", "Branch A",
    "Branch B", filename=fName )

end  # @testset "Node composition report"

ext: jl


text:
module test_reflection

using Test

@test :Float64 == nameof(Float64)
@test :Float64 == Base.typename(Float64).name
@test 8 == sizeof(Float64)
@test 8 == sizeof(1.0)
@test 8 == sizeof(1)
@test 0 == sizeof("")
@test 1 == sizeof("a")
@test 3 == sizeof("헐")

end # module test_reflection

using Jive
@If VERSION >= v"1.2.0-DEV.218" module test_reflection_hasmethod

using Test

g(; b, c, a) = a + b + c

@test hasmethod(g, Tuple{}, (:a, :b, :c))

end # @If v"1.2.0-DEV.218" >= VERSION module test_reflection_hasmethod


text:
# This file roughly corresponds to functions documented in the
# Submission Comments API: https://canvas.instructure.com/doc/api/submission_comments

"""
    Canvas.upload_file(c::Course, a::Assignment, u::User, file; kwargs...) -> File

Upload a file to attach to a submission comment. Return a [`File`](@ref).

**Canvas API documentation**:
[Upload a file (`POST /api/v1/courses/:course_id/assignments/:assignment_id/submissions/:user_id/comments/files`)]
(https://canvas.instructure.com/doc/api/submission_comments#method.submission_comments_api.create_file)
"""
function upload_file(c::Course, a::Assignment, u::User, file; kwargs...)
    endpoint = "/api/v1$(Internals.pid(c))$(Internals.pid(a))/submissions/$(Internals.id(u))/comments/files"
    return Internals.upload_file(endpoint, file; kwargs...)
end


text:
"""
# module PartiallyOrderedParser

- Julia version:
- Author: rhdekker
- Date: 2019-02-17

# Examples

```jldoctest
julia>
```
"""
module PartiallyOrderedParser

using HyperGraphTools.SimpleTAGMLTokenizer

export my_parse

# We create the rules as a combination of tokens
# We use the Simple TAGML tokenizer
# Using the start state we try to predict to the next possible states

# We need to set the rules
# We do that we tree alike objects

struct TreeNode
    name::String
    children::Array{TreeNode}
end

function my_parse()
    return "Hello World"
end

end

max_stars_repo_name: rhdekker/HyperGraphTools

max_issues_repo_name: rhdekker/HyperGraphTools

max_forks_repo_name: rhdekker/HyperGraphTools


text:
"""
    Strictly{S <: Union{LessThan{T}, GreaterThan{T}, LexicographicallyGreaterThan}}

Converts an inequality set to a set with the same inequality made strict.
For example, while `LessThan(1)` corresponds to the inequality `x <= 1`,
`Strictly(LessThan(1))` corresponds to the inequality `x < 1`.

## Example

    x in Strictly(LessThan(1))
"""
struct Strictly{
    S <: Union{
        MOI.LessThan{T} where T,
        MOI.GreaterThan{T} where T,
        LexicographicallyLessThan,
        LexicographicallyGreaterThan,
        DoublyLexicographicallyGreaterThan,
        DoublyLexicographicallyLessThan,
        Increasing,
        Decreasing,
    },
    T <: Number,
} <: MOI.AbstractScalarSet
    set::S
end

copy(set::Strictly{S, T}) where {S, T} = Strictly{S, T}(copy(set.set))
MOI.constant(set::Strictly{S, T}) where {S, T} = MOI.constant(set.set)
MOI.dimension(set::Strictly{S, T}) where {S, T} = MOI.dimension(set.set)
function MOIU.shift_constant(set::Strictly{S, T}, offset::T) where {S, T}
    return typeof(set)(MOIU.shift_constant(set.set, offset))
end

function Strictly(set::LexicographicallyLessThan) # TODO: does this more harm than good, with an automatic value of Int?
    return Strictly{LexicographicallyLessThan, Int}(set)
end
function Strictly(set::LexicographicallyGreaterThan) # TODO: does this more harm than good, with an automatic value of Int?
    return Strictly{LexicographicallyGreaterThan, Int}(set)
end
function Strictly(set::DoublyLexicographicallyLessThan) # TODO: does this more harm than good, with an automatic value of Int?
    return Strictly{DoublyLexicographicallyLessThan, Int}(set)
end
function Strictly(set::DoublyLexicographicallyGreaterThan) # TODO: does this more harm than good, with an automatic value of Int?
    return Strictly{DoublyLexicographicallyGreaterThan, Int}(set)
end
function Strictly(set::MOI.LessThan{T}) where {T}
    return Strictly{MOI.LessThan{T}, T}(set)
end
function Strictly(set::MOI.GreaterThan{T}) where {T}
    return Strictly{MOI.GreaterThan{T}, T}(set)
end
function Strictly(set::Increasing)
    return Strictly{Increasing, Int}(set)
end
function Strictly(set::Decreasing)
    return Strictly{Decreasing, Int}(set)
end


text:
using GtkServer, Test

s = gtk_init()
if !s.nullmode
    @test begin
        gtk_init()
        gtk_send("gtk_init NULL NULL")
        win = gtk_send("gtk_window_new 0")
        gtk_exit()
    end == "ok\n"
else
    @test begin
        gtk_exit()
    end == ""
end


text:
using Random
using StatsBase: sample

dB(x) = 10 * log10(x)
dB(x::AbstractArray) = dB.(x)
lin(x) = exp10(x/10)
Base.exp10(Missing) = missing

getinds(x, i) = findall(isequal.(x.data,i))

function neg2miss!(pix)
    zero_ind = pix .<= 1e-4
    zero_ind[ismissing.(zero_ind)] .=false
    pix[collect(skipmissing(zero_ind))] .=missing
    pix
end

function randinds(cube, shpcube::YAXArrays.YAXArray, polygon; seed=123, nsamples=25)
shpinds=getinds(shpcube, polygon)
@info length(shpinds)
Random.seed!(seed)
shpsmall = sample(shpinds, nsamples, replace=false)
end

function randinds(cube, shppath::AbstractString, polygon;seed=123,nsamples=25, wrap=nothing, inner=true)
    if inner
        shpestcube =  ESDL.cubefromshape(shppath, cube, wrap=wrap,samplefactor=10)
    else
        shpestcube=ESDL.cubefromshape(shppath, cube,wrap=wrap)
    end
    #@show shpestcube
    #@info findall(skipmissing(.!iszero.(shpestcube.data)))
    randinds(cube, shpestcube, polygon, seed=seed, nsamples=nsamples)
end

function getsample(cube, shppath::AbstractString, polygon; seed=123,nsamples=25, wrap=nothing, inner=true)
    inds = randinds(cube, shppath, polygon, seed=seed, nsamples=nsamples, wrap=wrap, inner=inner)
    axvals = [cube[ind.I...,:] for ind in inds]
    nonmissinds = [.!ismissing.(ts) for ts in axvals]
    axnonmiss = [ax[nonmissinds[i]] for (i,ax) in enumerate(axvals)]
    return axnonmiss, nonmissinds
end

function getsample(cube, shppath::AbstractString, polygon, axnum; seed=123,nsamples=25, wrap=nothing, inner=true)
    inds = randinds(cube, shppath, polygon, seed=seed, nsamples=nsamples, wrap=wrap, inner=inner)
    axvals = [cube[ind.I...,:,axnum] for ind in inds]
    nonmissinds = [.!ismissing.(ts) for ts in axvals]
    axnonmiss = [ax[nonmissinds[i]] for (i,ax) in enumerate(axvals)]
    return axnonmiss, nonmissinds
end

function getsample(cube, shpcube, polygon, axnum; seed=123,nsamples=25)
    inds = randinds(cube,shpcube, polygon, seed=seed, nsamples=nsamples)
    axvals = [cube[ind.I...,:,axnum] for ind in inds]
    nonmissinds = [.!ismissing.(ts) for ts in axvals]
    axnonmiss = [ax[nonmissinds[i]] for (i,ax) in enumerate(axvals)]
    return axnonmiss, nonmissinds
end

function getsample(cube, shpcube, polygon; seed=123,nsamples=25)
    @info cube, shpcube, polygon
    inds = randinds(cube,shpcube, polygon, seed=seed, nsamples=nsamples)
    axvals = [cube[ind.I...,:] for ind in inds]
    nonmissinds = [.!ismissing.(ts) for ts in axvals]
    axnonmiss = [ax[nonmissinds[i]] for (i,ax) in enumerate(axvals)]
    return axnonmiss, nonmissinds
end
function getall(shpcube, metric, ax)
    T =eltype(metric)
    shpmetric = []
    for polygon in 1:maximum(skipmissing(shpcube.data))
        shpinds = getinds(shpcube, polygon)
        a = [collect(metric[i.I..., ax...]) for i in shpinds]
        @show typeof(a), size(a)
        append!(shpmetric, a)
    end
    shpmetric
end


text:
mutable struct EDF_FileHeader
    # Header
    Version::Clong                      # 8 ascii : version of this data format (0)
    Patient::String                # 80 ascii : local patient identification (mind item 3 of the additional EDF+ specs)
    Comment::String                 # 80 ascii : local recording identification (mind item 4 of the additional EDF+ specs)
#     start_date::String                  # 8 ascii : startdate of recording (dd.mm.yy) (mind item 2 of the additional EDF+ specs)
#     start_time::String                  # 8 ascii : starttime of recording (hh.mm.ss)

    Year::Cint
    Month::Cint
    Day::Cint
    Hour::Cint
    Minute::Cint
    Second::Cint

    Padding::Vector{Cuchar}             # 8 ascii : number of bytes in header record
                                        # 44 ascii : reserved
    NumRecord::Cint                     # 8 ascii : number of data records (-1 if unknown, obey item 10 of the additional EDF+ specs)
    SampleDuration::Cfloat              # 8 ascii : duration of a data record, in seconds
    NumChannel::Cint                    # 4 ascii : number of signals (ns) in data record

    ChannelLabels::Vector{String}     # ns * 16 ascii : ns * label (e.g. EEG Fpz-Cz or Body temp) (mind item 9 of the additional EDF+ specs)
    ChannelType::Vector{String}       # ns * 80 ascii : ns * transducer type (e.g. AgAgCl electrode)
    PhysicalDim::Vector{String}       # ns * 8 ascii : ns * physical dimension (e.g. uV or degreeC)
    PhysicalMin::Vector{Cfloat}       # ns * 8 ascii : ns * physical minimum (e.g. -500 or 34)
    PhysicalMax::Vector{Cfloat}       # ns * 8 ascii : ns * physical maximum (e.g. 500 or 40)
    DigitalMin::Vector{Cshort}        # ns * 8 ascii : ns * digital minimum (e.g. -2048)
    DigitalMax::Vector{Cshort}        # ns * 8 ascii : ns * digital maximum (e.g. 2047)

    Prefiltering::Vector{String}      # ns * 80 ascii : ns * prefiltering (e.g. HP:0.1Hz LP:75Hz)
    NumSamplesInRecord::Vector{Cshort}           # ns * 8 ascii : ns * nr of samples in each data record
    NumReservedSamplesInRecord::Vector{Cshort}  # ns * 32 ascii : ns * reserved

    EDF_FileHeader(file::IOStream) = begin
        _x = new()

        _x.Version = read(file, Int64)
        _x.Patient = read(file, 80) |> String |> strip
        _x.Comment = read(file, 80) |> String |> strip

        _x.Day, _x.Month, _x.Year = read(file, 8) |> String |> strip |>
            x->match(r"(\d{2})\.(\d{2})\.(\d{2})", x) |> x-> (x[1], x[2], x[3]) .|> Meta.parse
        _x.Hour, _x.Minute, _x.Second = read(file, 8) |> String |> strip |>
            x->match(r"(\d{2})\.(\d{2})\.(\d{2})", x) |> x-> (x[1], x[2], x[3]) .|> Meta.parse
        _x.Padding = read(file, 52)

        _x.NumRecord = read(file, 8) |> String |> Meta.parse
        _x.SampleDuration = read(file, 8) |> String |> Meta.parse
        _x.NumChannel = read(file, 4) |> String |> Meta.parse

        _x.ChannelLabels = read(file, 16*_x.NumChannel) |> x->reshape(x, (16, _x.NumChannel)) |> b-> mapreduce(x->String([x]), *, b, dims=1)[:] .|> strip
        _x.ChannelType = read(file, 80*_x.NumChannel) |> x->reshape(x, (80, _x.NumChannel)) |> b-> mapreduce(x->String([x]), *, b, dims=1)[:] .|> strip
        _x.PhysicalDim = read(file, 8*_x.NumChannel) |> x->reshape(x, (8, _x.NumChannel)) |> b-> mapreduce(x->String([x]), *, b, dims=1)[:] .|> strip
        _x.PhysicalMin = read(file, 8*_x.NumChannel) |> x->reshape(x, (8, _x.NumChannel)) |> b-> mapreduce(x->String([x]), *, b, dims=1)[:] .|> strip .|> Meta.parse
        _x.PhysicalMax = read(file, 8*_x.NumChannel) |> x->reshape(x, (8, _x.NumChannel)) |> b-> mapreduce(x->String([x]), *, b, dims=1)[:] .|> strip .|> Meta.parse
        _x.DigitalMin  = read(file, 8*_x.NumChannel) |> x->reshape(x, (8, _x.NumChannel)) |> b-> mapreduce(x->String([x]), *, b, dims=1)[:] .|> strip .|> Meta.parse
        _x.DigitalMax  = read(file, 8*_x.NumChannel) |> x->reshape(x, (8, _x.NumChannel)) |> b-> mapreduce(x->String([x]), *, b, dims=1)[:] .|> strip .|> Meta.parse

        _x.Prefiltering = read(file, 80*_x.NumChannel) |> x->reshape(x, (80, _x.NumChannel)) |> b-> mapreduce(x->String([x]), *, b, dims=1)[:] .|> strip
        _x.NumSamplesInRecord = read(file, 8*_x.NumChannel) |> x->reshape(x, (8, _x.NumChannel)) |> b-> mapreduce(x->String([x]), *, b, dims=1)[:] .|> strip .|> Meta.parse
        _x.NumReservedSamplesInRecord = read(file, 32*_x.NumChannel) |> x->reshape(x, (32, _x.NumChannel)) |> b-> mapreduce(x->String([x]), *, b, dims=1)[:] .|> strip .|> Meta.parse .|> x -> (x==nothing) ? 0 : x

        _x
    end
end

mutable struct EDFData
    FILE_HEADER::EDF_FileHeader
    CONTINUOUS_DATA::Array{Int16, 2}

    ##### misc #####
    Freq::Float32
#     Tspec::Vector{Float32}
    PhysicalUnit::Vector{Float32}

    RecordTime::String
    RecordDate::String

    EDFData(filename::String) = begin
        _f = open(filename, "r")
        _x = new()

        _x.FILE_HEADER = EDF_FileHeader(_f)

        _raw_data = zeros(Int16, _x.FILE_HEADER.NumRecord * _x.FILE_HEADER.NumSamplesInRecord[1], _x.FILE_HEADER.NumChannel)
#         _raw_reserved = zeros(Int16, _x.FILE_HEADER.NumChannel, _x.FILE_HEADER.NumRecord * _x.FILE_HEADER.NumReservedSamplesInRecord[1])

        _step = sum(_x.FILE_HEADER.NumSamplesInRecord)
        _chstep = _x.FILE_HEADER.NumSamplesInRecord[1]
        for _record_idx = 1:_x.FILE_HEADER.NumRecord
            record_data = read!(_f, Array{Int16, 2}(undef, _chstep, _x.FILE_HEADER.NumChannel))
            _raw_data[_chstep*(_record_idx-1)+1:_chstep*_record_idx, :] = record_data
        end
        _x.CONTINUOUS_DATA = _raw_data

        _x.Freq = _chstep / _x.FILE_HEADER.SampleDuration
        _x.PhysicalUnit = ( _x.FILE_HEADER.PhysicalMax .-  _x.FILE_HEADER.PhysicalMin) ./ ( _x.FILE_HEADER.DigitalMax -  _x.FILE_HEADER.DigitalMin)

        _header = _x.FILE_HEADER
        _x.RecordTime = "$(_header.Year)-$(_header.Month)-$(_header.Day) $(_header.Hour):$(_header.Minute):$(_header.Second)"
        _x.RecordDate = "$(_header.Year)-$(_header.Month)-$(_header.Day)"

        _x
    end
end

function export_isplit(_edf::EDFData; Comment = nothing, _dir="./iSplit")

    _index_json = joinpath(_dir, "channel_index.json")
    if !isfile(_index_json)
        open(_index_json, "w") do file
            write(file, "{}")
        end
    end

    channel_index = open(_index_json, "r") do file
        JSON.parse(file)
    end

    _record_time = _edf.RecordTime
    _record_date = _edf.RecordDate

    _comment = (Comment == nothing) ? Dict() : Comment

    for (chidx, chlabel) in enumerate(_edf.FILE_HEADER.ChannelLabels)

        _comment["label"] = chlabel
        _value = _edf.CONTINUOUS_DATA[:, chidx]
        _idx = hash(_value) |> repr

        if haskey(channel_index, @sprintf("channel%03d", chidx))
            if _idx in channel_index[@sprintf("channel%03d", chidx)]
                continue
            end
        else
            channel_index[@sprintf("channel%03d", chidx)] = Vector{String}(undef, 0)
        end

        _isplit_name = joinpath(_dir, @sprintf("channel%03d.jld", chidx))

        if !isfile(_isplit_name)
            jldopen(_isplit_name, "w") do file
                write(file, "Name", @sprintf("Channel%03d", chidx))
                write(file, "Comment", "")

            end
        end

        jldopen(_isplit_name, "r+") do file
            _entry = iSplitUnit(
                chidx, _record_date, _record_time, _comment,
                _edf.PhysicalUnit[chidx], _edf.Freq, _value
            )
            write(file, _idx, _entry)
        end

        push!(channel_index[@sprintf("channel%03d", chidx)], _idx)
    end

    open(_index_json, "w") do file
        write(file, JSON.json(channel_index))
    end
end


text:
using Pkg
Pkg.activate(@__DIR__)
Pkg.instantiate()

using Logging
using Gadfly
using DifferentialEquations
using ColorSchemes
using LaTeXStrings
import Plots
import Cairo,
      Fontconfig

include("../calc/problem_set.jl")
include("../calc/objective_function.jl")
include("./utils.jl")
import .ProblemSet: get_problem, DEProblem
import .ObjectiveFunction: data_shooting, single_shooting, tikhonov
import .PlottingUtils: heatmap, problem_plot, add_noise

const PATH = "./data/contours/"
const GADFLY_FONT = "Arial"

Plots.pyplot()
Plots.theme(:default)

function contour_3d_plots(x, y, z, par, save_path; method="", save_name="", cam=(-60,30))
    title = Dict("ss"=>"Single Shooting", "ds"=>"Data Shooting")

    if length(par) > 1
        cont = PlottingUtils.heatmap(x, y, vec(z'),
                                     xlabel="θ₁", ylabel="θ₂",
                                     zlabel="Objective\nFunction",
                                     title=title[method],
                                     fillcolor=ColorSchemes.vik)
    else
        cont = plot(x=x, y=vec(z), Geom.line, Guide.title(title[method]),
                    Gadfly.Coord.cartesian(yflip=false,
                                            fixed=false,
                                            xmin=minimum(x),
                                            xmax=maximum(x),
                                            ymin=minimum(vec(z)),
                                            ymax=maximum(vec(z))),
                    Gadfly.Theme(minor_label_font=GADFLY_FONT,
                                    major_label_font=GADFLY_FONT,
                                    key_title_font=GADFLY_FONT,
                                    key_label_font=GADFLY_FONT),
                    Guide.xlabel("θ₁"), Guide.ylabel("Objective Function"))
    end

    if par[1] > x[1] && par[1] < x[end]
        pushfirst!(cont.layers,
                    layer(xintercept=[par[1]],
                            Geom.vline(color="magenta"))[1])
    end

    if length(par) > 1
        if par[2] > y[1] && par[2] < y[end]
            pushfirst!(cont.layers,
                        layer(yintercept=[par[2]],
                                Geom.hline(color="cyan"))[1])
        end

        if occursin("bep", save_name)
            zlabel = "\n\n\nObjective Function"
            xlabel="\n\n\n"*L"θ_1"
            ylabel="\n"*L"θ_2"
            zrotation=-35
            xformatter=:scientific
        else
            zlabel = "\nObjective Function"
            xlabel="\n"*L"θ_1"
            ylabel="\n"*L"θ_2"
            zrotation=nothing
            xformatter=:auto
        end
        # "Arial" font does not have the required glyphs under PyPlot
        three_dim = Plots.surface(x, y, z,
                                  fillcolor=:vik, alpha=0.7,
                                  title=title[method],
                                  # xrotation=xrotation,
                                  # yrotation=360-45,
                                  zrotation=zrotation,
                                  xformatter=xformatter,
                                  # yformatter=yformatter,
                                  # zformatter=zformatter,
                                  xlabel=xlabel,
                                  ylabel=ylabel,
                                  zlabel=zlabel,
                                  xtickfont=Plots.font("DejaVu Sans", 10, "#6c606b"),
                                  ytickfont=Plots.font("DejaVu Sans", 10, "#6c606b"),
                                  ztickfont=Plots.font("DejaVu Sans", 10, "#6c606b"),
                                  titlefont=Plots.font("DejaVu Sans", 12, "#564a55"),
                                  legendfont=Plots.font("DejaVu Sans", 10, "#6c606b"),
                                  guidefont=Plots.font("DejaVu Sans", 12, "#564a55"),
                                  colorbar=false, right_margin=30px,
                                  camera=cam
                                  )

        Plots.savefig(three_dim,
            joinpath(save_path,
            "./3d_$(method)_$(save_name).pdf"))
    end

    Gadfly.draw(PDF(joinpath(save_path,
                            "./cont_$(method)_$(save_name).pdf")),
                    cont)
end

function calc_z_plot(x::AbstractArray, y::AbstractFloat,
                     data, ode_fun, t, obj_fun;
                     unknown_states=[],fixed_pars=[-1.0,-1.0])::AbstractArray
    z = zeros(length(x))
    par_eval = copy(fixed_pars)
    idx = 1

    for k in x
        par_eval[fixed_pars .< 0.0] .= [k]
        z[idx] = obj_fun(par_eval, data, t, ode_fun)
        @debug "Eval" k par_eval z[idx]
        idx += 1
    end

    z = reshape(z, (length(y), length(x)))

    return z
end
function calc_z_plot(x::AbstractArray, y::AbstractArray,
                     data, ode_fun, t, obj_fun;
                     unknown_states=[],fixed_pars=[-1.0,-1.0])::AbstractArray
    z = zeros(length(y)*length(x))
    par_eval = copy(fixed_pars)
    idx = 1

    for i in x
        for j in y
            par_eval[fixed_pars .< 0.0] .= [i, j]
            # obj_eval = (obj_fun(par_eval, data, t, ode_fun)
            #             +tikhonov(0.01, par_eval,
            #                       zeros(length(par_eval)),
            #                       ones(length(par_eval))))
            z[idx] = obj_fun(par_eval, data, t, ode_fun)
            @debug "Eval" i j par_eval z[idx]
            idx += 1
        end
    end

    z = reshape(z, (length(y), length(x)))

    return z
end

function experiment_contour(exp::Dict, sample_range::AbstractArray)::Nothing
    ode_problem = exp["ode_problem"]
    ode_fun = ode_problem.fun
    t = ode_problem.t
    phi = ode_problem.phi
    bounds = ode_problem.bounds
    ini_cond = ode_problem.data[1]
    rand_range = ode_problem.bounds

    min_range = rand_range[1][1]
    max_range = rand_range[end][end]

    delta_t = 0.1

    dir = exp["ode_problem"].fun |> Symbol |> String
    save_path = joinpath(PATH,dir)
    mkdir(joinpath(PATH,dir))

    cam = (60,30)
    if Symbol(ode_fun) == :bep
        cam = (-100,35)
    end

    # --- Fine Tune This Part ---
    fixed_pars = exp["fixed_pars"]

    min_range = exp["min_range"]
    max_range = exp["max_range"]

    states = exp["states"]
    unknown_states = exp["unknown_states"]

    true_par = exp["true_par"]

    r = exp["reduced_raius"]
    s = exp["reduced_step"]/2.0

    noise = exp["noise"]
    # -- Fine Tune This Part ---

    for num_samples in sample_range
        tspan = (t[1], t[end])
        oprob = ODEProblem(ode_fun, ini_cond, tspan, phi)
        #saveat_t = range(t[1], stop=t[end], length=num_samples)
        #saveat_t = collect(t[1]:((t[end]-t[1])/(num_samples-1)):t[end])
        saveat_t = range(t[1], stop=t[end], length=num_samples)
        osol  = solve(oprob, saveat=saveat_t)
        Plots.plot(osol)
        data = osol.u
        known_states = setdiff(1:length(states),unknown_states)
        #data = data[filter(x -> x in known_states, states),:]
        if noise > 0.0
            data = add_noise(data, noise)
        end

        plot_data = problem_plot(reduce(hcat, data), collect(saveat_t),
                                "scatter_line")

        Gadfly.draw(PDF(joinpath(save_path,
                        "./data_$(length(saveat_t)*length(known_states)).pdf")),
                        plot_data)

        x = range(min_range, max_range, step=(max_range-min_range)/500)
        if length(true_par) == 1
            y = 0.0
        else
            y = range(min_range, max_range, step=(max_range-min_range)/500)
        end

        @info """Data Shooting Estimator
                   Calculating z...""" Symbol(ode_fun)
        z = calc_z_plot(x, y, data, ode_fun, saveat_t,
                        data_shooting,
                        unknown_states=unknown_states,
                        fixed_pars=fixed_pars)

        @info """Data Shooting Estimator
                   Plotting...""" Symbol(ode_fun)
        contour_3d_plots(x, y, z,
                         true_par, save_path,
                         method="ds",
                         save_name="$(dir)_$(length(data))_big",
                         cam=cam)

        @info """Data Shooting Estimator
                   Reducing range...""" Symbol(ode_fun)
        f_min,f_min_idx  = findmin(z)

        x_reduced = range(x[f_min_idx[2]]-r, x[f_min_idx[2]]+r, step=s)
        y_reduced = range(y[f_min_idx[1]]-r, y[f_min_idx[1]]+r, step=s)
        try
            @info """Data Shooting Estimator
                        Calculating z...""" Symbol(ode_fun)
            z = calc_z_plot(x_reduced, y_reduced, data, ode_fun, saveat_t,
                            data_shooting,
                            unknown_states=unknown_states,
                            fixed_pars=fixed_pars)

            @info """Data Shooting Estimator
                        Plotting...""" Symbol(ode_fun)
            contour_3d_plots(x_reduced, y_reduced, z,
                             true_par, save_path,
                             method="ds",
                             save_name="$(dir)_$(length(data))_small",
                             cam=cam)
        catch e
            bt = backtrace()
            msg = sprint(showerror, e, bt)
            @warn """Error!
                        Error in small grid.""" msg
        end

        try
            @info """Single Shooting Estimator
                        Calculating z...""" Symbol(ode_fun)
            z = calc_z_plot(x, y, data, ode_fun, saveat_t,
                            single_shooting,
                            unknown_states=unknown_states,
                            fixed_pars=fixed_pars)

            @info """Single Shooting Estimator
                        Plotting...""" Symbol(ode_fun)
            contour_3d_plots(x, y, z,
                             true_par, save_path,
                             method="ss",
                             save_name="$(dir)_$(length(data))_big",
                             cam=cam)

            @info """Single Shooting Estimator
                        Reducing range...""" Symbol(ode_fun)
            f_min,f_min_idx  = findmin(z)
            x_reduced = range(x[f_min_idx[2]]-r, x[f_min_idx[2]]+r, step=s)
            y_reduced = range(y[f_min_idx[1]]-r, y[f_min_idx[1]]+r, step=s)
            try
                @info """Single Shooting Estimator
                             Calculating z...""" Symbol(ode_fun)
                z = calc_z_plot(x_reduced, y_reduced, data, ode_fun, saveat_t,
                                single_shooting,
                                unknown_states=unknown_states,
                                fixed_pars=fixed_pars)

                @info """Single Shooting Estimator
                             Plotting...""" Symbol(ode_fun)
                contour_3d_plots(x_reduced, y_reduced, z,
                                 true_par, save_path,
                                 method="ss",
                                 save_name="$(dir)_$(length(data))_small",
                                 cam=cam)
            catch e
                bt = backtrace()
                msg = sprint(showerror, e, bt)
                @warn """Error!
                             Error in small grid.""" msg
            end
        catch e
            bt = backtrace()
            msg = sprint(showerror, e, bt)
            @warn """Error!
                        Error in small grid.""" msg
        end
    end
end

function get_experiments()::Vector{Dict}
    experiments = Dict[]
    # --- Interesting Experiments ---

    # No missing states

    # 0 - exponential
    expo = Dict(
        "ode_problem" => get_problem("exponential"),
        "fixed_pars" => [-1.0],
        "min_range" => -1.1,
        "max_range" => 1.15,
        "reduced_raius" => 1.0,
        "reduced_step" => 0.02,
        "noise" => 0.0,
        "states" => [1],
        "unknown_states" => [],
        "true_par" => [1.0])
    push!(experiments, expo)

    # 2 - floudas_1
    fic = Dict(
        "ode_problem" => get_problem("fic"),
        "fixed_pars" => [-1.0,-1.0],
        "min_range" => 0.0,
        "max_range" => 10.0,
        "reduced_raius" => 0.5,
        "reduced_step" => 0.01,
        "noise" => 0.0,
        "states" => [1,2],
        "unknown_states" => [],
        "true_par" => [5.0035,1.0])
    push!(experiments, fic)

    # 1 - floudas_6
    lvp = Dict(
        "ode_problem" => get_problem("lvp"),
        "fixed_pars" => [-1.0,-1.0],
        "min_range" => 0.5,
        "max_range" => 5.0,
        "reduced_raius" => 1.0,
        "reduced_step" => 0.02,
        "noise" => 0.0,
        "states" => [1,2],
        "unknown_states" => [],
        "true_par" => [3.2434,0.9209])
    push!(experiments, lvp)

    # 2 - fhn
    fhn = Dict(
        "ode_problem" => get_problem("fhn"),
        "fixed_pars" => [-1.0,-1.0, 3.0],
        "min_range" => 0.0,
        "max_range" => 1.50,
        "reduced_raius" => 0.91,
        "reduced_step" => 0.005,
        "noise" => 0.0,
        "states" => [1,2],
        "unknown_states" => [],
        "true_par" => [0.2,0.2])
    push!(experiments, fhn)

    # 2 - floudas_4
    bep = Dict(
        "ode_problem" => get_problem("bep"),
        "fixed_pars" => [-1.0,-1.0],
        "min_range" => 0.0,
        "max_range" => 0.01,
        "reduced_raius" => 1e-4,
        "reduced_step" => 1e-6,
        "noise" => 0.0,
        "states" => [1],
        "unknown_states" => [],
        "true_par" => [4.5704*10^(-6),2.7845*10^(-4)])
    push!(experiments, bep)

    # 2 - floudas_5
    mhp = Dict(
        "ode_problem" => get_problem("mhp"),
        "fixed_pars" => [-1.0,-1.0,1e-6,1e-6,1e-6],
        "min_range" => 0.0,
        "max_range" => 10.0,
        "reduced_raius" => 0.8,
        "reduced_step" => 0.01,
        "noise" => 0.0,
        "noise" => 0.0,
        "states" => [1,2,3],
        "unknown_states" => [],
        "true_par" => [5.2407,1.2176])
    push!(experiments, mhp)

    #TODO
    # Up to Here
    # 2 - bbg
    #phi = [0.4, 5, 0.05, 0.5]
    experiment = Dict(
        "ode_problem" => get_problem("bbg"),
        "fixed_pars" => [-1.0,5.0,-1.0,0.5],
        "min_range" => 0.0,
        "max_range" => 5.0,
        "reduced_raius" => 0.8,
        "reduced_step" => 0.01,
        "noise" => 0.0,
        "states" => [1,2],
        "unknown_states" => [],
        "true_par" => [0.4,0.05])
    # push!(experiments, experiment)

    experiment = Dict(
        "ode_problem" => get_problem("bbg"),
        "fixed_pars" => [0.4,-1.0,0.05,-1.0],
        "min_range" => 0.5,
        "max_range" => 8.0,
        "reduced_raius" => 0.1,
        "reduced_step" => 0.005,
        "noise" => 0.0,
        "states" => [1,2],
        "unknown_states" => [],
        "true_par" => [5.0,0.5])
    # push!(experiments, experiment)

    # 1 - floudas_6
    # Not so interesting
    experiment = Dict(
        "ode_problem" => get_problem("lvp"),
        "fixed_pars" => [-1.0,0.9209,-1.0],
        "min_range" => 0.5,
        "max_range" => 3.5,
        "reduced_raius" => 0.5,
        "reduced_step" => 0.05,
        "noise" => 0.0,
        "states" => [1,2],
        "unknown_states" => [2],
        "true_par" => [3.2434,1.1])
    # push!(experiments, experiment)

    # 1 - floudas_6
    # Better
    experiment_1 = Dict(
        "ode_problem" => get_problem("lvp"),
        "fixed_pars" => [-1.0,0.9209,-1.0],
        "min_range" => 0.5,
        "max_range" => 5.0,
        "reduced_raius" => 1.0,
        "reduced_step" => 0.05,
        "noise" => 0.0,
        "states" => [1,2],
        "unknown_states" => [1],
        "true_par" => [3.2434,1.2])
    # push!(experiments, experiment_1)

    # 2 - floudas_1
    experiment = Dict(
        "ode_problem" => get_problem("fic"),
        "fixed_pars" => [5.0035,-1.0,-1.0],
        "min_range" => 0.0,
        "max_range" => 5.0,
        "reduced_raius" => 0.5,
        "reduced_step" => 0.01,
        "noise" => 0.0,
        "states" => [1,2],
        "unknown_states" => [1],
        "true_par" => [1.0,1.0])
    # push!(experiments, experiment)

    # 2 - floudas_1
    # Not so interesting
    experiment = Dict(
        "ode_problem" => get_problem("fic"),
        "fixed_pars" => [-1.0,1.0,-1.0],
        "min_range" => -1.0,
        "max_range" => 7.0,
        "reduced_raius" => 0.5,
        "reduced_step" => 0.01,
        "noise" => 0.0,
        "states" => [1,2],
        "unknown_states" => [2],
        "true_par" => [5.0035,0.0])
    # push!(experiments, experiment)
    return experiments
end

function main()
    experiments = get_experiments()
    experiment_contour_10_50 = e -> experiment_contour(e, 10:20:50)
    for e in experiments
        experiment_contour_10_50(e)
    end
end

main()

max_stars_repo_name: atgmello/DEParamEst

max_issues_repo_name: atgmello/DEParamEst

max_forks_repo_name: atgmello/DEParamEst


text:
using Distributions
using NoisySignalIntegration
using MonteCarloMeasurements
using Random: seed!, rand
using Statistics
using StatsBase: mean, percentile, std
using Test

const NP = MonteCarloMeasurements.DEFAULT_NUM_PARTICLES
const nsi = NoisySignalIntegration

if false
    include("tmp.jl")
else
    include("test_common.jl")
    include("test_curves.jl")
    include("test_bounds.jl")
    include("test_noise.jl")
    include("test_integration.jl")
    include("test_regression.jl")
end


text:
struct BNet
    number_of_nodes::Int
    weights::Array{Float64,2}
    thresholds::Vector{Float64}
    BNet(ws, ts) = new(size(ws,1), ws, ts)
end

load(::Type{BNet}, wfile, tfile) = BNet(readdlm(wfile), vec(readdlm(tfile)))

Base.size(net) = net.number_of_nodes

volume(net) = 1 << size(net)

function fire!(net, state, next_state)
    temp = net.weights * state
    for i in 1:length(state)
        next_state[i] = if temp[i] > net.thresholds[i]
            1
        elseif temp[i] < net.thresholds[i]
            0
        else
            state[i]
        end
    end
    next_state
end

fire(net, state) = fire!(net, state, similar(state))

function encode(state)
    const N = length(state)
    code = 0
    for i in 1:N
        code = 2code + state[N - i + 1]
    end
    code + 1
end

function transitions(net)
    const N, V = size(net), volume(net)
    trans = Array{Int}(V)
    state = zeros(Int, N)
    next_state = fire(net, state)

    code, next_code = 1, encode(next_state)
    trans[code] = next_code

    while code < V
        for i in 1:N
            if state[i] == 0
                state[i] += 1
                state[1:i-1] = 0
                break
            end
        end
        code += 1

        fire!(net, state, next_state)
        next_code = encode(next_state)
        trans[code] = next_code
    end

    trans
end

function attractors(net)
    const V = volume(net)
    const trans = transitions(net)
    seen = zeros(Bool, V)
    basins = fill(-1, V)
    basin_number = 0

    attractors = Vector{Int}[]
    state_stack = Int[]
    cycle = Int[]
    for initial_state in trans
        if seen[initial_state]
            continue
        end

        state = initial_state
        in_cycle = false
        terminus = next_state = trans[state]
        seen[state] = true

        while !seen[next_state]
            push!(state_stack, state)
            state = next_state
            terminus = next_state = trans[state]
            seen[state] = true
        end

        basin = basins[next_state]
        if basins[next_state] == -1
            basin = basin_number
            basin_number += 1
            push!(cycle, state)
            in_cycle = (terminus != state)
        end

        basins[state] = basin
        while !isempty(state_stack)
            state = pop!(state_stack)
            basins[state] = basin
            if in_cycle
                push!(cycle, state)
                in_cycle = (terminus != state)
            end
        end

        if !isempty(cycle)
            push!(attractors, cycle)
            cycle = Int[]
        end
    end
    attractors
end

function main(wfile, tfile)
    const net = load(BNet, wfile, tfile)

    duration = @elapsed begin
        attrs = attractors(net)
    end
    println("First Invocation:  $(duration)s\n")

    duration = @elapsed begin
        attrs = attractors(net)
    end
    w = ceil(log2(length(attrs)))
    for (i, attr) in enumerate(attrs)
        print("Attractor $i: ")
        for state in attr
            print("$(state-1) ")
        end
        println()
    end
    println("Second Invocation: $(duration)s")
end

main(ARGS[1], ARGS[2])

max_stars_repo_name: ELIFE-ASU/meet-julia

max_issues_repo_name: ELIFE-ASU/meet-julia

max_forks_repo_name: ELIFE-ASU/meet-julia


text:
export BeagleBoneStream, init_devices!

struct BeagleBoneStream <: LabStream
    devices::Array{AbstractDevice,1}
    sendbuffer::Array{Tuple,1}
    readbuffer::Array{Tuple,1}
    stream::TCPSocket
end

function BeagleBoneStream(addr::IPAddr, port::Int64=2001)
    clientside = connect(addr, port)
    BeagleBoneStream(AbstractDevice[], Tuple[], Tuple[], clientside)
end

#For BeagleBoneStream we can directly serialize the data, other streams might want to send binary data
serialize(bbstream::BeagleBoneStream, cmd) = serialize(bbstream.stream, cmd)

function init_devices!(bbstream::BeagleBoneStream, devs::AbstractDevice...)
    for dev in devs
        if dev ∉ bbstream.devices
            setstream!(dev, bbstream)
            push!(bbstream.devices, dev)
            initialize(dev)
        else
            warn("Device $dev already added to a stream")
        end
    end
    return
end

function send(bbstream::BeagleBoneStream)
    ncmds = length(bbstream.sendbuffer)
    serialize(bbstream.stream, (true, Int32(ncmds), bbstream.sendbuffer...))
    empty!(bbstream.sendbuffer)
    return
end
#TODO know the types of outputs some way
function read(bbstream::BeagleBoneStream)
    ncmds = length(bbstream.readbuffer)
    serialize(bbstream.stream, (false, Int32(ncmds), bbstream.readbuffer...))
    empty!(bbstream.readbuffer)
    vals, timestamps = deserialize(bbstream.stream)
    length(vals) == ncmds || error("Wrong number of return values in $vals on request $(bbstream.readbuffer)")
    #TODO Do something with timestamps
    return (vals...,) #Converting from array to tuple
end

#The following are for interal use only
function send(bbstream::BeagleBoneStream, cmd)
    allcmds = (true, Int32(1), cmd)
    println("Sending single command: $allcmds")
    serialize(bbstream.stream, allcmds)
    return
end
function read(bbstream::BeagleBoneStream, cmd)
    allcmds = (false, Int32(1), cmd)
    println("Sending single command: $allcmds")
    serialize(bbstream.stream, allcmds)
    vals, timestamps = deserialize(bbstream.stream)
    length(vals) == 1 || error("Wrong number of return values in $vals on request $cmd")
    #TODO Do something with timestamps
    return vals[1], timestamps[1]
end

function close(bbstream::BeagleBoneStream)
    cmds = Tuple[]
    for dev in bbstream.devices
        close(dev)
    end
    close(bbstream.stream)
    return
end


text:
Pkg.add("Ipopt")
#Pkg.add("KNITRO")
Pkg.add("JuMP")
Pkg.add("MAT")

Pkg.clone("https://github.com/JuliaOptimizers/MUMPS.jl")

Pkg.update()

max_forks_repo_name: ohinder/Everest


text:
using StochasticDiffEq, DiffEqNoiseProcess, LinearAlgebra, Statistics

function generate_stiff_stoch_heat(D=1,k=1;N = 100, t_end = 3.0, adaptivealg = :RSwM3)
    A = Array(Tridiagonal([1.0 for i in 1:N-1],[-2.0 for i in 1:N],[1.0 for i in 1:N-1]))
    dx = 1/N
    A = D/(dx^2) * A
    function f(du,u,p,t)
        mul!(du,A,u)
    end
    #=
    function f(::Type{Val{:analytic}},u0,p,t,W)
        exp((A-k/2)*t+W*I)*u0 # no -k/2 for Strat
    end
    =#
    function g(du,u,p,t)
        @. du = k*u
    end
    SDEProblem(f,g,ones(N),(0.0,t_end),noise=WienerProcess(0.0,0.0,0.0,rswm=RSWM(adaptivealg=adaptivealg)))
end

N = 100
D = 1; k = 1
    A = Array(Tridiagonal([1.0 for i in 1:N-1],[-2.0 for i in 1:N],[1.0 for i in 1:N-1]))
    dx = 1/N
    A = D/(dx^2) * A;

prob = generate_stiff_stoch_heat(1.0,1.0)
@time sol = solve(prob,SRIW1(),progress=true,abstol=1e-6,reltol=1e-6);

@time sol = solve(generate_stiff_stoch_heat(1.0,1.0),SRIW1());

@time sol = solve(generate_stiff_stoch_heat(1.0,1.0),SRIW1(),progress=true,adaptive=false,dt=0.00005);

@time sol = solve(generate_stiff_stoch_heat(1.0,1.0),EM(),progress=true,adaptive=false,dt=0.00005);

@time sol = solve(generate_stiff_stoch_heat(1.0,1.0),ImplicitRKMil(),progress=true,dt=0.1);

@time sol = solve(generate_stiff_stoch_heat(1.0,1.0),ImplicitRKMil(),progress=true,dt=0.01);

@time sol = solve(generate_stiff_stoch_heat(1.0,1.0),ImplicitRKMil(),progress=true,dt=0.001);

@time sol = solve(generate_stiff_stoch_heat(1.0,1.0),ImplicitEM(),progress=true,dt=0.001);

function simple_error(alg;kwargs...)
    sol = solve(generate_stiff_stoch_heat(1.0,1.0,t_end=0.25),alg;kwargs...);
    sum(abs2,sol[end] - exp(A*sol.t[end]+sol.W[end]*I)*prob.u0)
end

mean(simple_error(EulerHeun(),dt=0.00005) for i in 1:400)

mean(simple_error(ImplicitRKMil(interpretation=:Stratanovich),dt=0.1) for i in 1:400)

mean(simple_error(ImplicitRKMil(interpretation=:Stratanovich),dt=0.01) for i in 1:400)

mean(simple_error(ImplicitRKMil(interpretation=:Stratanovich),dt=0.001) for i in 1:400)

mean(simple_error(ImplicitEulerHeun(),dt=0.001) for i in 1:400)

mean(simple_error(ImplicitEulerHeun(),dt=0.01) for i in 1:400)

mean(simple_error(ImplicitEulerHeun(),dt=0.1) for i in 1:400)

sol = solve(generate_stiff_stoch_heat(1.0,1.0,adaptivealg=:RSwM1),SRIW1());

using DiffEqBenchmarks
DiffEqBenchmarks.bench_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])


text:
using Test
using Random
using ClimaCoupler, Dates, Unitful

@testset "Coupler Interface" begin
    Random.seed!(26)

    coupler = CouplerState()

    data = rand(10, 10)
    coupler_add_field!(coupler, :test1, data)
    coupler_add_field!(coupler, :test2, data)
    coupler_add_field!(coupler, :test3, data)

    @show coupler

    @testset "coupler_get" begin
        @test data === coupler_get(coupler, :test1)

        # key not in coupler dict
        @test_throws KeyError coupler_get(coupler, :idontexist)
    end

    @testset "coupler_put!" begin
        newdata = rand(10, 10)
        coupler_put!(coupler, :test1, newdata)

        @test newdata == coupler_get(coupler, :test1)
        # coupler_put! is in-place; original data array has been modified
        @test data === coupler_get(coupler, :test1)

        # coupler_put! must be to a previously add_fielded field
        @test_throws KeyError coupler_put!(coupler, :idontexist, newdata)
        # incoming data must match dimensions of add_fielded field
        @test_throws DimensionMismatch coupler_put!(coupler, :test1, rand(10, 5))
    end
end

max_stars_repo_name: CliMA/ClimaCoupler


text:
# ------------------------------------------------------------------
# Licensed under the MIT License. See LICENSE in the project root.
# ------------------------------------------------------------------

module GeoStats

using Reexport

# reexport project modules
@reexport using Meshes
@reexport using GeoStatsBase
@reexport using Variography
@reexport using KrigingEstimators
@reexport using PointPatterns
@reexport using GeoClustering
@reexport using GeoEstimation
@reexport using GeoSimulation
@reexport using GeoLearning

end


text:
using Pkg

download_info = Dict(
    "CORE_BUNDLE_URL" => ("https://github.com/bmharsha/PlotlyJS.jl/releases/download/v0.12.90/plotly-latest.min.js", "49931a0d14ec3f33e91739836539bc9c6f218024f2dd786349b0b38b3cad436510dc0431dcde4c445fa80ff0ff85b06f74effda3df9932184131d32302cce51d"),
    "GENERIC_HTTP_BUNDLE_URL" => ("https://github.com/bmharsha/PlotlyJS.jl/releases/download/v0.12.90/plotschema.json", "f9fd4d2fbd4bcb2bc7b5ef540f6115d3d2dc9859715c60030a68fe37b4ca5204c8e76eb3bad643ff501f3940d9ffc357ef044bed7a3e0a880a51"),
)

const _pkg_root = dirname(dirname(@__FILE__))
const _pkg_deps = joinpath(_pkg_root,"deps")
const _pkg_assets = joinpath(_pkg_root,"assets")

!isdir(_pkg_assets) && mkdir(_pkg_assets)

function datadown(thepath, thefile, theurl)
    filepath = joinpath(thepath, thefile)
    try
        Pkg.PlatformEngines.probe_platform_engines!()
        Pkg.PlatformEngines.download(theurl, filepath)
    catch
        if isfile(filepath)
            @warn("Failed to update $thefile, but you already have it. Things might continue to work, but if you would like to make sure you have the latest version of $thefile, use may use your web-browser to download it from $theurl and place it in $_pkg_deps.")
        else
            error("Failed to download $thefile from $theurl. You may use your web-browser to download it from $theurl and place it in $_pkg_deps.")
        end
    end
end

URL = Pkg.pkg_server() * "/binary/PlotlyJS.jl/v0.12.90/plotschema.json"
datadown(_pkg_deps, "plotschema.json", URL)
URL = Pkg.pkg_server() * "/binary/PlotlyJS.jl/v0.12.90/plotly-latest.min.js"
datadown(_pkg_assets, "plotly-latest.min.js", URL)

include("make_schema_docs.jl")
include("find_attr_groups.jl")
AttrGroups.main()


text:
@testset "BOCcos" begin
    @testset "BOCCos($(get_system_string(system)), 0, $n)" for system in [GPSL1()], n in [1]#[GPSL1(), GPSL5(), GalileoE1B()], n in [1, 5, 10]
        boc = BOCcos(system, 0, n)
        @test @inferred(get_center_frequency(boc)) == get_center_frequency(system)
        @test @inferred(get_code_length(boc)) == get_code_length(system)
        @test @inferred(get_secondary_code_length(boc)) == get_secondary_code_length(system)
        @test @inferred(get_code(boc, 0, 1)) == get_code(system, 0, 1)
        @test @inferred(get_code(boc, 0.0, 1)) == get_code(system, 0.0, 1)
        @test @inferred(get_data_frequency(boc)) == get_data_frequency(system)
        @test @inferred(get_code_frequency(boc)) == n * get_code_frequency(system)
        @test get_code.(boc, 0:1022, 1) == get_code.(system, 0:1022, 1)
        @test GNSSSignals.get_code_unsafe.(boc, 0:1022, 1) == get_code.(system, 0:1022, 1)
        @test GNSSSignals.get_code_unsafe.(boc, 0.0:1022.0, 1) == get_code.(system, 0.0:1022.0, 1)
    end

    @testset "BOCcos(GPSL1, $m, 1) modulation" for m in [1,2,2.5,5,12.5]
        gpsl1 = GPSL1()
        rate = 1e-3
        tau = 0:rate:10
        boc_code = get_code.(BOCcos(gpsl1, m, 1), tau, 1) ./ get_code.(gpsl1, tau, 1)
        idx = findall(diff(boc_code) .== 2)
        len = mean(diff(idx))
        @test isapprox(len, 1 / (m * rate), atol = 1 / length(idx))
    end
end


text:
function lotofacil()
  i = 0; jogo = 0; sorteio = 1;

  while jogo != sorteio
    jogo = sortear(25,15);
    sorteio = sortear(25,15);
    i += 1;
  end

  println("Jogo: ", jogo);
  println("Numero de Jogos: ", i);
  return
end

function lotofacil(t)
  i = 0
  jogo = 0; sorteio = 1

  if !(t∈[11,12,13,14,15])
    return "Por favor, escolha como parâmetro 11, 12, 13, 14 ou 15."
  end

  while length(∩(sorteio,jogo)) < t
    jogo = sortear(25,15);
    sorteio = sortear(25,15);
    i += 1;
  end

  intersec = length(∩(sorteio,jogo))

  println("Sorteio:\n", sorteio)
  println("Jogo de acerto:\n", jogo, " (", intersec, " acertos!)\n")
  println("Numero de Jogos: ", i)
  return
end

max_stars_repo_name: fabiom/loteria

max_issues_repo_name: fabiom/loteria

max_forks_repo_name: fabiom/loteria


text:
module kernels

using ..gpflow
import ..gpflow: instantiate!
export
    Combination,
    Product,
    Sum,
    Stationary,
    Convolutional,
    WeightedConvolutional,
    Cosine,
    Exponential,
    RationalQuadratic,
    SquaredExponential,
    Linear,
    Polynomial,
    Matern12,
    Matern32,
    Matern52,
    Static,
    White,
    Bias,
    Constant,
    ArcCosine,
    Periodic,
    Coregion,
    instantiate!

# Stationary Kernels

abstract type AbstractStationary <: Kernel end
abstract type AbstractLinear <: Kernel end
abstract type AbstractCombination <: Kernel end
abstract type AbstractStatic <: Kernel end

"""
    Combine a list of kernels, e.g. by adding or multiplying (see inheriting
    classes).

    The names of the kernels to be combined are generated from their class
    names.
"""
mutable struct Combination <: AbstractCombination
    kernels
    name::Union{String, Nothing}
    o::Union{PyObject, Nothing}
end

function Combination(
    kernels;
    name=nothing
)
    out = Combination(kernels, name, nothing)
    instantiate!(out)
    return out
end

function instantiate!(o::Union{Combination, Nothing})
    if o === nothing return nothing end
    if typeof(o.o)<:PyObject return o.o end
    o.o = py_gpflow.kernels.Combination(
        [kern.o for kern in o.kernels];
        name=o.name
    )
    return o.o
end

mutable struct Product <: AbstractCombination
    kernels
    name::Union{String, Nothing}
    o::Union{PyObject, Nothing}
end

function Product(
    kernels;
    name=nothing
)
    out = Product(kernels, name, nothing)
    instantiate!(out)
    return out
end

function instantiate!(o::Union{Product, Nothing})
    if o === nothing return nothing end
    if typeof(o.o)<:PyObject return o.o end
    o.o = py_gpflow.kernels.Product(
        [kern.o for kern in o.kernels];
        name=o.name
    )
    return o.o
end

mutable struct Sum <: AbstractCombination
    kernels
    name::Union{String, Nothing}
    o::Union{PyObject, Nothing}
end

function Sum(
    kernels;
    name=nothing
)
    out = Sum(kernels, name, nothing)
    instantiate!(out)
    return out
end

function instantiate!(o::Union{Sum, Nothing})
    if o === nothing return nothing end
    if typeof(o.o)<:PyObject return o.o end
    o.o = py_gpflow.kernels.Sum(
        [kern.o for kern in o.kernels];
        name=o.name
    )
    return o.o
end

"""
    Base class for kernels that are stationary, that is, they only depend on

        r = || x - x' ||

    This class handles 'ARD' behaviour, which stands for 'Automatic Relevance
    Determination'. This means that the kernel has one lengthscale per
    dimension, otherwise the kernel is isotropic (has a single lengthscale).
"""
mutable struct Stationary <: AbstractStationary
    input_dim
    variance
    lengthscales
    active_dims
    ARD
    name::Union{String, Nothing}
    o::Union{PyObject, Nothing}
end

function Stationary(
    input_dim;
    variance=1.0,
    lengthscales=1.0,
    active_dims=nothing,
    ARD=nothing,
    name=nothing
)
    out = Stationary(input_dim, variance, lengthscales, active_dims, ARD, name, nothing)
    instantiate!(out)
    return out
end

function instantiate!(o::Union{Stationary, Nothing})
    if o === nothing return nothing end
    if typeof(o.o)<:PyObject return o.o end
    o.o = py_gpflow.kernels.Stationary(
        o.input_dim;
        variance=o.variance,
        lengthscales=o.lengthscales,
        active_dims=o.active_dims,
        ARD=o.ARD,
        name=o.name
    )
    return o.o
end

"""
    Plain convolutional kernel as described in \\citet{vdw2017convgp}. Defines
    a GP f( ) that is constructed from a sum of responses of individual patches
    in an image:
    f(x) = \\sum_p x^{[p]}
    where x^{[p]} is the pth patch in the image.

    @incollection{vdw2017convgp,
    title = {Convolutional Gaussian Processes},
    author = {van der Wilk, Mark and Rasmussen, Carl Edward and Hensman, James},
    booktitle = {Advances in Neural Information Processing Systems 30},
    year = {2017},
    url = {http://papers.nips.cc/paper/6877-convolutional-gaussian-processes.pdf}
    }
"""
mutable struct Convolutional <: AbstractStationary
    basekern
    img_size
    patch_size
    colour_channels
    o::Union{PyObject, Nothing}
end

function Convolutional(
    basekern,
    img_size,
    patch_size;
    colour_channels=1
)
    out = Convolutional(basekern, img_size, patch_size, colour_channels, nothing)
    instantiate!(out)
    return out
end

function instantiate!(o::Union{Convolutional, Nothing})
    if o === nothing return nothing end
    if typeof(o.o)<:PyObject return o.o end
    o.o = py_gpflow.kernels.Convolutional(
        o.basekern,
        o.img_size,
        o.patch_size;
        colour_channels=o.colour_channels
    )
    return o.o
end

"""
    Similar to `Convolutional`, but with different weights for each patch:
      f(x) = \\sum_p x^{[p]}

     @incollection{vdw2017convgp,
      title = {Convolutional Gaussian Processes},
      author = {van der Wilk, Mark and Rasmussen, Carl Edward and Hensman, James},
      booktitle = {Advances in Neural Information Processing Systems 30},
      year = {2017},
      url = {http://papers.nips.cc/paper/6877-convolutional-gaussian-processes.pdf}
    }
"""
mutable struct WeightedConvolutional <: AbstractStationary
    basekern
    img_size
    patch_size
    colour_channels
    o::Union{PyObject, Nothing}
end

function WeightedConvolutional(
    basekern,
    img_size,
    patch_size;
    colour_channels=1
)
    out = WeightedConvolutional(basekern, img_size, patch_size, colour_channels, nothing)
    instantiate!(out)
    return out
end

function instantiate!(o::Union{WeightedConvolutional, Nothing})
    if o === nothing return nothing end
    if typeof(o.o)<:PyObject return o.o end
    o.o = py_gpflow.kernels.WeightedConvolutional(
        o.basekern,
        o.img_size,
        o.patch_size;
        colour_channels=o.colour_channels
    )
    return o.o
end

"""
    The Cosine kernel. Functions drawn from a GP with this kernel are sinusoids
    (with a random phase).  The kernel equation is

        k(r) =  σ² cos{r}

    where:
    r  is the Euclidean distance between the input points, scaled by the lengthscale parameter ℓ,
    σ² is the variance parameter.
"""
mutable struct Cosine <: AbstractStationary
    input_dim
    variance
    lengthscales
    active_dims
    ARD
    name::Union{String, Nothing}
    o::Union{PyObject, Nothing}
end

function Cosine(
    input_dim;
    variance=1.0,
    lengthscales=1.0,
    active_dims=nothing,
    ARD=nothing,
    name=nothing
)
    out = Cosine(input_dim, variance, lengthscales, active_dims, ARD, name, nothing)
    instantiate!(out)
    return out
end

function instantiate!(o::Union{Cosine, Nothing})
    if o === nothing return nothing end
    if typeof(o.o)<:PyObject return o.o end
    o.o = py_gpflow.kernels.Cosine(
        o.input_dim;
        variance=o.variance,
        lengthscales=o.lengthscales,
        active_dims=o.active_dims,
        ARD=o.ARD,
        name=o.name
    )
    return o.o
end

"""
    The Exponential kernel. It is equivalent to a Matern12 kernel with doubled lengthscales.
"""
mutable struct Exponential <: AbstractStationary
    input_dim
    variance
    lengthscales
    active_dims
    ARD
    name::Union{String, Nothing}
    o::Union{PyObject, Nothing}
end

function Exponential(
    input_dim;
    variance=1.0,
    lengthscales=1.0,
    active_dims=nothing,
    ARD=nothing,
    name=nothing
)
    out = Exponential(input_dim, variance, lengthscales, active_dims, ARD, name, nothing)
    instantiate!(out)
    return out
end

function instantiate!(o::Union{Exponential, Nothing})
    if o === nothing return nothing end
    if typeof(o.o)<:PyObject return o.o end
    o.o = py_gpflow.kernels.Exponential(
        o.input_dim;
        variance=o.variance,
        lengthscales=o.lengthscales,
        active_dims=o.active_dims,
        ARD=o.ARD,
        name=o.name
    )
    return o.o
end

"""
    Rational Quadratic kernel. The kernel equation is

    k(r) = σ² (1 + r² / 2α)^(-α)

    where:
    r  is the Euclidean distance between the input points, scaled by the lengthscale parameter ℓ,
    σ² is the variance parameter,
    α  determines relative weighting of small-scale and large-scale fluctuations.

    For α → ∞, the RQ kernel becomes equivalent to the squared exponential.
"""
mutable struct RationalQuadratic <: AbstractStationary
    input_dim
    variance
    lengthscales
    active_dims
    ARD
    name::Union{String, Nothing}
    o::Union{PyObject, Nothing}
end

function RationalQuadratic(
    input_dim;
    variance=1.0,
    lengthscales=1.0,
    active_dims=nothing,
    ARD=nothing,
    name=nothing
)
    out = RationalQuadratic(input_dim, variance, lengthscales, active_dims, ARD, name, nothing)
    instantiate!(out)
    return out
end

function instantiate!(o::Union{RationalQuadratic, Nothing})
    if o === nothing return nothing end
    if typeof(o.o)<:PyObject return o.o end
    o.o = py_gpflow.kernels.RationalQuadratic(
        o.input_dim;
        variance=o.variance,
        lengthscales=o.lengthscales,
        active_dims=o.active_dims,
        ARD=o.ARD,
        name=o.name
    )
    return o.o
end

"""
    The radial basis function (RBF) or squared exponential kernel. The kernel equation is

        k(r) = σ² exp{-½ r²}

    where:
    r   is the Euclidean distance between the input points, scaled by the lengthscale parameter ℓ.
    σ²  is the variance parameter

    Functions drawn from a GP with this kernel are infinitely differentiable!
"""
mutable struct SquaredExponential <: AbstractStationary
    input_dim
    variance
    lengthscales
    active_dims
    ARD
    name::Union{String, Nothing}
    o::Union{PyObject, Nothing}
end

function SquaredExponential(
    input_dim;
    variance=1.0,
    lengthscales=1.0,
    active_dims=nothing,
    ARD=nothing,
    name=nothing
)
    out = SquaredExponential(input_dim, variance, lengthscales, active_dims, ARD, name, nothing)
    instantiate!(out)
    return out
end

function instantiate!(o::Union{SquaredExponential, Nothing})
    if o === nothing return nothing end
    if typeof(o.o)<:PyObject return o.o end
    o.o = py_gpflow.kernels.SquaredExponential(
        o.input_dim;
        variance=o.variance,
        lengthscales=o.lengthscales,
        active_dims=o.active_dims,
        ARD=o.ARD,
        name=o.name
    )
    return o.o
end

RBF = SquaredExponential

"""
    The linear kernel. Functions drawn from a GP with this kernel are linear, i.e. f(x) = cx. The kernel equation is

        k(x, y) = σ²xy

    where:
    σ²  is the variance parameter.
"""
mutable struct Linear <: AbstractLinear
    input_dim
    variance
    active_dims
    ARD
    name::Union{String, Nothing}
    o::Union{PyObject, Nothing}
end

function Linear(
    input_dim;
    variance=1.0,
    active_dims=nothing,
    ARD=nothing,
    name=nothing
)
    out = Linear(input_dim, variance, active_dims, ARD, name, nothing)
    instantiate!(out)
    return out
end

function instantiate!(o::Union{Linear, Nothing})
    if o === nothing return nothing end
    if typeof(o.o)<:PyObject return o.o end
    o.o = py_gpflow.kernels.Linear(
        o.input_dim;
        variance=o.variance,
        active_dims=o.active_dims,
        ARD=o.ARD,
        name=o.name
    )
    return o.o
end

"""
    The Polynomial kernel. Functions drawn from a GP with this kernel are
    polynomials of degree `d`. The kernel equation is

        k(x, y) = (σ²xy + γ) ^ d

    where:
    σ² is the variance parameter,
    γ is the offset parameter,
    d is the degree parameter.
"""
mutable struct Polynomial <: AbstractLinear
    input_dim
    degree
    variance
    offset
    active_dims
    ARD
    name::Union{String, Nothing}
    o::Union{PyObject, Nothing}
end

function Polynomial(
    input_dim;
    degree=3.0,
    variance=1.0,
    offset=1.0,
    active_dims=nothing,
    ARD=nothing,
    name=nothing
)
    out = Polynomial(input_dim, degree, variance, offset, active_dims, ARD, name, nothing)
    instantiate!(out)
    return out
end

function instantiate!(o::Union{Polynomial, Nothing})
    if o === nothing return nothing end
    if typeof(o.o)<:PyObject return o.o end
    o.o = py_gpflow.kernels.Polynomial(
        o.input_dim;
        degree=o.degree,
        variance=o.variance,
        offset=o.offset,
        active_dims=o.active_dims,
        ARD=o.ARD,
        name=o.name
    )
    return o.o
end

"""
    The Matern 1/2 kernel. Functions drawn from a GP with this kernel are not
    differentiable anywhere. The kernel equation is

    k(r) = σ² exp{-r}

    where:
    r  is the Euclidean distance between the input points, scaled by the lengthscale parameter ℓ.
    σ² is the variance parameter
"""
mutable struct Matern12 <: AbstractStationary
    input_dim
    variance
    lengthscales
    active_dims
    ARD
    name::Union{String, Nothing}
    o::Union{PyObject, Nothing}
end

function Matern12(
    input_dim;
    variance=1.0,
    lengthscales=1.0,
    active_dims=nothing,
    ARD=nothing,
    name=nothing
)
    out = Matern12(input_dim, variance, lengthscales, active_dims, ARD, name, nothing)
    instantiate!(out)
    return out
end

function instantiate!(o::Union{Matern12, Nothing})
    if o === nothing return nothing end
    if typeof(o.o)<:PyObject return o.o end
    o.o = py_gpflow.kernels.Matern12(
        o.input_dim;
        variance=o.variance,
        lengthscales=o.lengthscales,
        active_dims=o.active_dims,
        ARD=o.ARD,
        name=o.name
    )
    return o.o
end

mutable struct Matern32 <: AbstractStationary
    input_dim
    variance
    lengthscales
    active_dims
    ARD
    name::Union{String, Nothing}
    o::Union{PyObject, Nothing}
end

"""
    The Matern 3/2 kernel. Functions drawn from a GP with this kernel are once
    differentiable. The kernel equation is

    k(r) = σ² (1 + √3r) exp{-√3 r}

    where:
    r  is the Euclidean distance between the input points, scaled by the lengthscale parameter ℓ,
    σ² is the variance parameter.
"""
function Matern32(
    input_dim;
    variance=1.0,
    lengthscales=1.0,
    active_dims=nothing,
    ARD=nothing,
    name=nothing
)
    out = Matern32(input_dim, variance, lengthscales, active_dims, ARD, name, nothing)
    instantiate!(out)
    return out
end

function instantiate!(o::Union{Matern32, Nothing})
    if o === nothing return nothing end
    if typeof(o.o)<:PyObject return o.o end
    o.o = py_gpflow.kernels.Matern32(
        o.input_dim;
        variance=o.variance,
        lengthscales=o.lengthscales,
        active_dims=o.active_dims,
        ARD=o.ARD,
        name=o.name
    )
    return o.o
end

"""
    The Matern 5/2 kernel. Functions drawn from a GP with this kernel are twice
    differentiable. The kernel equation is

    k(r) = σ² (1 + √5r + 5/3r²) exp{-√5 r}

    where:
    r  is the Euclidean distance between the input points, scaled by the lengthscale parameter ℓ,
    σ² is the variance parameter.
"""
mutable struct Matern52 <: AbstractStationary
    input_dim
    variance
    lengthscales
    active_dims
    ARD
    name::Union{String, Nothing}
    o::Union{PyObject, Nothing}
end

function Matern52(
    input_dim;
    variance=1.0,
    lengthscales=1.0,
    active_dims=nothing,
    ARD=nothing,
    name=nothing
)
    out = Matern52(input_dim, variance, lengthscales, active_dims, ARD, name, nothing)
    instantiate!(out)
    return out
end

function instantiate!(o::Union{Matern52, Nothing})
    if o === nothing return nothing end
    if typeof(o.o)<:PyObject return o.o end
    o.o = py_gpflow.kernels.Matern52(
        o.input_dim;
        variance=o.variance,
        lengthscales=o.lengthscales,
        active_dims=o.active_dims,
        ARD=o.ARD,
        name=o.name
    )
    return o.o
end

# Static Kernels
"""
    Kernels who don't depend on the value of the inputs are 'Static'.  The only
    parameter is a variance, σ².
"""
mutable struct Static <: AbstractStatic
    input_dim
    variance
    active_dims
    o::Union{PyObject, Nothing}
end

function Static(
    input_dim;
    variance=1.0,
    active_dims=nothing,
)
    out = Static(input_dim, variance, active_dims, nothing)
    instantiate!(out)
    return out
end

function instantiate!(o::Union{Static, Nothing})
    if o === nothing return nothing end
    if typeof(o.o)<:PyObject return o.o end
    o.o = py_gpflow.kernels.Static(
        o.input_dim;
        variance=o.variance,
        active_dims=o.active_dims,
    )
    return o.o
end

"""
    The White kernel: this kernel produces 'white noise'. The kernel equation is

        k(x_n, x_m) = δ(n, m) σ²

    where:
    δ(.,.) is the Kronecker delta,
    σ²  is the variance parameter.
"""
mutable struct White <: AbstractStatic
    variance
    active_dims
    o::Union{PyObject, Nothing}
end

function White(;
    variance=1.0,
    active_dims=nothing,
)
    out = White(variance, active_dims, nothing)
    instantiate!(out)
    return out
end

function instantiate!(o::Union{White, Nothing})
    if o === nothing return nothing end
    if typeof(o.o)<:PyObject return o.o end
    o.o = py_gpflow.kernels.White(;
        variance=o.variance,
        active_dims=o.active_dims,
    )
    return o.o
end

"""
    Another name for the Constant kernel, included for convenience.
"""
mutable struct Bias <: AbstractStatic
    variance
    active_dims
    o::Union{PyObject, Nothing}
end

function Bias(;
    variance=1.0,
    active_dims=nothing,
)
    out = Bias(variance, active_dims, nothing)
    instantiate!(out)
    return out
end

function instantiate!(o::Union{Bias, Nothing})
    if o === nothing return nothing end
    if typeof(o.o)<:PyObject return o.o end
    o.o = py_gpflow.kernels.Bias(;
        variance=o.variance,
        active_dims=o.active_dims,
    )
    return o.o
end

"""
    The Constant (aka Bias) kernel. Functions drawn from a GP with this kernel
    are constant, i.e. f(x) = c, with c ~ N(0, σ^2). The kernel equation is

        k(x, y) = σ²

    where:
    σ²  is the variance parameter.
"""
mutable struct Constant <: AbstractStatic
    variance
    active_dims
    o::Union{PyObject, Nothing}
end

function Constant(;
    variance=1.0,
    active_dims=nothing,
)
    out = Constant(variance, active_dims, nothing)
    instantiate!(out)
    return out
end

function instantiate!(o::Union{Constant, Nothing})
    if o === nothing return nothing end
    if typeof(o.o)<:PyObject return o.o end
    o.o = py_gpflow.kernels.Constant(;
        variance=o.variance,
        active_dims=o.active_dims,
    )
    return o.o
end

"""
    The Arc-cosine family of kernels which mimics the computation in neural
    networks. The order parameter specifies the assumed activation function.
    The Multi Layer Perceptron (MLP) kernel is closely related to the ArcCosine
    kernel of order 0. The key reference is

    ::

        @incollection{NIPS2009_3628,
            title = {Kernel Methods for Deep Learning},
            author = {Youngmin Cho and Lawrence K. Saul},
            booktitle = {Advances in Neural Information Processing Systems 22},
            year = {2009},
            url = {http://papers.nips.cc/paper/3628-kernel-methods-for-deep-learning.pdf}
        }

    Note: broadcasting over leading dimensions has not yet been implemented for
    the ArcCosine kernel.
"""
mutable struct ArcCosine{T1,T2,T3,T4,T5,T6,T7,T8} <: Kernel
    input_dim::T1
    order::T2
    variance::T3
    weight_variances::T4
    bias_variance::T5
    active_dims::T6
    ARD::T7
    name::T8
    o::Union{PyObject, Nothing}
end

function ArcCosine(
    input_dim;
    order=0,
    variance=1.0,
    weight_variances=1.,
    bias_variance=1.,
    active_dims=nothing,
    ARD=nothing,
    name=nothing
)
    out = ArcCosine(
        input_dim,
        order,
        variance,
        weight_variances,
        bias_variance,
        active_dims,
        ARD,
        name,
        nothing
    )
    instantiate!(out)
    return out
end

function instantiate!(o::Union{ArcCosine, Nothing})
    if o === nothing return nothing end
    if typeof(o.o)<:PyObject return o.o end
    o.o = py_gpflow.kernels.ArcCosine(
        o.input_dim,
        order=o.order,
        variance=o.variance,
        weight_variances=o.weight_variances,
        bias_variance=o.bias_variance,
        active_dims=o.active_dims,
        ARD=o.ARD,
        name=o.name
    )
    return o.o
end

"""
    The periodic family of kernels. Can be used to wrap any Stationary kernel
    to transform it into a periodic version. The canonical form (based on the
    SquaredExponential kernel) can be found in Equation (47) of

    D.J.C.MacKay. Introduction to Gaussian processes. In C.M.Bishop, editor,
    Neural Networks and Machine Learning, pages 133--165. Springer, 1998.

    The derivation can be achieved by mapping the original inputs through the
    transformation u = (cos(x), sin(x)).

    For the SquaredExponential base kernel, the result can be expressed as:
        k(r) = σ² exp{ -0.5 sin²(π r / γ) / ℓ² }

    where:
    r is the Euclidean distance between the input points,
    ℓ is the lengthscale parameter,
    σ² is the variance parameter,
    γ is the period parameter.

    (note that usually we have a factor of 4 instead of 0.5 in front but this
    is absorbed into lengthscale hyperparameter).
"""
mutable struct Periodic{T1,T2,T3,T4,T5,T6} <: Kernel
    input_dim::T1
    period::T2
    variance::T3
    lengthscales::T4
    active_dims::T5
    name::T6
    o::Union{PyObject, Nothing}
end

function Periodic(
    input_dim;
    period=1.0,
    variance=1.0,
    lengthscales=1.0,
    active_dims=nothing,
    name=nothing
)
    out = Periodic(
        input_dim,
        period,
        variance,
        lengthscales,
        active_dims,
        name,
        nothing
    )
    instantiate!(out)
    return out
end

function instantiate!(o::Union{Periodic, Nothing})
    if o === nothing return nothing end
    if typeof(o.o)<:PyObject return o.o end
    o.o = py_gpflow.kernels.Periodic(
        o.input_dim;
        period=o.period,
        variance=o.variance,
        lengthscales=o.lengthscales,
        active_dims=o.active_dims,
        name=o.name
    )
    return o.o
end

"""
    A Coregionalization kernel. The inputs to this kernel are _integers_
    (we cast them from floats as needed) which usually specify the
    *outputs* of a Coregionalization model.

    The parameters of this kernel, W, kappa, specify a positive-definite
    matrix B.

        B = W W^T + diag(kappa) .

    The kernel function is then an indexing of this matrix, so

        K(x, y) = B[x, y] .

    We refer to the size of B as "num_outputs x num_outputs", since this is
    the number of outputs in a coregionalization model. We refer to the
    number of columns on W as 'rank': it is the number of degrees of
    correlation between the outputs.

    NB. There is a symmetry between the elements of W, which creates a
    local minimum at W=0. To avoid this, it's recommended to initialize the
    optimization (or MCMC chain) using a random W.
"""
mutable struct Coregion{T1,T2,T3} <: Kernel
    output_dim::T1
    rank::T2
    active_dims::T3
    o::Union{PyObject, Nothing}
end

function Coregion(
    output_dim,
    rank;
    active_dims=nothing,
)
    out = Coregion(
        output_dim,
        rank,
        active_dims,
        nothing
    )
    instantiate!(out)
    return out
end

function instantiate!(o::Union{Coregion, Nothing})
    if o === nothing return nothing end
    if typeof(o.o)<:PyObject return o.o end
    o.o = py_gpflow.kernels.Coregion(
        o.output_dim,
        o.rank;
        active_dims=o.active_dims
    )
    return o.o
end

end # module