text:
using JuMP, EAGO

                     m = Model()

                     EAGO.register_eago_operators!(m)

                     @variable(m, -1 <= x[i=1:3] <= 1)

                     @variable(m, -19.736879506320445 <= q <= 22.217442927624916)

                     add_NL_constraint(m, :(softplus(-0.3136061325511519 + 0.2821341474705279*softplus(0.7833824073251248 + 0.1390648465658577*$(x[1]) + -0.6617731040629309*$(x[2]) + -0.5974574624055107*$(x[3])) + 0.4396178028948987*softplus(-0.7125949557702831 + 0.9109805514170546*$(x[1]) + 0.42115237771853087*$(x[2]) + 0.7134573642319126*$(x[3])) + -0.24849525966922226*softplus(-0.36270963442709325 + 0.07407412170431016*$(x[1]) + -0.6239570881148437*$(x[2]) + -0.6542866380333012*$(x[3])) + 0.5972646324288218*softplus(-0.5451890615285553 + -0.19626106399785304*$(x[1]) + 0.5284606976702149*$(x[2]) + 0.2694706847237054*$(x[3])) + -0.8620507270647968*softplus(0.35158020081654806 + 0.8300503955389886*$(x[1]) + -0.8477304064925764*$(x[2]) + 0.1840810006485709*$(x[3]))) + softplus(-0.9705953045797062 + -0.6259685253929317*softplus(0.7833824073251248 + 0.1390648465658577*$(x[1]) + -0.6617731040629309*$(x[2]) + -0.5974574624055107*$(x[3])) + 0.41918630672941015*softplus(-0.7125949557702831 + 0.9109805514170546*$(x[1]) + 0.42115237771853087*$(x[2]) + 0.7134573642319126*$(x[3])) + -0.9388772793667424*softplus(-0.36270963442709325 + 0.07407412170431016*$(x[1]) + -0.6239570881148437*$(x[2]) + -0.6542866380333012*$(x[3])) + -0.18849282727638839*softplus(-0.5451890615285553 + -0.19626106399785304*$(x[1]) + 0.5284606976702149*$(x[2]) + 0.2694706847237054*$(x[3])) + -0.7819718693068158*softplus(0.35158020081654806 + 0.8300503955389886*$(x[1]) + -0.8477304064925764*$(x[2]) + 0.1840810006485709*$(x[3]))) + softplus(0.8285261526161638 + 0.6863822914423507*softplus(0.7833824073251248 + 0.1390648465658577*$(x[1]) + -0.6617731040629309*$(x[2]) + -0.5974574624055107*$(x[3])) + -0.7060930690780838*softplus(-0.7125949557702831 + 0.9109805514170546*$(x[1]) + 0.42115237771853087*$(x[2]) + 0.7134573642319126*$(x[3])) + -0.2956343589188948*softplus(-0.36270963442709325 + 0.07407412170431016*$(x[1]) + -0.6239570881148437*$(x[2]) + -0.6542866380333012*$(x[3])) + 0.32353098534638214*softplus(-0.5451890615285553 + -0.19626106399785304*$(x[1]) + 0.5284606976702149*$(x[2]) + 0.2694706847237054*$(x[3])) + 0.6963022628505415*softplus(0.35158020081654806 + 0.8300503955389886*$(x[1]) + -0.8477304064925764*$(x[2]) + 0.1840810006485709*$(x[3]))) + softplus(-0.2246585184074279 + 0.8591320330102441*softplus(0.7833824073251248 + 0.1390648465658577*$(x[1]) + -0.6617731040629309*$(x[2]) + -0.5974574624055107*$(x[3])) + -0.5037522661683527*softplus(-0.7125949557702831 + 0.9109805514170546*$(x[1]) + 0.42115237771853087*$(x[2]) + 0.7134573642319126*$(x[3])) + 0.9621050832972355*softplus(-0.36270963442709325 + 0.07407412170431016*$(x[1]) + -0.6239570881148437*$(x[2]) + -0.6542866380333012*$(x[3])) + -0.1995700954953512*softplus(-0.5451890615285553 + -0.19626106399785304*$(x[1]) + 0.5284606976702149*$(x[2]) + 0.2694706847237054*$(x[3])) + 0.442251462608958*softplus(0.35158020081654806 + 0.8300503955389886*$(x[1]) + -0.8477304064925764*$(x[2]) + 0.1840810006485709*$(x[3]))) + softplus(0.5761249271362421 + -0.042724357144423575*softplus(0.7833824073251248 + 0.1390648465658577*$(x[1]) + -0.6617731040629309*$(x[2]) + -0.5974574624055107*$(x[3])) + -0.4537006876708345*softplus(-0.7125949557702831 + 0.9109805514170546*$(x[1]) + 0.42115237771853087*$(x[2]) + 0.7134573642319126*$(x[3])) + -0.12519521024691826*softplus(-0.36270963442709325 + 0.07407412170431016*$(x[1]) + -0.6239570881148437*$(x[2]) + -0.6542866380333012*$(x[3])) + -0.7426009177864223*softplus(-0.5451890615285553 + -0.19626106399785304*$(x[1]) + 0.5284606976702149*$(x[2]) + 0.2694706847237054*$(x[3])) + -0.8758186284143128*softplus(0.35158020081654806 + 0.8300503955389886*$(x[1]) + -0.8477304064925764*$(x[2]) + 0.1840810006485709*$(x[3]))) - $q <= 0.0))

                     @objective(m, Min, q)

                     return m

max_stars_repo_name: PSORLab/RSActivationFunctions

max_issues_repo_name: PSORLab/RSActivationFunctions

max_forks_repo_name: PSORLab/RSActivationFunctions


text:
########## Utility functions for scripts ##########

"""
    load_data(infile::String, pm::NamedTuple)

Load a time series from `infile` with the parameter set `pm`. Example of `pm`:
```
parms = (
    # for intraday data only
    intraday = true,
    # date range of data
    date_start = Dates.DateTime("0000-01-01"), date_end = Dates.DateTime("9999-01-01"),
    # daily time range
    wa = Dates.Hour(9) + Dates.Minute(30), wb = Dates.Hour(16) + Dates.Minute(0),
    adjusted = false,  # adjust intraday data

    # index of the column in the dataframe to work on
    column_index = 1,
)
```
"""
function load_data(infile::String, pm::NamedTuple)

    toto0 = TimeSeries.readtimearray(infile, format="yyyy-mm-dd HH:MM:SS", delim=',')
    cname = TimeSeries.colnames(toto0)[pm.column_index]
    toto0 = toto0[cname]

    if pm.intraday  # load intraday data
        toto = TimeSeries.to(TimeSeries.from(toto0, pm.date_start), pm.date_end)

        # Data splitted per day
        DataSplt = FracFin.window_split_timearray(toto, Dates.Day(1), (pm.wa, pm.wb); fillmode=:fb)
        #   Npd = size(DataSplt[1])[1]  # number of samples per day

        Data = if pm.adjusted
            vcat(FracFin.equalize_daynight(DataSplt)...)  # data with overnight effect removed
        else
            vcat(DataSplt...)  # raw data
        end

        return (DataRaw=Data, DataSplt=DataSplt)
    else
        return (DataRaw=toto0, DataSplt=nothing)
    end
end

ext: jl

max_stars_repo_name: yanncalec/FracFin

max_issues_repo_name: yanncalec/FracFin

max_forks_repo_name: yanncalec/FracFin


text:
@userplot HiScatter
@recipe function f(hs::HiScatter)
    data = hs.args[1]
    bin = hs.args[2]
    xaxis --> :log10
    yaxis --> :log10

    bin += 1
    m, M = minimum(data), maximum(data)
    stat_class = 10 .^ LinRange(log10(m), log10(M), bin)
    freq = [sum(data .< stat_class[2])]
    for k in 2:(bin-1)
        push!(freq, sum(stat_class[k] .≤ data .< stat_class[k+1]))
    end
    freq[end] += sum(data .≥ stat_class[end])
    x = stat_class[2:end][freq .> 0]
    y = freq[freq .> 0]
    # length(data) == sum(y)
    # println(bin)
    @series begin
        seriestype := :scatter
        xticks --> (10.0 .^((-8):8))[m .≤ 10.0 .^((-8):8) .≤ M]
        yticks --> (10.0 .^((-8):8))[stat_class[1] .≤ 10.0 .^((-8):8) .≤ stat_class[end]]
        x, y
    end
end


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

"""
    associate_created_artifact(created_artifact, migration_task_name, progress_update_stream)
    associate_created_artifact(created_artifact, migration_task_name, progress_update_stream, params::Dict{String,<:Any})

Associates a created artifact of an AWS cloud resource, the target receiving the migration,
with the migration task performed by a migration tool. This API has the following traits:
Migration tools can call the AssociateCreatedArtifact operation to indicate which AWS
artifact is associated with a migration task.   The created artifact name must be provided
in ARN (Amazon Resource Name) format which will contain information about type and region;
for example: arn:aws:ec2:us-east-1:488216288981:image/ami-6d0ba87b.   Examples of the AWS
resource behind the created artifact are, AMI's, EC2 instance, or DMS endpoint, etc.

# Arguments
- `created_artifact`: An ARN of the AWS resource related to the migration (e.g., AMI, EC2
  instance, RDS instance, etc.)
- `migration_task_name`: Unique identifier that references the migration task. Do not store
  personal data in this field.
- `progress_update_stream`: The name of the ProgressUpdateStream.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"DryRun"`: Optional boolean flag to indicate whether any effect should take place. Used
  to test if the caller has permission to make the call.
"""
function associate_created_artifact(
    CreatedArtifact,
    MigrationTaskName,
    ProgressUpdateStream;
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return migration_hub(
        "AssociateCreatedArtifact",
        Dict{String,Any}(
            "CreatedArtifact" => CreatedArtifact,
            "MigrationTaskName" => MigrationTaskName,
            "ProgressUpdateStream" => ProgressUpdateStream,
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function associate_created_artifact(
    CreatedArtifact,
    MigrationTaskName,
    ProgressUpdateStream,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return migration_hub(
        "AssociateCreatedArtifact",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}(
                    "CreatedArtifact" => CreatedArtifact,
                    "MigrationTaskName" => MigrationTaskName,
                    "ProgressUpdateStream" => ProgressUpdateStream,
                ),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    associate_discovered_resource(discovered_resource, migration_task_name, progress_update_stream)
    associate_discovered_resource(discovered_resource, migration_task_name, progress_update_stream, params::Dict{String,<:Any})

Associates a discovered resource ID from Application Discovery Service with a migration
task.

# Arguments
- `discovered_resource`: Object representing a Resource.
- `migration_task_name`: The identifier given to the MigrationTask. Do not store personal
  data in this field.
- `progress_update_stream`: The name of the ProgressUpdateStream.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"DryRun"`: Optional boolean flag to indicate whether any effect should take place. Used
  to test if the caller has permission to make the call.
"""
function associate_discovered_resource(
    DiscoveredResource,
    MigrationTaskName,
    ProgressUpdateStream;
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return migration_hub(
        "AssociateDiscoveredResource",
        Dict{String,Any}(
            "DiscoveredResource" => DiscoveredResource,
            "MigrationTaskName" => MigrationTaskName,
            "ProgressUpdateStream" => ProgressUpdateStream,
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function associate_discovered_resource(
    DiscoveredResource,
    MigrationTaskName,
    ProgressUpdateStream,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return migration_hub(
        "AssociateDiscoveredResource",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}(
                    "DiscoveredResource" => DiscoveredResource,
                    "MigrationTaskName" => MigrationTaskName,
                    "ProgressUpdateStream" => ProgressUpdateStream,
                ),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

Creates a progress update stream which is an AWS resource used for access control as well
as a namespace for migration task names that is implicitly linked to your AWS account. It
must uniquely identify the migration tool as it is used for all updates made by the tool;
however, it does not need to be unique for each AWS account because it is scoped to the AWS
account.

# Arguments
- `progress_update_stream_name`: The name of the ProgressUpdateStream. Do not store
  personal data in this field.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"DryRun"`: Optional boolean flag to indicate whether any effect should take place. Used
  to test if the caller has permission to make the call.
"""
function create_progress_update_stream(
    ProgressUpdateStreamName; aws_config::AbstractAWSConfig=global_aws_config()
)
    return migration_hub(
        "CreateProgressUpdateStream",
        Dict{String,Any}("ProgressUpdateStreamName" => ProgressUpdateStreamName);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function create_progress_update_stream(
    ProgressUpdateStreamName,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return migration_hub(
        "CreateProgressUpdateStream",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}("ProgressUpdateStreamName" => ProgressUpdateStreamName),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

Deletes a progress update stream, including all of its tasks, which was previously created
as an AWS resource used for access control. This API has the following traits:   The only
parameter needed for DeleteProgressUpdateStream is the stream name (same as a
CreateProgressUpdateStream call).   The call will return, and a background process will
asynchronously delete the stream and all of its resources (tasks, associated resources,
resource attributes, created artifacts).   If the stream takes time to be deleted, it might
still show up on a ListProgressUpdateStreams call.    CreateProgressUpdateStream,
ImportMigrationTask, NotifyMigrationTaskState, and all Associate[*] APIs related to the
tasks belonging to the stream will throw \"InvalidInputException\" if the stream of the
same name is in the process of being deleted.   Once the stream and all of its resources
are deleted, CreateProgressUpdateStream for a stream of the same name will succeed, and
that stream will be an entirely new logical resource (without any resources associated with
the old stream).

# Arguments
- `progress_update_stream_name`: The name of the ProgressUpdateStream. Do not store
  personal data in this field.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"DryRun"`: Optional boolean flag to indicate whether any effect should take place. Used
  to test if the caller has permission to make the call.
"""
function delete_progress_update_stream(
    ProgressUpdateStreamName; aws_config::AbstractAWSConfig=global_aws_config()
)
    return migration_hub(
        "DeleteProgressUpdateStream",
        Dict{String,Any}("ProgressUpdateStreamName" => ProgressUpdateStreamName);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function delete_progress_update_stream(
    ProgressUpdateStreamName,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return migration_hub(
        "DeleteProgressUpdateStream",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}("ProgressUpdateStreamName" => ProgressUpdateStreamName),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

Gets the migration status of an application.

# Arguments
- `application_id`: The configurationId in Application Discovery Service that uniquely
  identifies the grouped application.

"""
function describe_application_state(
    ApplicationId; aws_config::AbstractAWSConfig=global_aws_config()
)
    return migration_hub(
        "DescribeApplicationState",
        Dict{String,Any}("ApplicationId" => ApplicationId);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function describe_application_state(
    ApplicationId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return migration_hub(
        "DescribeApplicationState",
        Dict{String,Any}(
            mergewith(_merge, Dict{String,Any}("ApplicationId" => ApplicationId), params)
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    describe_migration_task(migration_task_name, progress_update_stream)
    describe_migration_task(migration_task_name, progress_update_stream, params::Dict{String,<:Any})

Retrieves a list of all attributes associated with a specific migration task.

# Arguments
- `migration_task_name`: The identifier given to the MigrationTask. Do not store personal
  data in this field.
- `progress_update_stream`: The name of the ProgressUpdateStream.

"""
function describe_migration_task(
    MigrationTaskName,
    ProgressUpdateStream;
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return migration_hub(
        "DescribeMigrationTask",
        Dict{String,Any}(
            "MigrationTaskName" => MigrationTaskName,
            "ProgressUpdateStream" => ProgressUpdateStream,
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function describe_migration_task(
    MigrationTaskName,
    ProgressUpdateStream,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return migration_hub(
        "DescribeMigrationTask",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}(
                    "MigrationTaskName" => MigrationTaskName,
                    "ProgressUpdateStream" => ProgressUpdateStream,
                ),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    disassociate_created_artifact(created_artifact_name, migration_task_name, progress_update_stream)
    disassociate_created_artifact(created_artifact_name, migration_task_name, progress_update_stream, params::Dict{String,<:Any})

Disassociates a created artifact of an AWS resource with a migration task performed by a
migration tool that was previously associated. This API has the following traits:   A
migration user can call the DisassociateCreatedArtifacts operation to disassociate a
created AWS Artifact from a migration task.   The created artifact name must be provided in
ARN (Amazon Resource Name) format which will contain information about type and region; for
example: arn:aws:ec2:us-east-1:488216288981:image/ami-6d0ba87b.   Examples of the AWS
resource behind the created artifact are, AMI's, EC2 instance, or RDS instance, etc.

# Arguments
- `created_artifact_name`: An ARN of the AWS resource related to the migration (e.g., AMI,
  EC2 instance, RDS instance, etc.)
- `migration_task_name`: Unique identifier that references the migration task to be
  disassociated with the artifact. Do not store personal data in this field.
- `progress_update_stream`: The name of the ProgressUpdateStream.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"DryRun"`: Optional boolean flag to indicate whether any effect should take place. Used
  to test if the caller has permission to make the call.
"""
function disassociate_created_artifact(
    CreatedArtifactName,
    MigrationTaskName,
    ProgressUpdateStream;
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return migration_hub(
        "DisassociateCreatedArtifact",
        Dict{String,Any}(
            "CreatedArtifactName" => CreatedArtifactName,
            "MigrationTaskName" => MigrationTaskName,
            "ProgressUpdateStream" => ProgressUpdateStream,
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function disassociate_created_artifact(
    CreatedArtifactName,
    MigrationTaskName,
    ProgressUpdateStream,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return migration_hub(
        "DisassociateCreatedArtifact",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}(
                    "CreatedArtifactName" => CreatedArtifactName,
                    "MigrationTaskName" => MigrationTaskName,
                    "ProgressUpdateStream" => ProgressUpdateStream,
                ),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    disassociate_discovered_resource(configuration_id, migration_task_name, progress_update_stream)
    disassociate_discovered_resource(configuration_id, migration_task_name, progress_update_stream, params::Dict{String,<:Any})

Disassociate an Application Discovery Service discovered resource from a migration task.

# Arguments
- `configuration_id`: ConfigurationId of the Application Discovery Service resource to be
  disassociated.
- `migration_task_name`: The identifier given to the MigrationTask. Do not store personal
  data in this field.
- `progress_update_stream`: The name of the ProgressUpdateStream.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"DryRun"`: Optional boolean flag to indicate whether any effect should take place. Used
  to test if the caller has permission to make the call.
"""
function disassociate_discovered_resource(
    ConfigurationId,
    MigrationTaskName,
    ProgressUpdateStream;
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return migration_hub(
        "DisassociateDiscoveredResource",
        Dict{String,Any}(
            "ConfigurationId" => ConfigurationId,
            "MigrationTaskName" => MigrationTaskName,
            "ProgressUpdateStream" => ProgressUpdateStream,
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function disassociate_discovered_resource(
    ConfigurationId,
    MigrationTaskName,
    ProgressUpdateStream,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return migration_hub(
        "DisassociateDiscoveredResource",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}(
                    "ConfigurationId" => ConfigurationId,
                    "MigrationTaskName" => MigrationTaskName,
                    "ProgressUpdateStream" => ProgressUpdateStream,
                ),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    import_migration_task(migration_task_name, progress_update_stream)
    import_migration_task(migration_task_name, progress_update_stream, params::Dict{String,<:Any})

Registers a new migration task which represents a server, database, etc., being migrated to
AWS by a migration tool. This API is a prerequisite to calling the NotifyMigrationTaskState
API as the migration tool must first register the migration task with Migration Hub.

# Arguments
- `migration_task_name`: Unique identifier that references the migration task. Do not store
  personal data in this field.
- `progress_update_stream`: The name of the ProgressUpdateStream. >

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"DryRun"`: Optional boolean flag to indicate whether any effect should take place. Used
  to test if the caller has permission to make the call.
"""
function import_migration_task(
    MigrationTaskName,
    ProgressUpdateStream;
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return migration_hub(
        "ImportMigrationTask",
        Dict{String,Any}(
            "MigrationTaskName" => MigrationTaskName,
            "ProgressUpdateStream" => ProgressUpdateStream,
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function import_migration_task(
    MigrationTaskName,
    ProgressUpdateStream,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return migration_hub(
        "ImportMigrationTask",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}(
                    "MigrationTaskName" => MigrationTaskName,
                    "ProgressUpdateStream" => ProgressUpdateStream,
                ),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

Lists all the migration statuses for your applications. If you use the optional
ApplicationIds parameter, only the migration statuses for those applications will be
returned.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"ApplicationIds"`: The configurationIds from the Application Discovery Service that
  uniquely identifies your applications.
- `"MaxResults"`: Maximum number of results to be returned per page.
- `"NextToken"`: If a NextToken was returned by a previous call, there are more results
  available. To retrieve the next page of results, make the call again using the returned
  token in NextToken.
"""
function list_application_states(; aws_config::AbstractAWSConfig=global_aws_config())
    return migration_hub(
        "ListApplicationStates"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET
    )
end
function list_application_states(
    params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()
)
    return migration_hub(
        "ListApplicationStates",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    list_created_artifacts(migration_task_name, progress_update_stream)
    list_created_artifacts(migration_task_name, progress_update_stream, params::Dict{String,<:Any})

Lists the created artifacts attached to a given migration task in an update stream. This
API has the following traits:   Gets the list of the created artifacts while migration is
taking place.   Shows the artifacts created by the migration tool that was associated by
the AssociateCreatedArtifact API.    Lists created artifacts in a paginated interface.

# Arguments
- `migration_task_name`: Unique identifier that references the migration task. Do not store
  personal data in this field.
- `progress_update_stream`: The name of the ProgressUpdateStream.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"MaxResults"`: Maximum number of results to be returned per page.
- `"NextToken"`: If a NextToken was returned by a previous call, there are more results
  available. To retrieve the next page of results, make the call again using the returned
  token in NextToken.
"""
function list_created_artifacts(
    MigrationTaskName,
    ProgressUpdateStream;
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return migration_hub(
        "ListCreatedArtifacts",
        Dict{String,Any}(
            "MigrationTaskName" => MigrationTaskName,
            "ProgressUpdateStream" => ProgressUpdateStream,
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function list_created_artifacts(
    MigrationTaskName,
    ProgressUpdateStream,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return migration_hub(
        "ListCreatedArtifacts",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}(
                    "MigrationTaskName" => MigrationTaskName,
                    "ProgressUpdateStream" => ProgressUpdateStream,
                ),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    list_discovered_resources(migration_task_name, progress_update_stream)
    list_discovered_resources(migration_task_name, progress_update_stream, params::Dict{String,<:Any})

Lists discovered resources associated with the given MigrationTask.

# Arguments
- `migration_task_name`: The name of the MigrationTask. Do not store personal data in this
  field.
- `progress_update_stream`: The name of the ProgressUpdateStream.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"MaxResults"`: The maximum number of results returned per page.
- `"NextToken"`: If a NextToken was returned by a previous call, there are more results
  available. To retrieve the next page of results, make the call again using the returned
  token in NextToken.
"""
function list_discovered_resources(
    MigrationTaskName,
    ProgressUpdateStream;
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return migration_hub(
        "ListDiscoveredResources",
        Dict{String,Any}(
            "MigrationTaskName" => MigrationTaskName,
            "ProgressUpdateStream" => ProgressUpdateStream,
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function list_discovered_resources(
    MigrationTaskName,
    ProgressUpdateStream,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return migration_hub(
        "ListDiscoveredResources",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}(
                    "MigrationTaskName" => MigrationTaskName,
                    "ProgressUpdateStream" => ProgressUpdateStream,
                ),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

Lists all, or filtered by resource name, migration tasks associated with the user account
making this call. This API has the following traits:   Can show a summary list of the most
recent migration tasks.   Can show a summary list of migration tasks associated with a
given discovered resource.   Lists migration tasks in a paginated interface.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"MaxResults"`: Value to specify how many results are returned per page.
- `"NextToken"`: If a NextToken was returned by a previous call, there are more results
  available. To retrieve the next page of results, make the call again using the returned
  token in NextToken.
- `"ResourceName"`: Filter migration tasks by discovered resource name.
"""
function list_migration_tasks(; aws_config::AbstractAWSConfig=global_aws_config())
    return migration_hub(
        "ListMigrationTasks"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET
    )
end
function list_migration_tasks(
    params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()
)
    return migration_hub(
        "ListMigrationTasks", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET
    )
end

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

Lists progress update streams associated with the user account making this call.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"MaxResults"`: Filter to limit the maximum number of results to list per page.
- `"NextToken"`: If a NextToken was returned by a previous call, there are more results
  available. To retrieve the next page of results, make the call again using the returned
  token in NextToken.
"""
function list_progress_update_streams(; aws_config::AbstractAWSConfig=global_aws_config())
    return migration_hub(
        "ListProgressUpdateStreams"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET
    )
end
function list_progress_update_streams(
    params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()
)
    return migration_hub(
        "ListProgressUpdateStreams",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    notify_application_state(application_id, status)
    notify_application_state(application_id, status, params::Dict{String,<:Any})

Sets the migration state of an application. For a given application identified by the value
passed to ApplicationId, its status is set or updated by passing one of three values to
Status: NOT_STARTED | IN_PROGRESS | COMPLETED.

# Arguments
- `application_id`: The configurationId in Application Discovery Service that uniquely
  identifies the grouped application.
- `status`: Status of the application - Not Started, In-Progress, Complete.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"DryRun"`: Optional boolean flag to indicate whether any effect should take place. Used
  to test if the caller has permission to make the call.
- `"UpdateDateTime"`: The timestamp when the application state changed.
"""
function notify_application_state(
    ApplicationId, Status; aws_config::AbstractAWSConfig=global_aws_config()
)
    return migration_hub(
        "NotifyApplicationState",
        Dict{String,Any}("ApplicationId" => ApplicationId, "Status" => Status);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function notify_application_state(
    ApplicationId,
    Status,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return migration_hub(
        "NotifyApplicationState",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}("ApplicationId" => ApplicationId, "Status" => Status),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    notify_migration_task_state(migration_task_name, next_update_seconds, progress_update_stream, task, update_date_time)
    notify_migration_task_state(migration_task_name, next_update_seconds, progress_update_stream, task, update_date_time, params::Dict{String,<:Any})

Notifies Migration Hub of the current status, progress, or other detail regarding a
migration task. This API has the following traits:   Migration tools will call the
NotifyMigrationTaskState API to share the latest progress and status.    MigrationTaskName
is used for addressing updates to the correct target.    ProgressUpdateStream is used for
access control and to provide a namespace for each migration tool.

# Arguments
- `migration_task_name`: Unique identifier that references the migration task. Do not store
  personal data in this field.
- `next_update_seconds`: Number of seconds after the UpdateDateTime within which the
  Migration Hub can expect an update. If Migration Hub does not receive an update within the
  specified interval, then the migration task will be considered stale.
- `progress_update_stream`: The name of the ProgressUpdateStream.
- `task`: Information about the task's progress and status.
- `update_date_time`: The timestamp when the task was gathered.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"DryRun"`: Optional boolean flag to indicate whether any effect should take place. Used
  to test if the caller has permission to make the call.
"""
function notify_migration_task_state(
    MigrationTaskName,
    NextUpdateSeconds,
    ProgressUpdateStream,
    Task,
    UpdateDateTime;
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return migration_hub(
        "NotifyMigrationTaskState",
        Dict{String,Any}(
            "MigrationTaskName" => MigrationTaskName,
            "NextUpdateSeconds" => NextUpdateSeconds,
            "ProgressUpdateStream" => ProgressUpdateStream,
            "Task" => Task,
            "UpdateDateTime" => UpdateDateTime,
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function notify_migration_task_state(
    MigrationTaskName,
    NextUpdateSeconds,
    ProgressUpdateStream,
    Task,
    UpdateDateTime,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return migration_hub(
        "NotifyMigrationTaskState",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}(
                    "MigrationTaskName" => MigrationTaskName,
                    "NextUpdateSeconds" => NextUpdateSeconds,
                    "ProgressUpdateStream" => ProgressUpdateStream,
                    "Task" => Task,
                    "UpdateDateTime" => UpdateDateTime,
                ),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    put_resource_attributes(migration_task_name, progress_update_stream, resource_attribute_list)
    put_resource_attributes(migration_task_name, progress_update_stream, resource_attribute_list, params::Dict{String,<:Any})

Provides identifying details of the resource being migrated so that it can be associated in
the Application Discovery Service repository. This association occurs asynchronously after
PutResourceAttributes returns.    Keep in mind that subsequent calls to
PutResourceAttributes will override previously stored attributes. For example, if it is
first called with a MAC address, but later, it is desired to add an IP address, it will
then be required to call it with both the IP and MAC addresses to prevent overriding the
MAC address.   Note the instructions regarding the special use case of the
ResourceAttributeList  parameter when specifying any \"VM\" related value.     Because this
is an asynchronous call, it will always return 200, whether an association occurs or not.
To confirm if an association was found based on the provided details, call
ListDiscoveredResources.

# Arguments
- `migration_task_name`: Unique identifier that references the migration task. Do not store
  personal data in this field.
- `progress_update_stream`: The name of the ProgressUpdateStream.
- `resource_attribute_list`: Information about the resource that is being migrated. This
  data will be used to map the task to a resource in the Application Discovery Service
  repository.  Takes the object array of ResourceAttribute where the Type field is reserved
  for the following values: IPV4_ADDRESS | IPV6_ADDRESS | MAC_ADDRESS | FQDN | VM_MANAGER_ID
  | VM_MANAGED_OBJECT_REFERENCE | VM_NAME | VM_PATH | BIOS_ID | MOTHERBOARD_SERIAL_NUMBER
  where the identifying value can be a string up to 256 characters.     If any \"VM\" related
  value is set for a ResourceAttribute object, it is required that VM_MANAGER_ID, as a
  minimum, is always set. If VM_MANAGER_ID is not set, then all \"VM\" fields will be
  discarded and \"VM\" fields will not be used for matching the migration task to a server in
  Application Discovery Service repository. See the Example section below for a use case of
  specifying \"VM\" related values.    If a server you are trying to match has multiple IP or
  MAC addresses, you should provide as many as you know in separate type/value pairs passed
  to the ResourceAttributeList parameter to maximize the chances of matching.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"DryRun"`: Optional boolean flag to indicate whether any effect should take place. Used
  to test if the caller has permission to make the call.
"""
function put_resource_attributes(
    MigrationTaskName,
    ProgressUpdateStream,
    ResourceAttributeList;
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return migration_hub(
        "PutResourceAttributes",
        Dict{String,Any}(
            "MigrationTaskName" => MigrationTaskName,
            "ProgressUpdateStream" => ProgressUpdateStream,
            "ResourceAttributeList" => ResourceAttributeList,
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function put_resource_attributes(
    MigrationTaskName,
    ProgressUpdateStream,
    ResourceAttributeList,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return migration_hub(
        "PutResourceAttributes",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}(
                    "MigrationTaskName" => MigrationTaskName,
                    "ProgressUpdateStream" => ProgressUpdateStream,
                    "ResourceAttributeList" => ResourceAttributeList,
                ),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end


text:
function heat_index(t :: T1, rh :: T2)::Real where
    {T1<:Union{Real, Missing}, T2<:Union{Real, Missing}}
#     if (is.na(rh) || is.na(t)) {
#         hi = NA
#     } else
    # print(t, ismissing(t) || ismissing(rh))
    if (ismissing(t) || ismissing(rh)); return(NaN64); end
    if (t <= 40)
        hi = t
    else
        alpha = 61 + ((t - 68) * 1.2) + (rh * 0.094)
        hi = 0.5*(alpha + t)
        if (hi > 79)
            hi = -42.379 + 2.04901523 * t + 10.14333127 * rh -
                    0.22475541 * t * rh - 6.83783 * 10^-3 * t^2 -
                    5.481717 * 10^-2 * rh^2 + 1.22874 * 10^-3 * t^2 *
                    rh + 8.5282 * 10^-4 * t * rh^2 - 1.99 * 10^-6 *
                    t^2 * rh^2
            if (rh <= 13 && t >= 80 && t <= 112)
                adjustment1 = (13 - rh)/4
                adjustment2 = sqrt((17 - abs(t - 95))/17)
                total_adjustment = adjustment1 * adjustment2
                hi = hi - total_adjustment
            elseif (rh > 85 && t >= 80 && t <= 87)
                adjustment1 = (rh - 85)/10
                adjustment2 = (87 - t)/5
                total_adjustment = adjustment1 * adjustment2
                hi = hi + total_adjustment
            end
        end
    end
    return(hi)
end

function heat_index(t :: AbstractArray{T}, rh :: AbstractArray{T}) where
    T<:Union{Real, Union{Missing, Real}}

    heat_index.(t, rh)
end

# function heat_index(t :: AbstractArray{T, 2}, rh :: AbstractArray{T, 2}):: AbstractArray{T, 2} where
#     T<:Union{Real, Union{Missing, Real}}
#     heat_index.(t, rh)
# end

max_stars_repo_name: CUG-hydro/heatwave

max_issues_repo_name: CUG-hydro/heatwave

max_forks_repo_name: CUG-hydro/heatwave


text:
module SkeletonTriangulationsTests

using Test
using Gridap.TensorValues
using Gridap.Arrays
using Gridap.Fields
using Gridap.ReferenceFEs
using Gridap.Geometry
using Gridap.Geometry: IN, OUT
using Gridap.Geometry: DiscreteModelMock

model = DiscreteModelMock()

strian = SkeletonTriangulation(model)
test_triangulation(strian)
@test get_background_triangulation(strian) === get_triangulation(model)

#function polar(q)
#  r, t, z = q
#  x = r*cos(t)
#  y = r*sin(t)
#  Point(x,y,z)
#end
#domain = (1,2,0,pi,0,0.5)
#partition = (10,30,4)
#model = CartesianDiscreteModel(domain,partition,polar)

domain = (0,1,0,1,0,1)
partition = (3,3,3)
model = CartesianDiscreteModel(domain,partition)

strian = SkeletonTriangulation(model)
test_triangulation(strian)
@test get_background_triangulation(strian) === get_triangulation(model)

#s = CompressedArray([Point{2,Float64}[(0.25,0.25),(0.75,0.75)]],get_cell_type(strian))
#
#s2x = get_cell_map(strian)
#x = laevaluate(s2x,s)
#
#nvec = get_normal_vector(strian)
#nx = evaluate(nvec,s)
#collect(nx)
#
#fun(x) = sin(pi*x[1])*cos(pi*x[2])
#
#q2x = get_cell_map(trian)
#
#funq = compose(fun,q2x)
#
#fun_gamma = restrict(funq,strian)
#
#@test isa(fun_gamma, SkeletonPair)
#
#cellids = collect(1:num_cells(trian))
#
#cellids_gamma = reindex(cellids,strian)
#@test isa(fun_gamma, SkeletonPair)
#@test cellids_gamma.plus == get_face_to_cell(strian.plus)
#@test cellids_gamma.minus == get_face_to_cell(strian.minus)
#
#ids = get_cell_to_bgcell(strian)
#@test isa(ids,SkeletonPair)
#
##using Gridap.Visualization
##
##writevtk(trian,"trian")
##writevtk(strian,"strian")
##writevtk(x,"x",nodaldata=["nvec" => nx])

model = DiscreteModelMock()

trian = Triangulation(model)

cell_to_is_left = [true,true,false,true,false]

itrian = InterfaceTriangulation(model,cell_to_is_left)

ltrian = itrian.plus
rtrian = itrian.minus
@test itrian.⁺ === ltrian
@test itrian.⁻ === rtrian

ni = get_facet_normal(itrian)
nl = get_facet_normal(ltrian)
nr = get_facet_normal(rtrian)
@test isa(ni,SkeletonPair)

#using Gridap.Visualization
#
#writevtk(trian,"trian")
#writevtk(itrian,"itrian",nsubcells=10,cellfields=["ni"=>ni,"nl"=>nl,"nr"=>nr])

domain = (0,1,0,1)
partition = (10,10)
model = CartesianDiscreteModel(domain,partition)

cell_to_inout = zeros(Int8,num_cells(model))
cell_to_inout[1:13] .= OUT
cell_to_inout[14:34] .= IN

itrian = InterfaceTriangulation(model,cell_to_inout)
@test num_cells(itrian) == 11

itrian = InterfaceTriangulation(model,1:13,14:34)
@test num_cells(itrian) == 11

#ltrian = get_left_boundary(itrian)
#rtrian = get_right_boundary(itrian)
#ni = get_normal_vector(itrian)
#nl = get_normal_vector(ltrian)
#nr = get_normal_vector(rtrian)
#trian = Triangulation(model)
#
#using Gridap.Visualization
#writevtk(trian,"trian",celldata=["inout"=>cell_to_inout])
#writevtk(itrian,"itrian",nsubcells=10,cellfields=["ni"=>ni,"nl"=>nl,"nr"=>nr])

reffe = LagrangianRefFE(Float64,QUAD,(2,2))
conf = CDConformity((CONT,DISC))
face_own_dofs = get_face_own_dofs(reffe,conf)
strian = SkeletonTriangulation(model,reffe,face_own_dofs)
test_triangulation(strian)
ns = get_facet_normal(strian)
@test length(ns.⁺) == num_cells(strian)

#using Gridap.Visualization
#writevtk(strian,"strian",cellfields=["normal"=>ns])

domain = (0,1,0,1,0,1)
partition = (3,3,3)
oldmodel = CartesianDiscreteModel(domain,partition)
oldstrian = SkeletonTriangulation(oldmodel)

sface_to_oldsface = collect(1:10)
strian = RestrictedTriangulation(oldstrian,sface_to_oldsface)
test_triangulation(strian)
@test isa(strian,SkeletonTriangulation)

end # module


text:
using VectorField
using Test

@testset "VectorField.jl" begin

end


text:
export predict!,backward!,add_layer!,add_optimizer!,get_layers,get_params,get_loss,get_now_epoch,save_model,load_model,reset!,convert_to_array,convert_to_cu,get_optimizer
#===
共通型，関数
・全てのモデルはModelCommonをcommonに持ち，Modelsの子型になる
===#

mutable struct ModelCommon
    layers
    optimizer
    epoch
    now_epoch
    min_epoch
    learn_io
    learn_plot
    loss
    min_loss
    std_params #Dict("name"=>[avg,variance,std])
    norm_params #Dict("name"=>[max,min])
    gpu_flg

    function ModelCommon(gpu_flg)
        new(
            nothing,
            nothing,
            0,
            0,
            0,
            IOBuffer(),
            nothing,
            [],
            0.0,
            Dict(),
            Dict(),
            gpu_flg
        )
    end
end

#=========
dataは全て{N,D}の形でここに渡す.
cuは引数の前にしておく
=========#
function predict!(model::Models,data,learn_flg=false)
    out = data

    @inbounds @simd for i in 1:length(model.common.layers)
        layer = get_layers(model,i)
        out = forward!(layer,out,learn_flg)
    end

    return out
end

function backward!(model::Models)
    dout = 0
    @inbounds @simd for layer in reverse(model.common.layers)
        dout = backward!(layer,dout)
    end
end

function add_layer!(model::Models,layers)
    if model.common.gpu_flg
        @inbounds for i in 1:length(layers)
            convert_to_cu!(layers[i])
        end
    end
    model.common.layers = layers
    nothing
end

function add_optimizer!(model::Models,optimizer)
    fit!(optimizer,model)
end

function reset!(model::Models)
    @inbounds @simd for i in 1:length(model.common.layers)
        reset!(model.common.layers[i])
    end
end

function convert_to_cu!(model::Models)
    #optimizer
    convert_to_cu!(get_optimizer(model),model)
    #レイヤ
    @inbounds for i in 1:length(model.common.layers)
        convert_to_cu!(model.common.layers[i])
    end
end
function convert_to_array!(model::Models)
    #optimizer
    convert_to_array!(get_optimizer(model),model)
    #レイヤ
    @inbounds for i in 1:length(model.common.layers)
        convert_to_array!(model.common.layers[i])
    end
end

function get_layers(model::Models,n=nothing)
    (n===nothing) ? model.common.layers : model.common.layers[n]
end
function get_now_epoch(model::Models)
    model.common.now_epoch
end
function get_loss(model::Models)
    model.common.loss
end
function get_params(model::Models,n=nothing)
    if n===nothing
        re = []
        @inbounds for i in 1:length(model.common.layers)
            @simd for j in 1:length(model.common.layers[i].params)
                append!(re,[model.common.layers[i].params[j]])
            end
        end
        return re
    else
        return model.common.layers[n].params
    end
end
function get_optimizer(model::Models)
    return model.common.optimizer
end

function save_model(model::Models,path)
    #パラメータ全てをArrayに直す必要がある
    if model.common.gpu_flg
        convert_to_array!(model)
    end
    save(path,"model",Dict("content"=>model))
    #GPUへ復元
    if model.common.gpu_flg
        convert_to_cu!(model)
    end
    nothing
end
function load_model(path,gpu_flg=false)
    d = load(path)
    model = d["model"]["content"]
    if gpu_flg
        convert_to_cu!(model)
    end
    return model
end

#===
ファイルの読み込み
===#
include("sequential.jl")

max_stars_repo_name: catmanium/Spike

max_issues_repo_name: catmanium/Spike

max_forks_repo_name: catmanium/Spike


text:
struct ForwardColorJacCache{T,T2,T3,T4,T5,T6}
    t::T
    fx::T2
    dx::T3
    p::T4
    colorvec::T5
    sparsity::T6
    chunksize::Int
end

function default_chunk_size(maxcolor)
    if maxcolor < DEFAULT_CHUNK_THRESHOLD
        Val(maxcolor)
    else
        Val(DEFAULT_CHUNK_THRESHOLD)
    end
end

getsize(::Val{N}) where N = N
getsize(N::Integer) = N

function ForwardColorJacCache(f,x,_chunksize = nothing;
                              dx = nothing,
                              colorvec=1:length(x),
                              sparsity::Union{AbstractArray,Nothing}=nothing)

    if _chunksize isa Nothing
        chunksize = default_chunk_size(maximum(colorvec))
    else
        chunksize = _chunksize
    end

    p = adapt.(typeof(x),generate_chunked_partials(x,colorvec,chunksize))
    t = reshape(Dual{typeof(f)}.(vec(x),first(p)),size(x)...)

    if dx isa Nothing
        fx = similar(t)
        _dx = similar(x)
    else
        pi = first(p) #perform trim (length(dx)<length(x)) or padding (length(dx)>length(x)) to first(p)
        if length(dx)>length(x)
            pi = vcat(pi,reshape(mapslices(Tuple,zeros(Bool,length(first(pi)),length(dx)-length(x)),dims=1),:))
        else
            pi = pi[1:length(dx)]
        end
        fx = reshape(Dual{typeof(f)}.(vec(dx),pi),size(dx)...)
        _dx = dx
    end

    ForwardColorJacCache(t,fx,_dx,p,colorvec,sparsity,getsize(chunksize))
end

generate_chunked_partials(x,colorvec,N::Integer) = generate_chunked_partials(x,colorvec,Val(N))
function generate_chunked_partials(x,colorvec,::Val{chunksize}) where chunksize
    maxcolor = maximum(colorvec)
    num_of_chunks = Int(ceil(maxcolor / chunksize))
    padding_size = (chunksize - (maxcolor % chunksize)) % chunksize
    partials = colorvec .== (1:maxcolor)'
    padding_matrix = BitMatrix(undef, length(x), padding_size)
    partials = hcat(partials, padding_matrix)

    chunked_partials = map(i -> Tuple.(eachrow(partials[:,(i-1)*chunksize+1:i*chunksize])),1:num_of_chunks)
    chunked_partials

end

function forwarddiff_color_jacobian(f,
                x::AbstractArray{<:Number};
                dx = copy(x), #if dx is nothing, we will estimate dx at the cost of a function call
                colorvec = 1:length(x),
                sparsity = nothing,
                jac_prototype = nothing)
    if dx isa Nothing
        dx = f(x)
    end
    forwarddiff_color_jacobian(f,x,ForwardColorJacCache(f,x,dx=dx,colorvec=colorvec,sparsity=sparsity),jac_prototype)
end

function forwarddiff_color_jacobian(f,x::AbstractArray{<:Number},jac_cache::ForwardColorJacCache,jac_prototype=nothing)
    t = jac_cache.t
    dx = jac_cache.dx
    p = jac_cache.p
    colorvec = jac_cache.colorvec
    sparsity = jac_cache.sparsity
    chunksize = jac_cache.chunksize
    color_i = 1
    maxcolor = maximum(colorvec)

    vecx = vec(x)

    J = jac_prototype isa Nothing ? (sparsity isa Nothing ? false .* vec(dx) .* vecx' : zeros(eltype(x),size(sparsity))) : zero(jac_prototype)
    nrows,ncols = size(J)

    if !(sparsity isa Nothing)
        rows_index, cols_index = ArrayInterface.findstructralnz(sparsity)
        rows_index = [rows_index[i] for i in 1:length(rows_index)]
        cols_index = [cols_index[i] for i in 1:length(cols_index)]
    end

    for i in eachindex(p)
        partial_i = p[i]
        t = reshape(Dual{typeof(f)}.(vecx, partial_i),size(t))
        fx = f(t)
        if !(sparsity isa Nothing)
            for j in 1:chunksize
                dx = vec(partials.(fx, j))
                pick_inds = [i for i in 1:length(rows_index) if colorvec[cols_index[i]] == color_i]
                rows_index_c = rows_index[pick_inds]
                cols_index_c = cols_index[pick_inds]
                len_rows = length(pick_inds)
                unused_rows = setdiff(1:nrows,rows_index_c)
                perm_rows = sortperm(vcat(rows_index_c,unused_rows))
                cols_index_c = vcat(cols_index_c,zeros(Int,nrows-len_rows))[perm_rows]
                Ji = [j==cols_index_c[i] ? dx[i] : false for i in 1:nrows, j in 1:ncols]
                J = J + Ji
                color_i += 1
                (color_i > maxcolor) && return J
            end
        else
            for j in 1:chunksize
                col_index = (i-1)*chunksize + j
                (col_index > ncols) && return J
                Ji = mapreduce(i -> i==col_index ? partials.(vec(fx), j) : zeros(nrows), hcat, 1:ncols)
                J = J + (size(Ji)!=size(J) ? reshape(Ji,size(J)) : Ji) #branch when size(dx) == (1,) => size(Ji) == (1,) while size(J) == (1,1)
            end
        end
    end
    J
end

function forwarddiff_color_jacobian!(J::AbstractMatrix{<:Number},
                f,
                x::AbstractArray{<:Number};
                dx = Array{eltype(x)}(undef,size(J,1)),
                colorvec = 1:length(x),
                sparsity = ArrayInterface.has_sparsestruct(J) ? J : nothing)
    forwarddiff_color_jacobian!(J,f,x,ForwardColorJacCache(f,x,dx=dx,colorvec=colorvec,sparsity=sparsity))
end

function forwarddiff_color_jacobian!(J::AbstractMatrix{<:Number},
                f,
                x::AbstractArray{<:Number},
                jac_cache::ForwardColorJacCache)

    t = jac_cache.t
    fx = jac_cache.fx
    dx = jac_cache.dx
    p = jac_cache.p
    colorvec = jac_cache.colorvec
    sparsity = jac_cache.sparsity
    chunksize = jac_cache.chunksize
    color_i = 1
    maxcolor = maximum(colorvec)
    fill!(J, zero(eltype(J)))

    if DiffEqDiffTools._use_findstructralnz(sparsity)
        rows_index, cols_index = ArrayInterface.findstructralnz(sparsity)
    else
        rows_index = nothing
        cols_index = nothing
    end

    vecx = vec(x)
    vect = vec(t)
    vecfx= vec(fx)
    vecdx= vec(dx)

    ncols=size(J,2)

    for i in eachindex(p)
        partial_i = p[i]
        vect .= Dual{typeof(f)}.(vecx, partial_i)
        f(fx,t)
        if !(sparsity isa Nothing)
            for j in 1:chunksize
                dx .= partials.(fx, j)
                if ArrayInterface.fast_scalar_indexing(dx)
                    #dx is implicitly used in vecdx
                    DiffEqDiffTools._colorediteration!(J,sparsity,rows_index,cols_index,vecdx,colorvec,color_i,ncols)
                else
                    #=
                    J.nzval[rows_index] .+= (colorvec[cols_index] .== color_i) .* dx[rows_index]
                    or
                    J[rows_index, cols_index] .+= (colorvec[cols_index] .== color_i) .* dx[rows_index]
                    += means requires a zero'd out start
                    =#
                    if J isa SparseMatrixCSC
                        @. setindex!((J.nzval,),getindex((J.nzval,),rows_index) + (getindex((colorvec,),cols_index) == color_i) * getindex((vecdx,),rows_index),rows_index)
                    else
                        @. setindex!((J,),getindex((J,),rows_index, cols_index) + (getindex((colorvec,),cols_index) == color_i) * getindex((vecdx,),rows_index),rows_index, cols_index)
                    end
                end
                color_i += 1
                (color_i > maxcolor) && return
            end
        else
            for j in 1:chunksize
                col_index = (i-1)*chunksize + j
                (col_index > ncols) && return
                J[:, col_index] .= partials.(vecfx, j)
            end
        end
    end
    nothing
end


text:
module TRGSW
    using ..MulFFT
    using ..TRLWE
    using ..Key
    using LinearAlgebra

    function trgswSymEncrypt(p::Array{UInt32,1},α::Float64,h::Array{Float64},key::Array{UInt32,1},plan::MulFFT.TwistFFTPlan)
        l = length(h)
        c = [[TRLWE.trlweSymEncrypt(zeros(length(key)),α,key,plan) for i in 1:2*l]...]
        ph = map(x->round.(UInt32,x),p * h')
        for i in 1:l
            c[i][1] .+= ph[i]
            c[i+l][1] .+= ph[i]
        end
        return  c
    end
    function trgswfftSymEncrypt(p::Array{UInt32,1},α::Float64,h::Array{Float64},key::Array{UInt32,1},plan::MulFFT.TwistFFTPlan)
        trgsw = trgswSymEncrypt(p,α,h,key,plan)
        return hcat([MulFFT.TwistFFT.(trgsw[i],plan.fftplan,plan.twist) for i in 1:2*length(h)]...)
    end

    function Decomposition(trlwe::Array{Array{UInt32,1},1},params::Key.lweParams)
        temp = map(x->map(y->round(Int32,(y.%(2^params.Bgbit))-2^(params.Bgbit-1)),(x.+params.offset) * params.decb'),trlwe)
        return vcat([[temp[i][j,:] for j in 1:2] for i in 1:params.l]...)
    end

    function trgswExternalProduct(trgsw::Array{Array{Array{UInt32,1},1},1},trlwe::Array{Array{UInt32,1},1},params::Key.lweParams,plan::MulFFT.TwistFFTPlan)
        decvec = Decomposition(trlwe,params)
        return [sum([MulFFT.PolyMul(decvec[i],signed.(trgsw[i][j]),plan) for i in 1:2*params.l]) for j in 1:2]
    end
end


text:
using DiffEqFlux, Flux
using LinearAlgebra, Distributions
using Optim, GalacticOptim
using Test

function run_test(f, layer, atol)

    data_train_vals = [rand(length(layer.model)) for k in 1:500]
    data_train_fn = f.(data_train_vals)

    function loss_function(component)
        data_pred = [layer(x,component) for x in data_train_vals]
        loss = sum(norm.(data_pred.-data_train_fn))/length(data_train_fn)
        return loss
    end

    function cb(p,l)
        @show l
        return false
    end

    optfunc = GalacticOptim.OptimizationFunction((x, p) -> loss_function(x), GalacticOptim.AutoZygote())
    optprob = GalacticOptim.OptimizationProblem(optfunc, layer.p)
    res = GalacticOptim.solve(optprob, ADAM(0.1), cb=cb, maxiters = 100)
    optprob = GalacticOptim.OptimizationProblem(optfunc, res.minimizer)
    res = GalacticOptim.solve(optprob, ADAM(0.01), cb=cb, maxiters = 100)
    optprob = GalacticOptim.OptimizationProblem(optfunc, res.minimizer)
    res = GalacticOptim.solve(optprob, BFGS(), cb=cb, maxiters = 200)
    opt = res.minimizer

    data_validate_vals = [rand(length(layer.model)) for k in 1:100]
    data_validate_fn = f.(data_validate_vals)

    data_validate_pred = [layer(x,opt) for x in data_validate_vals]

    return sum(norm.(data_validate_pred.-data_validate_fn))/length(data_validate_fn) < atol
end

##test 01: affine function, Chebyshev and Polynomial basis
A = rand(2,2)
b = rand(2)
f = x -> A*x + b
layer = TensorLayer([ChebyshevBasis(10), PolynomialBasis(10)], 2)
@test run_test(f, layer, 0.05)

##test 02: non-linear function, Chebyshev and Legendre basis
A = rand(2,2)
b = rand(2)
f = x -> A*x*norm(x)+ b*sin(norm(x))
layer = TensorLayer([ChebyshevBasis(7), FourierBasis(7)], 2)
@test run_test(f, layer, 0.10)


text:
# syntax: proto3
using ProtoBuf
import ProtoBuf.meta

mutable struct Identity <: ProtoType
    __protobuf_jl_internal_meta::ProtoMeta
    __protobuf_jl_internal_values::Dict{Symbol,Any}
    __protobuf_jl_internal_defaultset::Set{Symbol}

    function Identity(; kwargs...)
        obj = new(meta(Identity), Dict{Symbol,Any}(), Set{Symbol}())
        values = obj.__protobuf_jl_internal_values
        symdict = obj.__protobuf_jl_internal_meta.symdict
        for nv in kwargs
            fldname, fldval = nv
            fldtype = symdict[fldname].jtyp
            (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
            if fldval !== nothing
                values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
            end
        end
        obj
    end
end # mutable struct Identity
const __meta_Identity = Ref{ProtoMeta}()
function meta(::Type{Identity})
    ProtoBuf.metalock() do
        if !isassigned(__meta_Identity)
            __meta_Identity[] = target = ProtoMeta(Identity)
            allflds = Pair{Symbol,Union{Type,String}}[]
            meta(target, Identity, allflds, ProtoBuf.DEF_REQ, ProtoBuf.DEF_FNUM, ProtoBuf.DEF_VAL, ProtoBuf.DEF_PACK, ProtoBuf.DEF_WTYPES, ProtoBuf.DEF_ONEOFS, ProtoBuf.DEF_ONEOF_NAMES)
        end
        __meta_Identity[]
    end
end

export Identity


text:
"""
    PDDL.Sets

Extends PDDL with set-valued fluents. Set members must be PDDL objects.
Register by calling `PDDL.Sets.register!`. Attach to a specific `domain`
by calling `PDDL.Sets.attach!(domain)`.
"""
module Sets

using ..PDDL
import ..PDDL: defaultval, valterm

construct_set(xs::Symbol...) = Set{Symbol}(xs)
empty_set() = Set{Symbol}()
cardinality(s::Set) = length(s)
member(s::Set, x) = in(x, s)
subset(x::Set, y::Set) = issubset(x, y)
union(x::Set, y::Set) = Base.union(x, y)
intersect(x::Set, y::Set) = Base.intersect(x, y)
difference(x::Set, y::Set) = setdiff(x, y)
add_element(s::Set, x) = push!(copy(s), x)
rem_element(s::Set, x) = pop!(copy(s), x)

defaultval(::Val{:set}) = Set{Symbol}()

valterm(s::Set) = isempty(s) ? Const(Symbol("(empty-set)")) :
    Compound(Symbol("construct-set"), valterm.(collect(s)))

const DATATYPES = Dict("set" => Set{Symbol})

const PREDICATES = Dict(
    "member" => member,
    "subset" => subset
)

const FUNCTIONS = Dict(
    "construct-set" => construct_set,
    "empty-set" => empty_set,
    "cardinality" => cardinality,
    "union" => union,
    "intersect" => intersect,
    "difference" => difference,
    "add-element" => add_element,
    "rem-element" => rem_element
)

function register!()
    for (name, ty) in DATATYPES
        PDDL.register!(:datatype, name, ty)
    end
    for (name, f) in PREDICATES
        PDDL.register!(:predicate, name, f)
    end
    for (name, f) in FUNCTIONS
        PDDL.register!(:function, name, f)
    end
    return nothing
end

function deregister!()
    for (name, ty) in DATATYPES
        PDDL.deregister!(:datatype, name)
    end
    for (name, f) in PREDICATES
        PDDL.deregister!(:predicate, name)
    end
    for (name, f) in FUNCTIONS
        PDDL.deregister!(:function, name)
    end
    return nothing
end

function attach!(domain::GenericDomain)
    for (name, ty) in DATATYPES
        PDDL.attach!(domain, :datatype, name, ty)
    end
    for (name, f) in PREDICATES
        PDDL.attach!(domain, :function, name, f)
    end
    for (name, f) in FUNCTIONS
        PDDL.attach!(domain, :function, name, f)
    end
    return nothing
end

end


text:
# This file was generated, do not modify it. # hide
evaluate!(knn, resampling=Holdout(fraction_train=0.7),
          measure=rms) |> pprint


text:
# Autogenerated wrapper script for PCL_jll for i686-w64-mingw32-cxx03
export libpcl_common, libpcl_features, libpcl_filters, libpcl_io, libpcl_io_ply, libpcl_kdtree, libpcl_keypoints, libpcl_ml, libpcl_octree, libpcl_recognition, libpcl_registration, libpcl_sample_consensus, libpcl_search, libpcl_segmentation, libpcl_stereo, libpcl_surface, libpcl_tracking, pcl_add_gaussian_noise, pcl_boundary_estimation, pcl_cluster_extraction, pcl_compute_cloud_error, pcl_compute_hausdorff, pcl_concatenate_points_pcd, pcl_convert_pcd_ascii_binary, pcl_crf_segmentation, pcl_demean_cloud, pcl_elch, pcl_extract_feature, pcl_fast_bilateral_filter, pcl_fpfh_estimation, pcl_generate, pcl_gp3_surface, pcl_grid_min, pcl_hdl_grabber, pcl_icp, pcl_icp2d, pcl_linemod_detection, pcl_local_max, pcl_lum, pcl_marching_cubes_reconstruction, pcl_match_linemod_template, pcl_mls_smoothing, pcl_morph, pcl_ndt2d, pcl_ndt3d, pcl_normal_estimation, pcl_outlier_removal, pcl_passthrough_filter, pcl_pcd2ply, pcl_pcd2vtk, pcl_pcd_change_viewpoint, pcl_pcd_convert_NaN_nan, pcl_pcd_introduce_nan, pcl_pclzf2pcd, pcl_plane_projection, pcl_ply2obj, pcl_ply2pcd, pcl_ply2ply, pcl_ply2raw, pcl_plyheader, pcl_poisson_reconstruction, pcl_progressive_morphological_filter, pcl_radius_filter, pcl_sac_segmentation_plane, pcl_spin_estimation, pcl_train_linemod_template, pcl_train_unary_classifier, pcl_transform_from_viewpoint, pcl_transform_point_cloud, pcl_unary_classifier_segment, pcl_uniform_sampling, pcl_vfh_estimation, pcl_voxel_grid, pcl_xyz2pcd

using CompilerSupportLibraries_jll
using FLANN_jll
using boost_jll
using Eigen_jll
JLLWrappers.@generate_wrapper_header("PCL")
JLLWrappers.@declare_library_product(libpcl_common, "libpcl_common.dll")
JLLWrappers.@declare_library_product(libpcl_features, "libpcl_features.dll")
JLLWrappers.@declare_library_product(libpcl_filters, "libpcl_filters.dll")
JLLWrappers.@declare_library_product(libpcl_io, "libpcl_io.dll")
JLLWrappers.@declare_library_product(libpcl_io_ply, "libpcl_io_ply.dll")
JLLWrappers.@declare_library_product(libpcl_kdtree, "libpcl_kdtree.dll")
JLLWrappers.@declare_library_product(libpcl_keypoints, "libpcl_keypoints.dll")
JLLWrappers.@declare_library_product(libpcl_ml, "libpcl_ml.dll")
JLLWrappers.@declare_library_product(libpcl_octree, "libpcl_octree.dll")
JLLWrappers.@declare_library_product(libpcl_recognition, "libpcl_recognition.dll")
JLLWrappers.@declare_library_product(libpcl_registration, "libpcl_registration.dll")
JLLWrappers.@declare_library_product(libpcl_sample_consensus, "libpcl_sample_consensus.dll")
JLLWrappers.@declare_library_product(libpcl_search, "libpcl_search.dll")
JLLWrappers.@declare_library_product(libpcl_segmentation, "libpcl_segmentation.dll")
JLLWrappers.@declare_library_product(libpcl_stereo, "libpcl_stereo.dll")
JLLWrappers.@declare_library_product(libpcl_surface, "libpcl_surface.dll")
JLLWrappers.@declare_library_product(libpcl_tracking, "libpcl_tracking.dll")
JLLWrappers.@declare_executable_product(pcl_add_gaussian_noise)
JLLWrappers.@declare_executable_product(pcl_boundary_estimation)
JLLWrappers.@declare_executable_product(pcl_cluster_extraction)
JLLWrappers.@declare_executable_product(pcl_compute_cloud_error)
JLLWrappers.@declare_executable_product(pcl_compute_hausdorff)
JLLWrappers.@declare_executable_product(pcl_concatenate_points_pcd)
JLLWrappers.@declare_executable_product(pcl_convert_pcd_ascii_binary)
JLLWrappers.@declare_executable_product(pcl_crf_segmentation)
JLLWrappers.@declare_executable_product(pcl_demean_cloud)
JLLWrappers.@declare_executable_product(pcl_elch)
JLLWrappers.@declare_executable_product(pcl_extract_feature)
JLLWrappers.@declare_executable_product(pcl_fast_bilateral_filter)
JLLWrappers.@declare_executable_product(pcl_fpfh_estimation)
JLLWrappers.@declare_executable_product(pcl_generate)
JLLWrappers.@declare_executable_product(pcl_gp3_surface)
JLLWrappers.@declare_executable_product(pcl_grid_min)
JLLWrappers.@declare_executable_product(pcl_hdl_grabber)
JLLWrappers.@declare_executable_product(pcl_icp)
JLLWrappers.@declare_executable_product(pcl_icp2d)
JLLWrappers.@declare_executable_product(pcl_linemod_detection)
JLLWrappers.@declare_executable_product(pcl_local_max)
JLLWrappers.@declare_executable_product(pcl_lum)
JLLWrappers.@declare_executable_product(pcl_marching_cubes_reconstruction)
JLLWrappers.@declare_executable_product(pcl_match_linemod_template)
JLLWrappers.@declare_executable_product(pcl_mls_smoothing)
JLLWrappers.@declare_executable_product(pcl_morph)
JLLWrappers.@declare_executable_product(pcl_ndt2d)
JLLWrappers.@declare_executable_product(pcl_ndt3d)
JLLWrappers.@declare_executable_product(pcl_normal_estimation)
JLLWrappers.@declare_executable_product(pcl_outlier_removal)
JLLWrappers.@declare_executable_product(pcl_passthrough_filter)
JLLWrappers.@declare_executable_product(pcl_pcd2ply)
JLLWrappers.@declare_executable_product(pcl_pcd2vtk)
JLLWrappers.@declare_executable_product(pcl_pcd_change_viewpoint)
JLLWrappers.@declare_executable_product(pcl_pcd_convert_NaN_nan)
JLLWrappers.@declare_executable_product(pcl_pcd_introduce_nan)
JLLWrappers.@declare_executable_product(pcl_pclzf2pcd)
JLLWrappers.@declare_executable_product(pcl_plane_projection)
JLLWrappers.@declare_executable_product(pcl_ply2obj)
JLLWrappers.@declare_executable_product(pcl_ply2pcd)
JLLWrappers.@declare_executable_product(pcl_ply2ply)
JLLWrappers.@declare_executable_product(pcl_ply2raw)
JLLWrappers.@declare_executable_product(pcl_plyheader)
JLLWrappers.@declare_executable_product(pcl_poisson_reconstruction)
JLLWrappers.@declare_executable_product(pcl_progressive_morphological_filter)
JLLWrappers.@declare_executable_product(pcl_radius_filter)
JLLWrappers.@declare_executable_product(pcl_sac_segmentation_plane)
JLLWrappers.@declare_executable_product(pcl_spin_estimation)
JLLWrappers.@declare_executable_product(pcl_train_linemod_template)
JLLWrappers.@declare_executable_product(pcl_train_unary_classifier)
JLLWrappers.@declare_executable_product(pcl_transform_from_viewpoint)
JLLWrappers.@declare_executable_product(pcl_transform_point_cloud)
JLLWrappers.@declare_executable_product(pcl_unary_classifier_segment)
JLLWrappers.@declare_executable_product(pcl_uniform_sampling)
JLLWrappers.@declare_executable_product(pcl_vfh_estimation)
JLLWrappers.@declare_executable_product(pcl_voxel_grid)
JLLWrappers.@declare_executable_product(pcl_xyz2pcd)
function __init__()
    JLLWrappers.@generate_init_header(CompilerSupportLibraries_jll, FLANN_jll, boost_jll, Eigen_jll)
    JLLWrappers.@init_library_product(
        libpcl_common,
        "bin\\libpcl_common.dll",
        RTLD_LAZY | RTLD_DEEPBIND,
    )

    JLLWrappers.@init_library_product(
        libpcl_features,
        "bin\\libpcl_features.dll",
        RTLD_LAZY | RTLD_DEEPBIND,
    )

    JLLWrappers.@init_library_product(
        libpcl_filters,
        "bin\\libpcl_filters.dll",
        RTLD_LAZY | RTLD_DEEPBIND,
    )

    JLLWrappers.@init_library_product(
        libpcl_io,
        "bin\\libpcl_io.dll",
        RTLD_LAZY | RTLD_DEEPBIND,
    )

    JLLWrappers.@init_library_product(
        libpcl_io_ply,
        "bin\\libpcl_io_ply.dll",
        RTLD_LAZY | RTLD_DEEPBIND,
    )

    JLLWrappers.@init_library_product(
        libpcl_kdtree,
        "bin\\libpcl_kdtree.dll",
        RTLD_LAZY | RTLD_DEEPBIND,
    )

    JLLWrappers.@init_library_product(
        libpcl_keypoints,
        "bin\\libpcl_keypoints.dll",
        RTLD_LAZY | RTLD_DEEPBIND,
    )

    JLLWrappers.@init_library_product(
        libpcl_ml,
        "bin\\libpcl_ml.dll",
        RTLD_LAZY | RTLD_DEEPBIND,
    )

    JLLWrappers.@init_library_product(
        libpcl_octree,
        "bin\\libpcl_octree.dll",
        RTLD_LAZY | RTLD_DEEPBIND,
    )

    JLLWrappers.@init_library_product(
        libpcl_recognition,
        "bin\\libpcl_recognition.dll",
        RTLD_LAZY | RTLD_DEEPBIND,
    )

    JLLWrappers.@init_library_product(
        libpcl_registration,
        "bin\\libpcl_registration.dll",
        RTLD_LAZY | RTLD_DEEPBIND,
    )

    JLLWrappers.@init_library_product(
        libpcl_sample_consensus,
        "bin\\libpcl_sample_consensus.dll",
        RTLD_LAZY | RTLD_DEEPBIND,
    )

    JLLWrappers.@init_library_product(
        libpcl_search,
        "bin\\libpcl_search.dll",
        RTLD_LAZY | RTLD_DEEPBIND,
    )

    JLLWrappers.@init_library_product(
        libpcl_segmentation,
        "bin\\libpcl_segmentation.dll",
        RTLD_LAZY | RTLD_DEEPBIND,
    )

    JLLWrappers.@init_library_product(
        libpcl_stereo,
        "bin\\libpcl_stereo.dll",
        RTLD_LAZY | RTLD_DEEPBIND,
    )

    JLLWrappers.@init_library_product(
        libpcl_surface,
        "bin\\libpcl_surface.dll",
        RTLD_LAZY | RTLD_DEEPBIND,
    )

    JLLWrappers.@init_library_product(
        libpcl_tracking,
        "bin\\libpcl_tracking.dll",
        RTLD_LAZY | RTLD_DEEPBIND,
    )

    JLLWrappers.@init_executable_product(
        pcl_add_gaussian_noise,
        "bin\\pcl_add_gaussian_noise.exe",
    )

    JLLWrappers.@init_executable_product(
        pcl_boundary_estimation,
        "bin\\pcl_boundary_estimation.exe",
    )

    JLLWrappers.@init_executable_product(
        pcl_cluster_extraction,
        "bin\\pcl_cluster_extraction.exe",
    )

    JLLWrappers.@init_executable_product(
        pcl_compute_cloud_error,
        "bin\\pcl_compute_cloud_error.exe",
    )

    JLLWrappers.@init_executable_product(
        pcl_compute_hausdorff,
        "bin\\pcl_compute_hausdorff.exe",
    )

    JLLWrappers.@init_executable_product(
        pcl_concatenate_points_pcd,
        "bin\\pcl_concatenate_points_pcd.exe",
    )

    JLLWrappers.@init_executable_product(
        pcl_convert_pcd_ascii_binary,
        "bin\\pcl_convert_pcd_ascii_binary.exe",
    )

    JLLWrappers.@init_executable_product(
        pcl_crf_segmentation,
        "bin\\pcl_crf_segmentation.exe",
    )

    JLLWrappers.@init_executable_product(
        pcl_demean_cloud,
        "bin\\pcl_demean_cloud.exe",
    )

    JLLWrappers.@init_executable_product(
        pcl_elch,
        "bin\\pcl_elch.exe",
    )

    JLLWrappers.@init_executable_product(
        pcl_extract_feature,
        "bin\\pcl_extract_feature.exe",
    )

    JLLWrappers.@init_executable_product(
        pcl_fast_bilateral_filter,
        "bin\\pcl_fast_bilateral_filter.exe",
    )

    JLLWrappers.@init_executable_product(
        pcl_fpfh_estimation,
        "bin\\pcl_fpfh_estimation.exe",
    )

    JLLWrappers.@init_executable_product(
        pcl_generate,
        "bin\\pcl_generate.exe",
    )

    JLLWrappers.@init_executable_product(
        pcl_gp3_surface,
        "bin\\pcl_gp3_surface.exe",
    )

    JLLWrappers.@init_executable_product(
        pcl_grid_min,
        "bin\\pcl_grid_min.exe",
    )

    JLLWrappers.@init_executable_product(
        pcl_hdl_grabber,
        "bin\\pcl_hdl_grabber.exe",
    )

    JLLWrappers.@init_executable_product(
        pcl_icp,
        "bin\\pcl_icp.exe",
    )

    JLLWrappers.@init_executable_product(
        pcl_icp2d,
        "bin\\pcl_icp2d.exe",
    )

    JLLWrappers.@init_executable_product(
        pcl_linemod_detection,
        "bin\\pcl_linemod_detection.exe",
    )

    JLLWrappers.@init_executable_product(
        pcl_local_max,
        "bin\\pcl_local_max.exe",
    )

    JLLWrappers.@init_executable_product(
        pcl_lum,
        "bin\\pcl_lum.exe",
    )

    JLLWrappers.@init_executable_product(
        pcl_marching_cubes_reconstruction,
        "bin\\pcl_marching_cubes_reconstruction.exe",
    )

    JLLWrappers.@init_executable_product(
        pcl_match_linemod_template,
        "bin\\pcl_match_linemod_template.exe",
    )

    JLLWrappers.@init_executable_product(
        pcl_mls_smoothing,
        "bin\\pcl_mls_smoothing.exe",
    )

    JLLWrappers.@init_executable_product(
        pcl_morph,
        "bin\\pcl_morph.exe",
    )

    JLLWrappers.@init_executable_product(
        pcl_ndt2d,
        "bin\\pcl_ndt2d.exe",
    )

    JLLWrappers.@init_executable_product(
        pcl_ndt3d,
        "bin\\pcl_ndt3d.exe",
    )

    JLLWrappers.@init_executable_product(
        pcl_normal_estimation,
        "bin\\pcl_normal_estimation.exe",
    )

    JLLWrappers.@init_executable_product(
        pcl_outlier_removal,
        "bin\\pcl_outlier_removal.exe",
    )

    JLLWrappers.@init_executable_product(
        pcl_passthrough_filter,
        "bin\\pcl_passthrough_filter.exe",
    )

    JLLWrappers.@init_executable_product(
        pcl_pcd2ply,
        "bin\\pcl_pcd2ply.exe",
    )

    JLLWrappers.@init_executable_product(
        pcl_pcd2vtk,
        "bin\\pcl_pcd2vtk.exe",
    )

    JLLWrappers.@init_executable_product(
        pcl_pcd_change_viewpoint,
        "bin\\pcl_pcd_change_viewpoint.exe",
    )

    JLLWrappers.@init_executable_product(
        pcl_pcd_convert_NaN_nan,
        "bin\\pcl_pcd_convert_NaN_nan.exe",
    )

    JLLWrappers.@init_executable_product(
        pcl_pcd_introduce_nan,
        "bin\\pcl_pcd_introduce_nan.exe",
    )

    JLLWrappers.@init_executable_product(
        pcl_pclzf2pcd,
        "bin\\pcl_pclzf2pcd.exe",
    )

    JLLWrappers.@init_executable_product(
        pcl_plane_projection,
        "bin\\pcl_plane_projection.exe",
    )

    JLLWrappers.@init_executable_product(
        pcl_ply2obj,
        "bin\\pcl_ply2obj.exe",
    )

    JLLWrappers.@init_executable_product(
        pcl_ply2pcd,
        "bin\\pcl_ply2pcd.exe",
    )

    JLLWrappers.@init_executable_product(
        pcl_ply2ply,
        "bin\\pcl_ply2ply.exe",
    )

    JLLWrappers.@init_executable_product(
        pcl_ply2raw,
        "bin\\pcl_ply2raw.exe",
    )

    JLLWrappers.@init_executable_product(
        pcl_plyheader,
        "bin\\pcl_plyheader.exe",
    )

    JLLWrappers.@init_executable_product(
        pcl_poisson_reconstruction,
        "bin\\pcl_poisson_reconstruction.exe",
    )

    JLLWrappers.@init_executable_product(
        pcl_progressive_morphological_filter,
        "bin\\pcl_progressive_morphological_filter.exe",
    )

    JLLWrappers.@init_executable_product(
        pcl_radius_filter,
        "bin\\pcl_radius_filter.exe",
    )

    JLLWrappers.@init_executable_product(
        pcl_sac_segmentation_plane,
        "bin\\pcl_sac_segmentation_plane.exe",
    )

    JLLWrappers.@init_executable_product(
        pcl_spin_estimation,
        "bin\\pcl_spin_estimation.exe",
    )

    JLLWrappers.@init_executable_product(
        pcl_train_linemod_template,
        "bin\\pcl_train_linemod_template.exe",
    )

    JLLWrappers.@init_executable_product(
        pcl_train_unary_classifier,
        "bin\\pcl_train_unary_classifier.exe",
    )

    JLLWrappers.@init_executable_product(
        pcl_transform_from_viewpoint,
        "bin\\pcl_transform_from_viewpoint.exe",
    )

    JLLWrappers.@init_executable_product(
        pcl_transform_point_cloud,
        "bin\\pcl_transform_point_cloud.exe",
    )

    JLLWrappers.@init_executable_product(
        pcl_unary_classifier_segment,
        "bin\\pcl_unary_classifier_segment.exe",
    )

    JLLWrappers.@init_executable_product(
        pcl_uniform_sampling,
        "bin\\pcl_uniform_sampling.exe",
    )

    JLLWrappers.@init_executable_product(
        pcl_vfh_estimation,
        "bin\\pcl_vfh_estimation.exe",
    )

    JLLWrappers.@init_executable_product(
        pcl_voxel_grid,
        "bin\\pcl_voxel_grid.exe",
    )

    JLLWrappers.@init_executable_product(
        pcl_xyz2pcd,
        "bin\\pcl_xyz2pcd.exe",
    )

    JLLWrappers.@generate_init_footer()
end  # __init__()


text:
using Scallops
using Test


text:
# This file is a part of Julia. License is MIT: https://julialang.org/license

"""
    SHA

The SHA module provides hashing functionality for SHA1, SHA2 and SHA3 algorithms.

They are implemented as both pure functions for hashing single pieces of data,
or a stateful context which can be updated with the `update!` function and
finalized with `digest!`.

```julia-repl
julia> sha1(b"some data")
20-element Vector{UInt8}:
 0xba
 0xf3
    ⋮
 0xe3
 0x56

julia> ctx = SHA1_CTX()
SHA1 hash state

julia> update!(ctx, b"some data")
0x0000000000000009

julia> digest!(ctx)
20-element Vector{UInt8}:
 0xba
 0xf3
    ⋮
 0xe3
 0x56
"""
module SHA

# Export convenience functions, context types, update!() and digest!() functions
export sha1, SHA1_CTX, update!, digest!
export sha224, sha256, sha384, sha512
export sha2_224, sha2_256, sha2_384, sha2_512
export sha3_224, sha3_256, sha3_384, sha3_512
export SHA224_CTX, SHA256_CTX, SHA384_CTX, SHA512_CTX
export SHA2_224_CTX, SHA2_256_CTX, SHA2_384_CTX, SHA2_512_CTX
export SHA3_224_CTX, SHA3_256_CTX, SHA3_384_CTX, SHA3_512_CTX
export HMAC_CTX, hmac_sha1
export hmac_sha224, hmac_sha256, hmac_sha384, hmac_sha512
export hmac_sha2_224, hmac_sha2_256, hmac_sha2_384, hmac_sha2_512
export hmac_sha3_224, hmac_sha3_256, hmac_sha3_384, hmac_sha3_512

# data to be hashed:
const AbstractBytes = Union{AbstractVector{UInt8},NTuple{N,UInt8} where N}

include("constants.jl")
include("types.jl")
include("base_functions.jl")
include("sha1.jl")
include("sha2.jl")
include("sha3.jl")
include("common.jl")
include("hmac.jl")

# Create data types and convenience functions for each hash implemented
for (f, ctx) in [(:sha1, :SHA1_CTX),
                 (:sha224, :SHA224_CTX),
                 (:sha256, :SHA256_CTX),
                 (:sha384, :SHA384_CTX),
                 (:sha512, :SHA512_CTX),
                 (:sha2_224, :SHA2_224_CTX),
                 (:sha2_256, :SHA2_256_CTX),
                 (:sha2_384, :SHA2_384_CTX),
                 (:sha2_512, :SHA2_512_CTX),
                 (:sha3_224, :SHA3_224_CTX),
                 (:sha3_256, :SHA3_256_CTX),
                 (:sha3_384, :SHA3_384_CTX),
                 (:sha3_512, :SHA3_512_CTX),]
    g = Symbol(:hmac_, f)

    @eval begin
        # Our basic function is to process arrays of bytes
        """
            $($f)(data)

        Hash data using the $($f) algorithm and return the resulting digest.
        See also [`$($ctx)`](@ref).
        """
        function $f(data::AbstractBytes)
            ctx = $ctx()
            update!(ctx, data)
            return digest!(ctx)

        """
            $($g)(key, data)

        Hash data using the $($f) algorithm using the passed key
        See also [`HMAC_CTX`](@ref).
        """
        end
        function $g(key::Vector{UInt8}, data::AbstractBytes)
            ctx = HMAC_CTX($ctx(), key)
            update!(ctx, data)
            return digest!(ctx)
        end

        # AbstractStrings are a pretty handy thing to be able to crunch through
        $f(str::AbstractString) = $f(String(str)) # always crunch UTF-8 repr
        $f(str::String) = $f(codeunits(str))
        $g(key::Vector{UInt8}, str::AbstractString) = $g(key, String(str))
        $g(key::Vector{UInt8}, str::String) = $g(key, codeunits(str))

        """
            $($f)(io::IO)

        Hash data from io using $($f) algorithm from io.
        """
        function $f(io::IO, chunk_size=4*1024)
            ctx = $ctx()
            buff = Vector{UInt8}(undef, chunk_size)
            while !eof(io)
                num_read = readbytes!(io, buff)
                update!(ctx, buff, num_read)
            end
            return digest!(ctx)
        end
        function $g(key::Vector{UInt8}, io::IO, chunk_size=4*1024)
            ctx = HMAC_CTX($ctx(), key)
            buff = Vector{UInt8}(chunk_size)
            while !eof(io)
                num_read = readbytes!(io, buff)
                update!(ctx, buff, num_read)
            end
            return digest!(ctx)
        end
    end
end

end #module SHA

max_stars_repo_name: vanillajonathan/julia

max_issues_repo_name: vanillajonathan/julia

max_forks_repo_name: vanillajonathan/julia


text:
"""
```julia
equation_dependencies(sys::AbstractSystem; variables=states(sys))
```

Given an `AbstractSystem` calculate for each equation the variables it depends on.

Notes:
- Variables that are not in `variables` are filtered out.
- `get_variables!` is used to determine the variables within a given equation.
- returns a `Vector{Vector{Variable}}()` mapping the index of an equation to the `variables` it depends on.

Example:
```julia
using ModelingToolkit
@parameters β γ κ η t
@variables S(t) I(t) R(t)

# use a reaction system to easily generate ODE and jump systems
rxs = [Reaction(β, [S,I], [I], [1,1], [2]),
       Reaction(γ, [I], [R]),
       Reaction(κ+η, [R], [S])]
rs = ReactionSystem(rxs, t, [S,I,R], [β,γ,κ,η])

# ODEs:
odesys = convert(ODESystem, rs)

# dependency of each ODE on state variables
equation_dependencies(odesys)

# dependency of each ODE on parameters
equation_dependencies(odesys, variables=parameters(odesys))

# Jumps
jumpsys = convert(JumpSystem, rs)

# dependency of each jump rate function on state variables
equation_dependencies(jumpsys)

# dependency of each jump rate function on parameters
equation_dependencies(jumpsys, variables=parameters(jumpsys))
```
"""
function equation_dependencies(sys::AbstractSystem; variables=states(sys))
    eqs  = equations(sys)
    deps = Set()
    depeqs_to_vars = Vector{Vector}(undef,length(eqs))

    for (i,eq) in enumerate(eqs)
        get_variables!(deps, eq, variables)
        depeqs_to_vars[i] = [value(v) for v in deps]
        empty!(deps)
    end

    depeqs_to_vars
end

"""
```julia
asgraph(eqdeps, vtois)
```

Convert a collection of equation dependencies, for example as returned by
`equation_dependencies`, to a [`BipartiteGraph`](@ref).

Notes:
- `vtois` should provide a `Dict` like mapping from each `Variable` dependency in
  `eqdeps` to the integer idx of the variable to use in the graph.

Example:
Continuing the example started in [`equation_dependencies`](@ref)
```julia
digr = asgraph(equation_dependencies(odesys), Dict(s => i for (i,s) in enumerate(states(odesys))))
```
"""
function asgraph(eqdeps, vtois)
    fadjlist = Vector{Vector{Int}}(undef, length(eqdeps))
    for (i,dep) in enumerate(eqdeps)
        fadjlist[i] = sort!([vtois[var] for var in dep])
    end

    badjlist = [Vector{Int}() for i = 1:length(vtois)]
    ne = 0
    for (eqidx,vidxs) in enumerate(fadjlist)
        foreach(vidx -> push!(badjlist[vidx], eqidx), vidxs)
        ne += length(vidxs)
    end

    BipartiteGraph(ne, fadjlist, badjlist)
end

# could be made to directly generate graph and save memory
"""
```julia
asgraph(sys::AbstractSystem; variables=states(sys),
                                      variablestoids=Dict(convert(Variable, v) => i for (i,v) in enumerate(variables)))
```

Convert an `AbstractSystem` to a [`BipartiteGraph`](@ref) mapping the index of equations
to the indices of variables they depend on.

Notes:
- Defaults for kwargs creating a mapping from `equations(sys)` to `states(sys)`
  they depend on.
- `variables` should provide the list of variables to use for generating
  the dependency graph.
- `variablestoids` should provide `Dict` like mapping from a `Variable` to its
  `Int` index within `variables`.

Example:
Continuing the example started in [`equation_dependencies`](@ref)
```julia
digr = asgraph(odesys)
```
"""
function asgraph(sys::AbstractSystem; variables=states(sys),
                                      variablestoids=Dict(v => i for (i,v) in enumerate(variables)))
    asgraph(equation_dependencies(sys, variables=variables), variablestoids)
end

"""
```julia
variable_dependencies(sys::AbstractSystem; variables=states(sys), variablestoids=nothing)
```

For each variable determine the equations that modify it and return as a [`BipartiteGraph`](@ref).

Notes:
- Dependencies are returned as a [`BipartiteGraph`](@ref) mapping variable
  indices to the indices of equations that modify them.
- `variables` denotes the list of variables to determine dependencies for.
- `variablestoids` denotes a `Dict` mapping `Variable`s to their `Int` index in `variables`.

Example:
Continuing the example of [`equation_dependencies`](@ref)
```julia
variable_dependencies(odesys)
```
"""
function variable_dependencies(sys::AbstractSystem; variables=states(sys), variablestoids=nothing)
    eqs   = equations(sys)
    vtois = isnothing(variablestoids) ? Dict(v => i for (i,v) in enumerate(variables)) : variablestoids

    deps = Set()
    badjlist = Vector{Vector{Int}}(undef, length(eqs))
    for (eidx,eq) in enumerate(eqs)
        modified_states!(deps, eq, variables)
        badjlist[eidx] = sort!([vtois[var] for var in deps])
        empty!(deps)
    end

    fadjlist = [Vector{Int}() for i = 1:length(variables)]
    ne = 0
    for (eqidx,vidxs) in enumerate(badjlist)
        foreach(vidx -> push!(fadjlist[vidx], eqidx), vidxs)
        ne += length(vidxs)
    end

    BipartiteGraph(ne, fadjlist, badjlist)
end

"""
```julia
asdigraph(g::BipartiteGraph, sys::AbstractSystem; variables = states(sys), equationsfirst = true)
```

Convert a [`BipartiteGraph`](@ref) to a `LightGraph.SimpleDiGraph`.

Notes:
- The resulting `SimpleDiGraph` unifies the two sets of vertices (equations
  and then states in the case it comes from [`asgraph`](@ref)), producing one
  ordered set of integer vertices (`SimpleDiGraph` does not support two distinct
  collections of vertices so they must be merged).
- `variables` gives the variables that `g` is associated with (usually the
  `states` of a system).
- `equationsfirst` (default is `true`) gives whether the [`BipartiteGraph`](@ref)
  gives a mapping from equations to variables they depend on (`true`), as calculated
  by [`asgraph`](@ref), or whether it gives a mapping from variables to the equations
  that modify them, as calculated by [`variable_dependencies`](@ref).

Example:
Continuing the example in [`asgraph`](@ref)
```julia
dg = asdigraph(digr)
```
"""
function asdigraph(g::BipartiteGraph, sys::AbstractSystem; variables = states(sys), equationsfirst = true)
    neqs     = length(equations(sys))
    nvars    = length(variables)
    fadjlist = deepcopy(g.fadjlist)
    badjlist = deepcopy(g.badjlist)

    # offset is for determining indices for the second set of vertices
    offset = equationsfirst ? neqs : nvars
    for i = 1:offset
        fadjlist[i] .+= offset
    end

    # add empty rows for vertices without connections
    append!(fadjlist, [Vector{Int}() for i=1:(equationsfirst ? nvars : neqs)])
    prepend!(badjlist, [Vector{Int}() for i=1:(equationsfirst ? neqs : nvars)])

    SimpleDiGraph(g.ne, fadjlist, badjlist)
end

"""
```julia
eqeq_dependencies(eqdeps::BipartiteGraph{T}, vardeps::BipartiteGraph{T}) where {T <: Integer}
```

Calculate a `LightGraph.SimpleDiGraph` that maps each equation to equations they depend on.

Notes:
- The `fadjlist` of the `SimpleDiGraph` maps from an equation to the equations that
  modify variables it depends on.
- The `badjlist` of the `SimpleDiGraph` maps from an equation to equations that
  depend on variables it modifies.

Example:
Continuing the example of `equation_dependencies`
```julia
eqeqdep = eqeq_dependencies(asgraph(odesys), variable_dependencies(odesys))
```
"""
function eqeq_dependencies(eqdeps::BipartiteGraph{T}, vardeps::BipartiteGraph{T}) where {T <: Integer}
    g = SimpleDiGraph{T}(length(eqdeps.fadjlist))

    for (eqidx,sidxs) in enumerate(vardeps.badjlist)
        # states modified by eqidx
        for sidx in sidxs
            # equations depending on sidx
            foreach(v -> add_edge!(g, eqidx, v), eqdeps.badjlist[sidx])
        end
    end

    g
end

"""
```julia
varvar_dependencies(eqdeps::BipartiteGraph{T}, vardeps::BipartiteGraph{T}) where {T <: Integer} = eqeq_dependencies(vardeps, eqdeps)
```

Calculate a `LightGraph.SimpleDiGraph` that maps each variable to variables they depend on.

Notes:
- The `fadjlist` of the `SimpleDiGraph` maps from a variable to the variables that
  depend on it.
- The `badjlist` of the `SimpleDiGraph` maps from a variable to variables on which
  it depends.

Example:
Continuing the example of `equation_dependencies`
```julia
varvardep = varvar_dependencies(asgraph(odesys), variable_dependencies(odesys))
```
"""
varvar_dependencies(eqdeps::BipartiteGraph{T}, vardeps::BipartiteGraph{T}) where {T <: Integer} = eqeq_dependencies(vardeps, eqdeps)


text:
# -*- coding: utf-8 -*-
# ---
# jupyter:
#   jupytext:
#     formats: ipynb,jl:hydrogen
#     text_representation:
#       extension: .jl
#       format_name: hydrogen
#       format_version: '1.3'
#       jupytext_version: 1.10.3
#   kernelspec:
#     display_name: Julia 1.6.3
#     language: julia
#     name: julia-1.6
# ---

# %% [markdown]
# ## デフォルトで定義されるコンストラクタ

# %%
struct Kuma{T}
    p::Tuple{T, T}
end

# %% [markdown]
# これだけで、
#
# * `Kuma(p::Tuple{T, T}) where T`
# * `Kuma{T}(p) where T`
#
# が定義される。内部コンストラクタを定義するとこれらは定義されなくなる。
#
# 多くの場合に自動的に定義されるデフォルトのコンストラクタで十分である。
#
# 複雑なことをやってくれるコンストラクタは外部コンストラクタで行えばよい。

# %%
methods(Kuma) |> display
methods(Kuma{Int}) |> display

# %% [markdown]
# ## デフォルトの`Kuma{T}(p)`は引数の型変換を自動的にしてくれる。

# %% [markdown]
# `Kuma{T}(p) where T` は `p` の型を自動的に `Tuple{T, T}` 型に変換してくれる。

# %%
x = Kuma{Int}((Float32(2.0), big(3)))

# %%
typeof(x.p)

# %% [markdown]
# ## promotionによる自動型変換に一般化

# %% [markdown]
# `Kuma(p::Tuple{T, U}) where {T, U}` をpromotionによって作成。

# %%
Kuma(p::Tuple{T, U}) where {T, U} = Kuma(promote(p...))

# %%
methods(Kuma)

# %%
y = Kuma((big(2), 3.0))

# %%
typeof(y.p)

# %% [markdown]
# ## `Kuma(x, y)` を定義

# %% [markdown]
# `Kuma(x, y)` を定義。

# %%
Kuma(x, y) = Kuma((x, y))

# %%
methods(Kuma)

# %%
z = Kuma(big(2), 3.0)

# %%
typeof(z.p)

# %% [markdown]
# ## `==` を定義

# %%
y == z

# %%
Base.:(==)(x::Kuma, y::Kuma) = x.p == y.p

# %%
y == z

# %%

max_stars_repo_path: 0024/default constructors.jl

max_stars_repo_name: genkuroki/public

max_issues_repo_path: 0024/default constructors.jl

max_issues_repo_name: genkuroki/public

max_forks_repo_path: 0024/default constructors.jl

max_forks_repo_name: genkuroki/public