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

"""
    associate_entity_to_thing(entity_id, thing_name)
    associate_entity_to_thing(entity_id, thing_name, params::Dict{String,<:Any})

Associates a device with a concrete thing that is in the user's registry. A thing can be
associated with only one device at a time. If you associate a thing with a new device id,
its previous association will be removed.

# Arguments
- `entity_id`: The ID of the device to be associated with the thing. The ID should be in
  the following format.  urn:tdm:REGION/ACCOUNT ID/default:device:DEVICENAME
- `thing_name`: The name of the thing to which the entity is to be associated.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"namespaceVersion"`: The version of the user's namespace. Defaults to the latest version
  of the user's namespace.
"""
associate_entity_to_thing(entityId, thingName; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("AssociateEntityToThing", Dict{String, Any}("entityId"=>entityId, "thingName"=>thingName); aws_config=aws_config)
associate_entity_to_thing(entityId, thingName, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("AssociateEntityToThing", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("entityId"=>entityId, "thingName"=>thingName), params)); aws_config=aws_config)

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

Creates a workflow template. Workflows can be created only in the user's namespace. (The
public namespace contains only entities.) The workflow can contain only entities in the
specified namespace. The workflow is validated against the entities in the latest version
of the user's namespace unless another namespace version is specified in the request.

# Arguments
- `definition`: The workflow DefinitionDocument.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"compatibleNamespaceVersion"`: The namespace version in which the workflow is to be
  created. If no value is specified, the latest version is used by default.
"""
create_flow_template(definition; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("CreateFlowTemplate", Dict{String, Any}("definition"=>definition); aws_config=aws_config)
create_flow_template(definition, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("CreateFlowTemplate", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("definition"=>definition), params)); aws_config=aws_config)

"""
    create_system_instance(definition, target)
    create_system_instance(definition, target, params::Dict{String,<:Any})

Creates a system instance.  This action validates the system instance, prepares the
deployment-related resources. For Greengrass deployments, it updates the Greengrass group
that is specified by the greengrassGroupName parameter. It also adds a file to the S3
bucket specified by the s3BucketName parameter. You need to call DeploySystemInstance after
running this action. For Greengrass deployments, since this action modifies and adds
resources to a Greengrass group and an S3 bucket on the caller's behalf, the calling
identity must have write permissions to both the specified Greengrass group and S3 bucket.
Otherwise, the call will fail with an authorization error. For cloud deployments, this
action requires a flowActionsRoleArn value. This is an IAM role that has permissions to
access AWS services, such as AWS Lambda and AWS IoT, that the flow uses when it executes.
If the definition document doesn't specify a version of the user's namespace, the latest
version will be used by default.

# Arguments
- `definition`:
- `target`: The target type of the deployment. Valid values are GREENGRASS and CLOUD.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"flowActionsRoleArn"`: The ARN of the IAM role that AWS IoT Things Graph will assume
  when it executes the flow. This role must have read and write access to AWS Lambda and AWS
  IoT and any other AWS services that the flow uses when it executes. This value is required
  if the value of the target parameter is CLOUD.
- `"greengrassGroupName"`: The name of the Greengrass group where the system instance will
  be deployed. This value is required if the value of the target parameter is GREENGRASS.
- `"metricsConfiguration"`:
- `"s3BucketName"`: The name of the Amazon Simple Storage Service bucket that will be used
  to store and deploy the system instance's resource file. This value is required if the
  value of the target parameter is GREENGRASS.
- `"tags"`: Metadata, consisting of key-value pairs, that can be used to categorize your
  system instances.
"""
create_system_instance(definition, target; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("CreateSystemInstance", Dict{String, Any}("definition"=>definition, "target"=>target); aws_config=aws_config)
create_system_instance(definition, target, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("CreateSystemInstance", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("definition"=>definition, "target"=>target), params)); aws_config=aws_config)

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

Creates a system. The system is validated against the entities in the latest version of the
user's namespace unless another namespace version is specified in the request.

# Arguments
- `definition`: The DefinitionDocument used to create the system.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"compatibleNamespaceVersion"`: The namespace version in which the system is to be
  created. If no value is specified, the latest version is used by default.
"""
create_system_template(definition; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("CreateSystemTemplate", Dict{String, Any}("definition"=>definition); aws_config=aws_config)
create_system_template(definition, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("CreateSystemTemplate", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("definition"=>definition), params)); aws_config=aws_config)

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

Deletes a workflow. Any new system or deployment that contains this workflow will fail to
update or deploy. Existing deployments that contain the workflow will continue to run
(since they use a snapshot of the workflow taken at the time of deployment).

# Arguments
- `id`: The ID of the workflow to be deleted. The ID should be in the following format.
  urn:tdm:REGION/ACCOUNT ID/default:workflow:WORKFLOWNAME

"""
delete_flow_template(id; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("DeleteFlowTemplate", Dict{String, Any}("id"=>id); aws_config=aws_config)
delete_flow_template(id, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("DeleteFlowTemplate", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("id"=>id), params)); aws_config=aws_config)

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

Deletes the specified namespace. This action deletes all of the entities in the namespace.
Delete the systems and flows that use entities in the namespace before performing this
action.

"""
delete_namespace(; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("DeleteNamespace"; aws_config=aws_config)
delete_namespace(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("DeleteNamespace", params; aws_config=aws_config)

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

Deletes a system instance. Only system instances that have never been deployed, or that
have been undeployed can be deleted. Users can create a new system instance that has the
same ID as a deleted system instance.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"id"`: The ID of the system instance to be deleted.
"""
delete_system_instance(; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("DeleteSystemInstance"; aws_config=aws_config)
delete_system_instance(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("DeleteSystemInstance", params; aws_config=aws_config)

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

Deletes a system. New deployments can't contain the system after its deletion. Existing
deployments that contain the system will continue to work because they use a snapshot of
the system that is taken when it is deployed.

# Arguments
- `id`: The ID of the system to be deleted. The ID should be in the following format.
  urn:tdm:REGION/ACCOUNT ID/default:system:SYSTEMNAME

"""
delete_system_template(id; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("DeleteSystemTemplate", Dict{String, Any}("id"=>id); aws_config=aws_config)
delete_system_template(id, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("DeleteSystemTemplate", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("id"=>id), params)); aws_config=aws_config)

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

 Greengrass and Cloud Deployments  Deploys the system instance to the target specified in
CreateSystemInstance.   Greengrass Deployments  If the system or any workflows and entities
have been updated before this action is called, then the deployment will create a new
Amazon Simple Storage Service resource file and then deploy it. Since this action creates a
Greengrass deployment on the caller's behalf, the calling identity must have write
permissions to the specified Greengrass group. Otherwise, the call will fail with an
authorization error. For information about the artifacts that get added to your Greengrass
core device when you use this API, see AWS IoT Things Graph and AWS IoT Greengrass.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"id"`: The ID of the system instance. This value is returned by the CreateSystemInstance
  action. The ID should be in the following format.  urn:tdm:REGION/ACCOUNT
  ID/default:deployment:DEPLOYMENTNAME
"""
deploy_system_instance(; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("DeploySystemInstance"; aws_config=aws_config)
deploy_system_instance(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("DeploySystemInstance", params; aws_config=aws_config)

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

Deprecates the specified workflow. This action marks the workflow for deletion. Deprecated
flows can't be deployed, but existing deployments will continue to run.

# Arguments
- `id`: The ID of the workflow to be deleted. The ID should be in the following format.
  urn:tdm:REGION/ACCOUNT ID/default:workflow:WORKFLOWNAME

"""
deprecate_flow_template(id; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("DeprecateFlowTemplate", Dict{String, Any}("id"=>id); aws_config=aws_config)
deprecate_flow_template(id, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("DeprecateFlowTemplate", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("id"=>id), params)); aws_config=aws_config)

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

Deprecates the specified system.

# Arguments
- `id`: The ID of the system to delete. The ID should be in the following format.
  urn:tdm:REGION/ACCOUNT ID/default:system:SYSTEMNAME

"""
deprecate_system_template(id; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("DeprecateSystemTemplate", Dict{String, Any}("id"=>id); aws_config=aws_config)
deprecate_system_template(id, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("DeprecateSystemTemplate", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("id"=>id), params)); aws_config=aws_config)

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

Gets the latest version of the user's namespace and the public version that it is tracking.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"namespaceName"`: The name of the user's namespace. Set this to aws to get the public
  namespace.
"""
describe_namespace(; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("DescribeNamespace"; aws_config=aws_config)
describe_namespace(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("DescribeNamespace", params; aws_config=aws_config)

"""
    dissociate_entity_from_thing(entity_type, thing_name)
    dissociate_entity_from_thing(entity_type, thing_name, params::Dict{String,<:Any})

Dissociates a device entity from a concrete thing. The action takes only the type of the
entity that you need to dissociate because only one entity of a particular type can be
associated with a thing.

# Arguments
- `entity_type`: The entity type from which to disassociate the thing.
- `thing_name`: The name of the thing to disassociate.

"""
dissociate_entity_from_thing(entityType, thingName; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("DissociateEntityFromThing", Dict{String, Any}("entityType"=>entityType, "thingName"=>thingName); aws_config=aws_config)
dissociate_entity_from_thing(entityType, thingName, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("DissociateEntityFromThing", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("entityType"=>entityType, "thingName"=>thingName), params)); aws_config=aws_config)

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

Gets definitions of the specified entities. Uses the latest version of the user's namespace
by default. This API returns the following TDM entities.   Properties   States   Events
Actions   Capabilities   Mappings   Devices   Device Models   Services   This action
doesn't return definitions for systems, flows, and deployments.

# Arguments
- `ids`: An array of entity IDs. The IDs should be in the following format.
  urn:tdm:REGION/ACCOUNT ID/default:device:DEVICENAME

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"namespaceVersion"`: The version of the user's namespace. Defaults to the latest version
  of the user's namespace.
"""
get_entities(ids; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("GetEntities", Dict{String, Any}("ids"=>ids); aws_config=aws_config)
get_entities(ids, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("GetEntities", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ids"=>ids), params)); aws_config=aws_config)

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

Gets the latest version of the DefinitionDocument and FlowTemplateSummary for the specified
workflow.

# Arguments
- `id`: The ID of the workflow. The ID should be in the following format.
  urn:tdm:REGION/ACCOUNT ID/default:workflow:WORKFLOWNAME

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"revisionNumber"`: The number of the workflow revision to retrieve.
"""
get_flow_template(id; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("GetFlowTemplate", Dict{String, Any}("id"=>id); aws_config=aws_config)
get_flow_template(id, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("GetFlowTemplate", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("id"=>id), params)); aws_config=aws_config)

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

Gets revisions of the specified workflow. Only the last 100 revisions are stored. If the
workflow has been deprecated, this action will return revisions that occurred before the
deprecation. This action won't work for workflows that have been deleted.

# Arguments
- `id`: The ID of the workflow. The ID should be in the following format.
  urn:tdm:REGION/ACCOUNT ID/default:workflow:WORKFLOWNAME

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"maxResults"`: The maximum number of results to return in the response.
- `"nextToken"`: The string that specifies the next page of results. Use this when you're
  paginating results.
"""
get_flow_template_revisions(id; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("GetFlowTemplateRevisions", Dict{String, Any}("id"=>id); aws_config=aws_config)
get_flow_template_revisions(id, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("GetFlowTemplateRevisions", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("id"=>id), params)); aws_config=aws_config)

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

Gets the status of a namespace deletion task.

"""
get_namespace_deletion_status(; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("GetNamespaceDeletionStatus"; aws_config=aws_config)
get_namespace_deletion_status(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("GetNamespaceDeletionStatus", params; aws_config=aws_config)

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

Gets a system instance.

# Arguments
- `id`: The ID of the system deployment instance. This value is returned by
  CreateSystemInstance. The ID should be in the following format.  urn:tdm:REGION/ACCOUNT
  ID/default:deployment:DEPLOYMENTNAME

"""
get_system_instance(id; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("GetSystemInstance", Dict{String, Any}("id"=>id); aws_config=aws_config)
get_system_instance(id, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("GetSystemInstance", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("id"=>id), params)); aws_config=aws_config)

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

Gets a system.

# Arguments
- `id`: The ID of the system to get. This ID must be in the user's namespace. The ID should
  be in the following format.  urn:tdm:REGION/ACCOUNT ID/default:system:SYSTEMNAME

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"revisionNumber"`: The number that specifies the revision of the system to get.
"""
get_system_template(id; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("GetSystemTemplate", Dict{String, Any}("id"=>id); aws_config=aws_config)
get_system_template(id, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("GetSystemTemplate", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("id"=>id), params)); aws_config=aws_config)

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

Gets revisions made to the specified system template. Only the previous 100 revisions are
stored. If the system has been deprecated, this action will return the revisions that
occurred before its deprecation. This action won't work with systems that have been deleted.

# Arguments
- `id`: The ID of the system template. The ID should be in the following format.
  urn:tdm:REGION/ACCOUNT ID/default:system:SYSTEMNAME

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"maxResults"`: The maximum number of results to return in the response.
- `"nextToken"`: The string that specifies the next page of results. Use this when you're
  paginating results.
"""
get_system_template_revisions(id; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("GetSystemTemplateRevisions", Dict{String, Any}("id"=>id); aws_config=aws_config)
get_system_template_revisions(id, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("GetSystemTemplateRevisions", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("id"=>id), params)); aws_config=aws_config)

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

Gets the status of the specified upload.

# Arguments
- `upload_id`: The ID of the upload. This value is returned by the UploadEntityDefinitions
  action.

"""
get_upload_status(uploadId; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("GetUploadStatus", Dict{String, Any}("uploadId"=>uploadId); aws_config=aws_config)
get_upload_status(uploadId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("GetUploadStatus", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("uploadId"=>uploadId), params)); aws_config=aws_config)

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

Returns a list of objects that contain information about events in a flow execution.

# Arguments
- `flow_execution_id`: The ID of the flow execution.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"maxResults"`: The maximum number of results to return in the response.
- `"nextToken"`: The string that specifies the next page of results. Use this when you're
  paginating results.
"""
list_flow_execution_messages(flowExecutionId; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("ListFlowExecutionMessages", Dict{String, Any}("flowExecutionId"=>flowExecutionId); aws_config=aws_config)
list_flow_execution_messages(flowExecutionId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("ListFlowExecutionMessages", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("flowExecutionId"=>flowExecutionId), params)); aws_config=aws_config)

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

Lists all tags on an AWS IoT Things Graph resource.

# Arguments
- `resource_arn`: The Amazon Resource Name (ARN) of the resource whose tags are to be
  returned.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"maxResults"`: The maximum number of tags to return.
- `"nextToken"`: The token that specifies the next page of results to return.
"""
list_tags_for_resource(resourceArn; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("ListTagsForResource", Dict{String, Any}("resourceArn"=>resourceArn); aws_config=aws_config)
list_tags_for_resource(resourceArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("ListTagsForResource", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("resourceArn"=>resourceArn), params)); aws_config=aws_config)

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

Searches for entities of the specified type. You can search for entities in your namespace
and the public namespace that you're tracking.

# Arguments
- `entity_types`: The entity types for which to search.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"filters"`: Optional filter to apply to the search. Valid filters are NAME NAMESPACE,
  SEMANTIC_TYPE_PATH and REFERENCED_ENTITY_ID. REFERENCED_ENTITY_ID filters on entities that
  are used by the entity in the result set. For example, you can filter on the ID of a
  property that is used in a state. Multiple filters function as OR criteria in the query.
  Multiple values passed inside the filter function as AND criteria.
- `"maxResults"`: The maximum number of results to return in the response.
- `"namespaceVersion"`: The version of the user's namespace. Defaults to the latest version
  of the user's namespace.
- `"nextToken"`: The string that specifies the next page of results. Use this when you're
  paginating results.
"""
search_entities(entityTypes; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("SearchEntities", Dict{String, Any}("entityTypes"=>entityTypes); aws_config=aws_config)
search_entities(entityTypes, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("SearchEntities", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("entityTypes"=>entityTypes), params)); aws_config=aws_config)

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

Searches for AWS IoT Things Graph workflow execution instances.

# Arguments
- `system_instance_id`: The ID of the system instance that contains the flow.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"endTime"`: The date and time of the latest flow execution to return.
- `"flowExecutionId"`: The ID of a flow execution.
- `"maxResults"`: The maximum number of results to return in the response.
- `"nextToken"`: The string that specifies the next page of results. Use this when you're
  paginating results.
- `"startTime"`: The date and time of the earliest flow execution to return.
"""
search_flow_executions(systemInstanceId; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("SearchFlowExecutions", Dict{String, Any}("systemInstanceId"=>systemInstanceId); aws_config=aws_config)
search_flow_executions(systemInstanceId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("SearchFlowExecutions", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("systemInstanceId"=>systemInstanceId), params)); aws_config=aws_config)

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

Searches for summary information about workflows.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"filters"`: An array of objects that limit the result set. The only valid filter is
  DEVICE_MODEL_ID.
- `"maxResults"`: The maximum number of results to return in the response.
- `"nextToken"`: The string that specifies the next page of results. Use this when you're
  paginating results.
"""
search_flow_templates(; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("SearchFlowTemplates"; aws_config=aws_config)
search_flow_templates(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("SearchFlowTemplates", params; aws_config=aws_config)

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

Searches for system instances in the user's account.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"filters"`: Optional filter to apply to the search. Valid filters are
  SYSTEM_TEMPLATE_ID, STATUS, and GREENGRASS_GROUP_NAME. Multiple filters function as OR
  criteria in the query. Multiple values passed inside the filter function as AND criteria.
- `"maxResults"`: The maximum number of results to return in the response.
- `"nextToken"`: The string that specifies the next page of results. Use this when you're
  paginating results.
"""
search_system_instances(; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("SearchSystemInstances"; aws_config=aws_config)
search_system_instances(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("SearchSystemInstances", params; aws_config=aws_config)

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

Searches for summary information about systems in the user's account. You can filter by the
ID of a workflow to return only systems that use the specified workflow.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"filters"`: An array of filters that limit the result set. The only valid filter is
  FLOW_TEMPLATE_ID.
- `"maxResults"`: The maximum number of results to return in the response.
- `"nextToken"`: The string that specifies the next page of results. Use this when you're
  paginating results.
"""
search_system_templates(; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("SearchSystemTemplates"; aws_config=aws_config)
search_system_templates(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("SearchSystemTemplates", params; aws_config=aws_config)

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

Searches for things associated with the specified entity. You can search by both device and
device model. For example, if two different devices, camera1 and camera2, implement the
camera device model, the user can associate thing1 to camera1 and thing2 to camera2.
SearchThings(camera2) will return only thing2, but SearchThings(camera) will return both
thing1 and thing2. This action searches for exact matches and doesn't perform partial text
matching.

# Arguments
- `entity_id`: The ID of the entity to which the things are associated. The IDs should be
  in the following format.  urn:tdm:REGION/ACCOUNT ID/default:device:DEVICENAME

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"maxResults"`: The maximum number of results to return in the response.
- `"namespaceVersion"`: The version of the user's namespace. Defaults to the latest version
  of the user's namespace.
- `"nextToken"`: The string that specifies the next page of results. Use this when you're
  paginating results.
"""
search_things(entityId; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("SearchThings", Dict{String, Any}("entityId"=>entityId); aws_config=aws_config)
search_things(entityId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("SearchThings", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("entityId"=>entityId), params)); aws_config=aws_config)

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

Creates a tag for the specified resource.

# Arguments
- `resource_arn`: The Amazon Resource Name (ARN) of the resource whose tags are returned.
- `tags`: A list of tags to add to the resource.>

"""
tag_resource(resourceArn, tags; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("TagResource", Dict{String, Any}("resourceArn"=>resourceArn, "tags"=>tags); aws_config=aws_config)
tag_resource(resourceArn, tags, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("TagResource", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("resourceArn"=>resourceArn, "tags"=>tags), params)); aws_config=aws_config)

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

Removes a system instance from its target (Cloud or Greengrass).

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"id"`: The ID of the system instance to remove from its target.
"""
undeploy_system_instance(; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("UndeploySystemInstance"; aws_config=aws_config)
undeploy_system_instance(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("UndeploySystemInstance", params; aws_config=aws_config)

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

Removes a tag from the specified resource.

# Arguments
- `resource_arn`: The Amazon Resource Name (ARN) of the resource whose tags are to be
  removed.
- `tag_keys`: A list of tag key names to remove from the resource. You don't specify the
  value. Both the key and its associated value are removed.  This parameter to the API
  requires a JSON text string argument. For information on how to format a JSON parameter for
  the various command line tool environments, see Using JSON for Parameters in the AWS CLI
  User Guide.

"""
untag_resource(resourceArn, tagKeys; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("UntagResource", Dict{String, Any}("resourceArn"=>resourceArn, "tagKeys"=>tagKeys); aws_config=aws_config)
untag_resource(resourceArn, tagKeys, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("UntagResource", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("resourceArn"=>resourceArn, "tagKeys"=>tagKeys), params)); aws_config=aws_config)

"""
    update_flow_template(definition, id)
    update_flow_template(definition, id, params::Dict{String,<:Any})

Updates the specified workflow. All deployed systems and system instances that use the
workflow will see the changes in the flow when it is redeployed. If you don't want this
behavior, copy the workflow (creating a new workflow with a different ID), and update the
copy. The workflow can contain only entities in the specified namespace.

# Arguments
- `definition`: The DefinitionDocument that contains the updated workflow definition.
- `id`: The ID of the workflow to be updated. The ID should be in the following format.
  urn:tdm:REGION/ACCOUNT ID/default:workflow:WORKFLOWNAME

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"compatibleNamespaceVersion"`: The version of the user's namespace. If no value is
  specified, the latest version is used by default. Use the GetFlowTemplateRevisions if you
  want to find earlier revisions of the flow to update.
"""
update_flow_template(definition, id; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("UpdateFlowTemplate", Dict{String, Any}("definition"=>definition, "id"=>id); aws_config=aws_config)
update_flow_template(definition, id, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("UpdateFlowTemplate", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("definition"=>definition, "id"=>id), params)); aws_config=aws_config)

"""
    update_system_template(definition, id)
    update_system_template(definition, id, params::Dict{String,<:Any})

Updates the specified system. You don't need to run this action after updating a workflow.
Any deployment that uses the system will see the changes in the system when it is
redeployed.

# Arguments
- `definition`: The DefinitionDocument that contains the updated system definition.
- `id`: The ID of the system to be updated. The ID should be in the following format.
  urn:tdm:REGION/ACCOUNT ID/default:system:SYSTEMNAME

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"compatibleNamespaceVersion"`: The version of the user's namespace. Defaults to the
  latest version of the user's namespace. If no value is specified, the latest version is
  used by default.
"""
update_system_template(definition, id; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("UpdateSystemTemplate", Dict{String, Any}("definition"=>definition, "id"=>id); aws_config=aws_config)
update_system_template(definition, id, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("UpdateSystemTemplate", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("definition"=>definition, "id"=>id), params)); aws_config=aws_config)

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

Asynchronously uploads one or more entity definitions to the user's namespace. The document
parameter is required if syncWithPublicNamespace and deleteExistingEntites are false. If
the syncWithPublicNamespace parameter is set to true, the user's namespace will synchronize
with the latest version of the public namespace. If deprecateExistingEntities is set to
true, all entities in the latest version will be deleted before the new DefinitionDocument
is uploaded. When a user uploads entity definitions for the first time, the service creates
a new namespace for the user. The new namespace tracks the public namespace. Currently
users can have only one namespace. The namespace version increments whenever a user uploads
entity definitions that are backwards-incompatible and whenever a user sets the
syncWithPublicNamespace parameter or the deprecateExistingEntities parameter to true. The
IDs for all of the entities should be in URN format. Each entity must be in the user's
namespace. Users can't create entities in the public namespace, but entity definitions can
refer to entities in the public namespace. Valid entities are Device, DeviceModel, Service,
Capability, State, Action, Event, Property, Mapping, Enum.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"deprecateExistingEntities"`: A Boolean that specifies whether to deprecate all entities
  in the latest version before uploading the new DefinitionDocument. If set to true, the
  upload will create a new namespace version.
- `"document"`: The DefinitionDocument that defines the updated entities.
- `"syncWithPublicNamespace"`: A Boolean that specifies whether to synchronize with the
  latest version of the public namespace. If set to true, the upload will create a new
  namespace version.
"""
upload_entity_definitions(; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("UploadEntityDefinitions"; aws_config=aws_config)
upload_entity_definitions(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = iotthingsgraph("UploadEntityDefinitions", params; aws_config=aws_config)


text:
# @testset "$(format("ADMM Algorithm: Small Input[Gaussian + Bernoulli + Poisson + Gamma + NegativeBinomial]"))" begin
#   let
#     Random.seed!(65536)
#     for i in 1:200
#       @printf("small case: rank = %d\n", i)
#       io = open("./test_result/gaussian_bernoulli/small/rank"*string(2*i)*".txt", "w")
#       truth_matrix     = rand([(FixedRankMatrix(Distributions.Gaussian(5, 10), rank = i), 400, 200),
#                                (FixedRankMatrix(Distributions.Bernoulli(0.5),  rank = i),  400, 200)])
#       sample_model     = provide(Sampler{BernoulliModel}(), rate = 0.8)
#       input_matrix     = sample_model.draw(truth_matrix)
#       @timeit to  "Gaussian + Bernoulli" completed_matrix, type_tracker = complete(A            = input_matrix,
#                                                                                maxiter      = 200,
#                                                                                ρ            = 0.3,
#                                                                                use_autodiff = false,
#                                                                                gd_iter      = 3,
#                                                                                debug_mode   = false,
#                                                                                project_rank = 2 * i,
#                                                                                io           = io)
#       log_simulation_result(Bernoulli(), completed_matrix, truth_matrix, type_tracker, io = io)
#       log_simulation_result(Gaussian(),  completed_matrix, truth_matrix, type_tracker, io = io)
#       show(io, MIME("text/plain"), to)
#       close(io)
#     end
#   end
# end

ext: jl


text:
module TensorPolynomialBases

using StaticArrays
using TensorValues
using Test

export ScratchData
export TensorPolynomialBasis
export MonomialBasis
export QGradMonomialBasis
export QCurlGradMonomialBasis
export test_polynomial_basis_without_gradient
export test_polynomial_basis
export gradient_type, value_type, point_type
export evaluate, gradient
export evaluate!, gradient!
import Base: length, ndims

include("Utils.jl")

include("Interfaces.jl")

include("MonomialBases.jl")

include("QGradMonomialBases.jl")

include("QCurlGradMonomialBases.jl")

end # module


text:
# ------------ Choice sites ------------ #

@inline function (ctx::AssessContext)(call::typeof(trace),
                                      addr::A,
                                      d::Distribution{K}) where {A <: Address, K}
    visit!(ctx, addr)
    haskey(ctx.target, addr) || error("AssessError: constrained target must provide constraints for all possible addresses in trace. Missing at address $addr.")
    val = getindex(ctx.target, addr)
    increment!(ctx, logpdf(d, val))
    return val
end

# ------------ Learnable ------------ #

@inline function (ctx::AssessContext)(fn::typeof(learnable), addr::Address)
    visit!(ctx, addr)
    haskey(ctx.params, addr) && return getindex(ctx.params, addr)
    error("Parameter not provided at address $addr.")
end

# ------------ Fillable ------------ #

@inline function (ctx::AssessContext)(fn::typeof(fillable), addr::Address)
    haskey(ctx.target, addr) && return getindex(ctx.target, addr)
    error("(fillable): parameter not provided at address $addr.")
end

# ------------ Call sites ------------ #

@inline function (ctx::AssessContext)(c::typeof(trace),
                                      addr::A,
                                      call::Function,
                                      args...) where A <: Address
    visit!(ctx, addr)
    ps = get_sub(ctx.params, addr)
    ss = get_sub(ctx.target, addr)
    ret, w = assess(ss, ps, call, args...)
    increment!(ctx, w)
    return ret
end

@inline function (ctx::AssessContext)(c::typeof(trace),
                                      addr::A,
                                      call::G,
                                      args...) where {G <: GenerativeFunction,
                                                      A <: Address}
    visit!(ctx, addr)
    ps = get_sub(ctx.params, addr)
    ss = get_sub(ctx.target, addr)
    ret, w = assess(ss, ps, call.fn, args...)
    increment!(ctx, w)
    return ret
end

# ------------ Convenience ------------ #

function assess(opt::J, sel::L, params, fn::Function, args...) where {J <: CompilationOptions, L <: AddressMap}
    ctx = Assess(opt, sel, params)
    ret = ctx(fn, args...)
    b, missed = compare(sel, ctx.visited)
    b || error("AssessError: did not visit all constraints in target.\nDid not visit: $(missed).")
    return ret, ctx.weight
end

function assess(sel::L, params, fn::Function, args...) where L <: AddressMap
    ctx = Assess(DefaultPipeline(), sel, params)
    ret = ctx(fn, args...)
    b, missed = compare(sel, ctx.visited)
    b || error("AssessError: did not visit all constraints in target.\nDid not visit: $(missed).")
    return ret, ctx.weight
end

# ------------ Documentation ------------ #

@doc(
"""
```julia
mutable struct AssessContext{P <: AddressMap} <: ExecutionContext
    select::AddressMap
    weight::Float64
    params::P
end
```

The `AssessContext` is used to assess selections according to a model function. For computation in the `AssessContext` to execute successfully, the `select` selection must provide a choice for every address visited in the model function, and the model function must allow the context to visit every constraints expressed in `select`.

Inner constructors:

```julia
function Assess(obs::Vector{Tuple{K, P}}) where {P, K <: Union{Symbol, Pair}}
    c_sel = selection(obs)
    new{EmptyAddressMap}(c_sel, 0.0, AddressMap())
end
```

Outer constructors:

```julia
AssessContext(obs::K, params) where {K <: AddressMap} = new(obs, 0.0, params)
Assess(obs::Vector) = AssessContext(selection(obs))
Assess(obs::AddressMap) = AssessContext(obs, AddressMap())
Assess(obs::AddressMap, params) = AssessContext(obs, params)
```
""", AssessContext)

@doc(
"""
```julia
ret, w = assess(sel::L, fn::Function, args...; params = AddressMap()) where L <: AddressMap
ret, w = assess(sel::L, fn::typeof(rand), d::Distribution{K}; params = AddressMap()) where {L <: AddressMap, K}
```

`assess` provides an API to the `AssessContext` execution context. You can use this function on any of the matching signatures above - it will return the return value `ret`, and the likelihood weight assess of the user-provided selection `sel`. The selection should satisfy the following requirement:

1. At any random choice in any branch traveled according to the constraints of `sel`, `sel` must provide a constraint for that choice.

Simply put, this just means you need to provide a constraint for each `ChoiceSite` you encounter.
""", assess)


text:
# Bernoulli Arm Model

type Bernoulli <: BanditArmBase
    armDist::Distributions.Bernoulli

    function Bernoulli( p::Real )
        new( Distributions.Bernoulli(p) )
    end
end

function pull!( arm::Bernoulli )
    return Distributions.rand(arm.armDist)
end

function tick!( arm::Bernoulli )
    # Do nothing
    nothing
end

function reset!( arm::Bernoulli )
    # Do nothing
    nothing
end


text:
using Random
using Plots
using Statistics

const MAX_GEN = 1000
const DNA_LEN = 25
const POP_SIZE = 20
const MUTATION_RATE = 0.001
const EXPERIMENTS = 20;
const EXPERIMENT_NAME = "pop20mut0001";

mutable struct Individial
    fitness::Int64
    dna::Vector{Bool}
    Individial() = begin
        ind = new(0, rand(Bool, DNA_LEN))
        eval!(ind)
        #eval2!(ind)
        return ind
    end
end

const Population = Vector{Individial}

function eval!(ind::Individial)
    ind.fitness = sum(ind.dna)
end

#version that seek 10101010...
function eval2!(ind::Individial)
    ind.fitness = 0;
    for k in 1:DNA_LEN
        ind.fitness += (k % 2 == 1) ? ind.dna[k] : 1-ind.dna[k]
    end
end

function mutate!(ind::Individial)
    for k in 1:DNA_LEN
        ind.dna[k] = rand() > MUTATION_RATE ? ind.dna[k] : !ind.dna[k]
    end
end

function breed!(parents::Population, childs::Population)
    tot_fitness = sum(ind -> ind.fitness, parents)
    npairs = div(POP_SIZE, 2)
    Threads.@threads for n in 1:npairs
        parent1 = roulette_wheel(parents, rand(1:tot_fitness))
        parent2 = roulette_wheel(parents, rand(1:tot_fitness))
        child1 = childs[n]
        child2 = childs[n + npairs]
        cross!(parent1, parent2, child1, child2)
    end
end

function cross!(
        parent1::Individial, parent2::Individial,
        child1::Individial, child2::Individial
        )
    cross_point = rand(0:DNA_LEN)
    for k in 1:DNA_LEN
        child1.dna[k] = (k <= cross_point ? parent1.dna[k] : parent2.dna[k])
        child2.dna[k] = (k <= cross_point ? parent2.dna[k] : parent1.dna[k])
    end
end

function roulette_wheel(pop::Population, x::Int64)::Individial
    n = 0
    while x > 0 && n+1 < length(pop)
        n += 1
        x -= pop[n].fitness
    end
    return pop[n]
end

function eva()
    log_best = Vector{Int64}()
    log_avg = Vector{Float64}()
    log_q25 = Vector{Float64}()
    log_q75 = Vector{Float64}()
    best = 1
    #random initial population
    pop = [Individial() for k in 1:POP_SIZE]
    #buffer for next population
    childs = [Individial() for k in 1:POP_SIZE]
    #then iterate:
    for gen in 1:MAX_GEN
        #generate offspring
        breed!(pop, childs)
        #mutate and calculate fitness
        Threads.@threads for ind in childs
            mutate!(ind)
            eval!(ind)
            #eval2!(ind)
        end
        #kill the parents
        begin
            temp = pop
            pop = childs
            childs = temp
        end
        #find the best guy
        best = 1
        for k in 1:POP_SIZE
            best = (pop[k].fitness > pop[best].fitness) ? k : best
        end
        #save results
        push!(log_best, pop[best].fitness)
        push!(log_avg , sum(ind -> ind.fitness/length(pop), pop))
        push!(log_q25, quantile!([p.fitness for p in pop], 0.25))
        push!(log_q75, quantile!([p.fitness for p in pop], 0.75))
    end
    return (pop[best], log_best, log_avg, log_q25, log_q75)
end

function main()
    log_avg = zeros(MAX_GEN)
    log_best = zeros(MAX_GEN)
    log_q25 = zeros(MAX_GEN)
    log_q75 = zeros(MAX_GEN)
    for k in 1:EXPERIMENTS
        println("experiment #", k)
        @time (result, _log_best, _log_avg, _log_q25, _log_q75) = eva()
        println(result);
        log_avg += _log_avg/EXPERIMENTS
        log_best += _log_best/EXPERIMENTS
        log_q25 += _log_q25/EXPERIMENTS
        log_q75 += _log_q75/EXPERIMENTS
    end
    p = plot(ylims = (12.5,DNA_LEN), legend = :bottomright)
    plot!(log_avg, label = "average")
    plot!(log_best, label = "best")
    plot!(log_q25, fillrange = log_q75, alpha = 0.3, label = "first-third quantile")
    savefig(p, "sga-"*EXPERIMENT_NAME*".png")
end

main()

max_stars_repo_name: OndrejKincl/evaTeaching-python

max_issues_repo_name: OndrejKincl/evaTeaching-python

max_forks_repo_name: OndrejKincl/evaTeaching-python


text:
#! /usr/bin/julia

#=
Small Parser for Project Timelogs
Brad Dowling
CIS 620, Fall 2020
=#

module SmallParser

export parse_timelog, summary_stastistics

using DataFrames, Dates, StatsBase

# Utility Functions

"Split log file into lines"
function process_file(filename::String)
    f = open(filename)
    lines = readlines(f)

    # Handle files with many null characters.
    if '\0' ∈ lines[1]
        lines = process_broken_file(lines)
    end

    lines = filter(x->length(x) > 0, lines)
    return split.(lines)
end

"Fix the files with many null chars"
function process_broken_file(lines)
    fixed_lines = join.(split.(lines, "\0"), "")
    fixed_lines = map(x->x[1:end-1], fixed_lines)

    return fixed_lines
end

"Process the data in the line vectors"
function process_lines(lines)
    dates = []
    start_times = []
    end_times = []
    activity = []

    last_date = ""
    last_activity = ""
    last_start = ""
    last_end = ""

    for line in lines
        if occursin(r"\d+/\d+/\d\d", line[1])
            if length(line) > 4
                last_activity = join(line[5:end], " ")
            end

            push!(dates, line[1][1:end-1])
            last_date = line[1][1:end-1]

            push!(start_times, line[2])
            last_start = line[2]

            # Handle comma separated timestamps
            if endswith(",", line[4])
                # cut it off and forget about second time stamp set
                line[4] = line[4][:end-1]

                # line components 5, 7 separated onto new line with
                # all other components identical
            end
            push!(end_times, line[4])
            last_end = line[4]

            push!(activity, last_activity)
        elseif occursin(r"\d+:\d\d", line[1])
            if length(line) > 3
                last_activity = join(line[4:end], " ")
            end

            push!(dates, last_date)

            push!(start_times, line[1])
            last_start = line[1]

            # Handle comma separated timestamps
            if endswith(",", line[3])
                # cut off second time
                line[3] = line[3][:end-1]

                # line components 4, 6 to be separated onto another line
                # with all other components identical.
            end

            push!(end_times, line[3])
            last_end = line[3]

            push!(activity, last_activity)

        elseif line[1] == "-"
            push!(dates, last_date)
            push!(start_times, last_start)
            push!(end_times, last_end)
            push!(activity, join(line, " "))
        end
    end

    # Make sure all columns are the same length
    @assert all(i->length(i) == length(dates),
                (dates, start_times, end_times, activity))

    return (dates, start_times, end_times, activity)
end

"Parse and normalize datetimes"
function fix_datetimes(dates, start_times, end_times)
    # Fix datetime types
    dates = Year(2000) .+ Date.(dates, dateformat"m/dd/yy")

    # Normalize hours
    for (i, t) in enumerate(start_times)
        if ~endswith(t, r"[ap]m")
            start_times[i] = join(cat(split(t, r"[ap]m")[1], "pm", dims=1), "")
        end
        if ~startswith(t, r"\d\d:\d\d")
            start_times[i] = join(cat("0", t, dims=1), "")
        end
        if endswith(t, r",")
            start_times[i] = t[1:end-1]
        end
    end
    for (i, t) in enumerate(end_times)
        if ~endswith(t, r"[ap]m")
            end_times[i] = join(cat(split(t, "[ap]m")[1], "pm", dims=1), "")
        end
        if ~startswith(t, r"\d\d:\d\d")
            end_times[i] = join(cat("0", t, dims=1), "")
        end
        if endswith(t, r",")
            end_times[i] = t[1:end-1]
        end
    end

    start_times = [Time(t, dateformat"II:MMpp") for t in start_times]
    end_times = [Time(t, dateformat"II:MMpp") for t in end_times]

    total = Minute.(end_times .- start_times)
    for (i, t) in enumerate(total)
        if t < Minute(0)
            total[i] = t + Minute(1440)
        end
    end

    return (dates, start_times, end_times, total)
end

"Create a dataframe from the parsed logfile"
function create_dataframe(dates, start_times, end_times, total, activity)
    return DataFrame(:Date => dates,
                     :Start => start_times,
                     :End => end_times,
                     :Total => total,
                     :Activity => activity)
end

### Public API

"Main function for parsing log files"
function parse_timelog(filename::String)::DataFrame
    lines = process_file(filename)
    (dates, start_times, end_times, activity) = process_lines(lines)
    (dates, start_times, end_times, total) = fix_datetimes(dates, start_times, end_times)
    return create_dataframe(dates, start_times, end_times, total, activity)
end

"Print Summary Statistics on Total time"
function summary_statistics(df::DataFrame)
    println("Total Time Spent: $(sum(df[!, :Total]))")
    println("Summary of time spent per session (minutes):")
    describe(Dates.value.(df[!, :Total]))
end

# Program entry point
Base.@ccallable function julia_main()::Cint
    try
        real_main()
    catch
        Base.invokelatest(Base.display_error, Base.catch_stack())
        return 1
    end
    return 0
end

function real_main()
    if length(ARGS) ≠ 1
        println("Usage: sh>  SmallParser.jl <logfile>")
        return
    end

    summary_statistics(parse_timelog(ARGS[1]))
end

if abspath(PROGRAM_FILE) == @__FILE__
    real_main()
end

end # module


text:
# Copyright (c) 2017: Miles Lubin and contributors
# Copyright (c) 2017: Google Inc.
#
# Use of this source code is governed by an MIT-style license that can be found
# in the LICENSE.md file or at https://opensource.org/licenses/MIT.

"""
    _UnsafeVectorView(offset, len, ptr)

Lightweight unsafe view for vectors.

## Motivation

`_UnsafeVectorView` is needed as an allocation-free equivalent of `view`. Other
alternatives, like `view(x, 1:len)` or a struct like
```
struct _SafeView{T}
    x::Vector{T}
    len::Int
end
```
will allocate so that `x` can be tracked by Julia's GC.

`_UnsafeVectorView` relies on the fact that the use-cases of `_UnsafeVectorView`
only temporarily wrap a long-lived vector like `d.jac_storage` so that we don't
have to worry about the GC removing `d.jac_storage` while `_UnsafeVectorView`
exists. This lets us use a `Ptr{T}` and create a struct that is `isbitstype` and
therefore does not allocate.

## Example

Instead of `view(x, 1:10)`, use `_UnsafeVectorView(0, 10, pointer(x))`.

## Unsafe behavior

`_UnsafeVectorView` is unsafe because it assumes that the vector `x` that the
pointer `ptr` refers to remains valid during the usage of `_UnsafeVectorView`.
"""
struct _UnsafeVectorView{T} <: DenseVector{T}
    offset::Int
    len::Int
    ptr::Ptr{T}
end

Base.getindex(x::_UnsafeVectorView, i) = unsafe_load(x.ptr, i + x.offset)

function Base.setindex!(x::_UnsafeVectorView, value, i)
    unsafe_store!(x.ptr, value, i + x.offset)
    return value
end

Base.length(v::_UnsafeVectorView) = v.len

Base.size(v::_UnsafeVectorView) = (v.len,)

function _UnsafeVectorView(x::Vector, N::Int)
    if length(x) < N
        resize!(x, N)
    end
    return _UnsafeVectorView(0, N, pointer(x))
end

function _reinterpret_unsafe(::Type{T}, x::Vector{R}) where {T,R}
    # how many T's fit into x?
    @assert isbitstype(T) && isbitstype(R)
    len = length(x) * sizeof(R)
    p = reinterpret(Ptr{T}, pointer(x))
    return _UnsafeVectorView(0, div(len, sizeof(T)), p)
end

max_stars_repo_name: JuliaOpt/MathOptInterface

max_issues_repo_name: JuliaOpt/MathOptInterface

max_forks_repo_name: JuliaOpt/MathOptInterface


text:
include("settings.jl")
include("SGSolver.jl")
include("DLRSolver.jl")
include("plotting.jl")

using NPZ;

close("all");

s = Settings();

###########################
# run conservative solver #
###########################
s.NCons = 2; # number of conserved basis functions
s.iCons = [1 1; 1 2]; # indices of conserved basis funtions
solver = DLRSolver(s);

PhiQuad = Array(solver.basis.PhiQuad');
PhiQuadCons = Array(solver.basis.PhiQuadCons');
PhiQuadW = Array(solver.basis.PhiQuadW');
fXi = 0.25;

X,S,W,uCons = FactorIC(solver);

@time tEnd, Xt,St,Wt,uCons = SolveSplitUnconventionalIntegrator(solver,X,S,W,uCons);

# compute moments
uQ = Xt*St*Wt'*PhiQuad + uCons*PhiQuadCons;
uDLRCons = uQ*Array(solver.basis.PhiQuadWFull')*fXi;

uDLRCons = Array(uDLRCons')

##################################
# run stochastic-Galerkin solver #
##################################
s.NCons = 0;
s.iCons = 0;

solver = Solver(s);

@time tEnd, uSG = Solve(solver);

#uSG = Array(uSG')

######################################
# run projector-splitting integrator #
######################################
s.stabilization = 0;
solver = DLRSolver(s);

@time tEnd, Xt, St, WDLRPS = SolveBackward(solver);

uDLR = Array((Xt*St*WDLRPS')')

#################################
# run unconventional integrator #
#################################
s.stabilization = 0;
solver = DLRSolver(s);

@time tEnd, Xt,St,Wt = SolveUnconventionalIntegrator(solver,X,S,W);

uDLRF = Array((Xt*St*Wt')')

#########################
##### Plot solution #####
#########################
plotSolution = Plotting(s,solver.basis,solver.q,s.tEnd);

x0 = 0.42;
PlotInXi(plotSolution,uSG,convert(Int, round(s.Nx*x0/(s.b-s.a))),"Figure4a");
PlotInXi(plotSolution,uDLR,convert(Int, round(s.Nx*x0/(s.b-s.a))),"Figure4b");
#PlotInXi(plotSolution,uDLRF,convert(Int, round(s.Nx*x0/(s.b-s.a))),"Figure4c");

Nq = plotSolution.settings.Nq;
Nx = plotSolution.settings.Nx;
NxFine = 1000;
xFine = collect(range(plotSolution.settings.a,plotSolution.settings.b,length=NxFine))
uExact = zeros(NxFine);
varExact = zeros(NxFine);
uPlot = zeros(Nx);
varPlot = zeros(Nx);
vPlot = zeros(Nx);
varVPlot = zeros(Nx);
wPlot = zeros(Nx);
varWPlot = zeros(Nx);

PlotExpectedValue(plotSolution,uSG,uDLR,uDLRF,"noFilter","Figure1");

# start plot
fig = figure("Figure2",figsize=(15, 8), dpi=100)#, facecolor='w', edgecolor='k') # dpi Aufloesung
ax = gca()
for j = 1:Nx
    uVals = EvalAtQuad(plotSolution.basis,uSG[:,j]);
    uPlot[j] = Integral(plotSolution.q,uVals*0.25);
    varPlot[j] = Integral(plotSolution.q,0.25*(uVals.-uPlot[j]).^2);
    vVals = EvalAtQuad(plotSolution.basis,uDLRF[:,j]);
    vPlot[j] = Integral(plotSolution.q,vVals*0.25);
    varVPlot[j] = Integral(plotSolution.q,0.25*(vVals.-vPlot[j]).^2);
    wVals = EvalAtQuad(plotSolution.basis,uDLRCons[:,j]);
    wPlot[j] = Integral(plotSolution.q,wVals*0.25);
    varWPlot[j] = Integral(plotSolution.q,0.25*(wVals.-wPlot[j]).^2);
end
varMax = maximum(varPlot);
expMax = maximum(uPlot);
qFine = Quadrature(200,"Gauss")
exactState = zeros(NxFine,qFine.Nq,qFine.Nq);
for j = 1:NxFine
    for k = 1:qFine.Nq
        for l = 1:qFine.Nq
            exactState[j,k,l] = plotSolution.settings.solutionExact(plotSolution.tEnd,xFine[j],qFine.xi[k],qFine.xi[l])[1];
        end
    end
end
for j = 1:NxFine
    for k = 1:qFine.Nq
        for l = 1:qFine.Nq
            uExact[j] += exactState[j,k,l]*0.25*qFine.w[k]*qFine.w[l];
        end
    end
    for k = 1:qFine.Nq
        for l = 1:qFine.Nq
            varExact[j] += (exactState[j,k,l]-uExact[j])^2 * 0.25*qFine.w[k]*qFine.w[l];
        end
    end
end
ax.plot(plotSolution.x,uPlot, "k--", linewidth=2, label=L"SG$_{100}$", alpha=1.0)
ax.plot(plotSolution.x,vPlot, "g-.", linewidth=2, label=L"DLRA$_{9}$", alpha=1.0)
ax.plot(plotSolution.x,wPlot, "m:", linewidth=2, label=L"DLRA$_{9}$, BC", alpha=1.0)

ylabel("Expectation", fontsize=20,color="red")
ax.plot(xFine,uExact, "r-", linewidth=2, alpha=0.5)
ax2 = ax[:twinx]() # Create another axis on top of the current axis
ylabel("Standard deviation", fontsize=20,color="blue")
ax2.plot(plotSolution.x,sqrt.(varPlot), "k--", linewidth=2, label="SG", alpha=1.0)
ax2.plot(plotSolution.x,sqrt.(varVPlot), "g-.", linewidth=2, label="DLRA", alpha=1.0)
ax2.plot(plotSolution.x,sqrt.(varWPlot), "m:", linewidth=2, label="unconventional DLRA", alpha=1.0)
#ax2[:set_position](new_position) # Position Method 2
setp(ax2[:get_yticklabels](),color="blue") # Y Axis font formatting
setp(ax[:get_yticklabels](),color="red")
ax2.plot(xFine,sqrt.(varExact), "b-", linewidth=2, alpha=0.5)
#ylimMinus = -0.5;
#ylimPlus = 16.0
#ax[:set_ylim]([ylimMinus,ylimPlus])
ax.set_xlim([plotSolution.settings.a,plotSolution.settings.b])
ax.set_xlabel("x", fontsize=20);
ax.legend(loc="upper right", fontsize=20)
ax.tick_params("both",labelsize=20)
ax2.tick_params("both",labelsize=20)
fig.canvas.draw() # Update the figure

#########################################
##### run computations with filters #####
#########################################
s.lambda = 0.00001;
##################################
# run stochastic-Galerkin solver #
##################################
s.NCons = 0;
s.iCons = 0;

solver = Solver(s);

@time tEnd, uSG = Solve(solver);

######################################
# run projector-splitting integrator #
######################################
s.stabilization = 0;
solver = DLRSolver(s);

@time tEnd, X, S, W = SolveBackward(solver);

uDLR = Array((X*S*W')')

#################################
# run unconventional integrator #
#################################
s.stabilization = 0;
solver = DLRSolver(s);

@time tEnd, X, S, W = SolveForward(solver);

uDLRF = Array((X*S*W')')

###################################################
##                      Plot                     ##
###################################################
PlotExpectedValue(plotSolution,uSG,uDLR,uDLRF,"Filter","Figure3");

x0 = 0.42;

PlotInXi(plotSolution,uSG,convert(Int, round(s.Nx*x0/(s.b-s.a))),"Figure4c");
PlotInXi(plotSolution,uDLR,convert(Int, round(s.Nx*x0/(s.b-s.a))),"Figure4d");
#PlotInXi(plotSolution,uDLRF,convert(Int, round(s.Nx*x0/(s.b-s.a))),"fuDLR");

#################################################
##                  Plot basis                 ##
#################################################
WDLRPlot = zeros(s.r,s.Nq,s.Nq)
xgrid, ygrid = meshgrid(solver.q.xi, solver.q.xi)

WQuad = EvalAtQuad(solver.basis,WDLRPS);

for n = 1:s.r
    for i = 1:s.Nq
        for j = 1:s.Nq
            WDLRPlot[n,i,j] = WQuad[(j-1)*s.Nq+i,n]
        end
    end
end

fig = figure("Figure5",figsize=(10,10))
ax = fig.add_subplot(3,3,1, projection="3d")
surf(xgrid, ygrid, WDLRPlot[1,:,:]', cmap=ColorMap("viridis"), alpha=0.7)
tight_layout()

ax = fig.add_subplot(3,3,2, projection="3d")
surf(xgrid, ygrid, WDLRPlot[2,:,:]', cmap=ColorMap("viridis"), alpha=0.7)
tight_layout()

ax = fig.add_subplot(3,3,3, projection="3d")
surf(xgrid, ygrid, WDLRPlot[3,:,:]', cmap=ColorMap("viridis"), alpha=0.7)
tight_layout()

ax = fig.add_subplot(3,3,4, projection="3d")
surf(xgrid, ygrid, WDLRPlot[4,:,:]', cmap=ColorMap("viridis"), alpha=0.7)
tight_layout()

ax = fig.add_subplot(3,3,5, projection="3d")
surf(xgrid, ygrid, WDLRPlot[5,:,:]', cmap=ColorMap("viridis"), alpha=0.7)
tight_layout()

ax = fig.add_subplot(3,3,6, projection="3d")
surf(xgrid, ygrid, WDLRPlot[6,:,:]', cmap=ColorMap("viridis"), alpha=0.7)
tight_layout()

ax = fig.add_subplot(3,3,7, projection="3d")
surf(xgrid, ygrid, WDLRPlot[7,:,:]', cmap=ColorMap("viridis"), alpha=0.7)
tight_layout()

ax = fig.add_subplot(3,3,8, projection="3d")
surf(xgrid, ygrid, WDLRPlot[8,:,:]', cmap=ColorMap("viridis"), alpha=0.7)
tight_layout()

ax = fig.add_subplot(3,3,9, projection="3d")
surf(xgrid, ygrid, WDLRPlot[9,:,:]', cmap=ColorMap("viridis"), alpha=0.7)
tight_layout()


text:
# decision making simulation
# using unreliable state estimation

module AnimeDpMcl
  using Plots
  pyplot()

  include(joinpath(split(@__FILE__, "src")[1], "src/model/world/puddle_world.jl"))
  include(joinpath(split(@__FILE__, "src")[1], "src/model/map/map.jl"))
  include(joinpath(split(@__FILE__, "src")[1], "src/model/robot/warp_robot/warp_robot.jl"))
  include(joinpath(split(@__FILE__, "src")[1], "src/localization/particle_filter/systematic_sampling/mcl_sys_samp.jl"))
  include(joinpath(split(@__FILE__, "src")[1], "src/model/goal/goal.jl"))
  include(joinpath(split(@__FILE__, "src")[1], "src/model/puddle/puddle.jl"))
  include(joinpath(split(@__FILE__, "src")[1], "src/decision_making/partially_observable_mdp/q_mdp_agent.jl"))

  function main(delta_time=0.1, end_time=30; is_test=false)
    # save path of gif file
    path = "src/decision_making/partially_observable_mdp/anime_qmdp_mcl.gif"

    # simulation world
    world = PuddleWorld(-5.0, 5.0, -5.0, 5.0,
                        delta_time=delta_time,
                        end_time=end_time,
                        is_test=is_test,
                        save_path=path)

    # map including landmarks
    map = Map()
    landmark_positions = [[1.0, 4.0],[4.0, 1.0],[-4.0, -4.0]]
    for (idx, pos) in enumerate(landmark_positions)
      add_object(map, Object(pos[1], pos[2], id=idx))
    end
    append(world, map)

    # goal
    goal = Goal(-3.0, -3.0)
    append(world, goal)

    # puddles
    puddles = [Puddle([-2.0, 0.0], [0.0, 2.0], 0.1),
               Puddle([-0.5, -2.0], [2.5, 1.0], 0.1)]
    for puddle in puddles
      append(world, puddle)
    end

    # robot including sensor, agent, estimator
    init_pose = [2.5, 2.5, 0.0]
    sensor = Sensor(map, dist_noise_rate=0.1, dir_noise=pi/90)
    noises = Dict("nn"=>0.20, "no"=>0.001, "on"=>0.11, "oo"=>0.20)
    mcl = MclSysSamp(init_pose, 100, noises, env_map=map,
                     dist_dev_rate=0.14, dir_dev=0.05)
    agent = QmdpAgent(delta_time=delta_time, estimator=mcl, goal=goal, puddles=puddles)
    robot = DifferentialWheeledRobot(init_pose, 0.2, "red",
                                     agent, delta_time,
                                     noise_per_meter=5,
                                     noise_std=pi/30,
                                     bias_rate_stds=[0.1, 0.1],
                                     sensor=sensor)
    append(world, robot)

    draw(world)
  end
end

max_stars_repo_name: ShisatoYano/JuliaAutonomy

max_issues_repo_name: ShisatoYano/JuliaAutonomy

max_forks_repo_name: ShisatoYano/JuliaAutonomy


text:
using SBML
using Catalyst
using EzXML
using MathML
using ModelingToolkit
using OrdinaryDiffEq
using Symbolics
using Test

@testset "SBML.jl" begin
    # @testset "suite" begin include("test.jl") end
    #=@testset "data" begin include("data.jl") end=#
    @testset "sbml2reactionsystem" begin include("sbml2reactionsystem.jl") end
end


text:
using Parameters

abstract type AbstractThermoUncertainty end
export AbstractThermoUncertainty

struct EmptyThermoUncertainty <: AbstractThermoUncertainty end
export EmptyThermoUncertainty

@with_kw struct ConstantThermoUncertainty <: AbstractThermoUncertainty
    u::AbstractFloat = nothing
end
(c::ConstantThermoUncertainty)(T::AbstractFloat=nothing) = c.u


text:
using DataFrames
using Gadfly

benchmarks = readtable("benchmarks.csv", names=[:language, :benchmark, :time])
cdata = benchmarks[benchmarks[:language].== "c", :]
benchmarks = join(benchmarks, cdata, on=:benchmark)
benchmarks[:time]./= benchmarks[:time_1]
benchmarks[:language] = PooledDataArray(benchmarks[:language])
benchmarks[:benchmark] = PooledDataArray(benchmarks[:benchmark])
benchmarks = benchmarks[benchmarks[:language].!= "c", :]
benchmarks[:language] = setlevels!(benchmarks[:language], Dict{UTF8String,Any}(
  [lang => (lang == "javascript" ? "JavaScript" : ucfirst(lang)) for lang in benchmarks[:language]]))

p = plot(benchmarks,
    x = :language,
    y = :time,
    color = :benchmark,
    Scale.y_log10,
    Guide.ylabel(nothing),
    Guide.xlabel(nothing),
    Theme(
        default_point_size = 1mm,
        guide_title_position = :left,
        colorkey_swatch_shape = :circle,
        minor_label_font = "Georgia",
        major_label_font = "Georgia",
    ),
)

draw(SVG("_includes/benchmarks.svg", 8inch, 8inch/golden), p)


text:
function PSI.construct_device!(
    optimization_container::PSI.OptimizationContainer,
    sys::PSY.System,
    model::PSI.DeviceModel{H, D},
    ::Type{S},
) where {
    H <: PSY.HydroEnergyReservoir,
    D <: HydroDispatchReservoirBudgetUpperBound,
    S <: PM.AbstractActivePowerModel,
}
    devices = PSI.get_available_components(H, sys)

    if !PSI.validate_available_devices(H, devices)
        return
    end

    # Variables
    PSI.add_variables!(optimization_container, PSI.ActivePowerVariable, devices, D())

    # Energy Budget Constraint
    PSI.energy_budget_constraints!(
        optimization_container,
        devices,
        model,
        S,
        PSI.get_feedforward(model),
    )

    # Range Constraints
    PSI.add_constraints!(
        optimization_container,
        PSI.RangeConstraint,
        PSI.ActivePowerVariable,
        devices,
        model,
        S,
        PSI.get_feedforward(model),
    )

    PSI.feedforward!(optimization_container, devices, model, PSI.get_feedforward(model))

    # Cost Function
    PSI.cost_function!(optimization_container, devices, model, S, nothing)

    return
end


text:
using Test
using Forecast
using Distributions: MvLogNormal, MvNormal

@testset "ar" begin
    xar = ar(rand(100),10)
    @test xar isa AR
    @test xar.ic isa Dict
    @test xar.call == "ar(X, order=10, constant=true)"
    @test length(xar.Φ) == 10
    @test length(xar.fitted) == 100 - 10
    @test length(xar.residuals) == 100 - 10

    xar = ar(rand(100), 10; alpha = 0.05)
    @test xar isa AR
    @test xar.ic isa Dict
    @test xar.call == "ar(X, order=10, constant=true)"
    @test length(xar.fitted) == 100 - 10
    @test length(xar.residuals) == 100 - 10

    n = 10000
    atol = .2

    # ar(Φ,Φ0,x0,n)
    Φ,Φ0,x0,n = .1,.2,.3,n
    xar = ar(arsim(Φ,Φ0,x0,n),1)
    @test isapprox(xar.Φ,Φ; atol = atol)
    @test isapprox(xar.Φ0,Φ0; atol = atol)

    Φ,Φ0,x0,n = [.1,.2],.3,[.4,.5],n
    xar = ar(arsim(Φ,Φ0,x0,n),2)
    @test isapprox(xar.Φ,Φ; atol = atol)
    @test isapprox(xar.Φ0,Φ0; atol = atol)

    Φ,Φ0,x0,n = [.1 .2; .3 .4],[.5, .6],[.7,.8],n
    xar = ar(arsim(Φ,Φ0,x0,n),1)
    @test isapprox(xar.Φ,Φ; atol = 2*atol)
    @test isapprox(xar.Φ0,Φ0; atol = 2*atol)

    # ar(Φ,Φ0,x0,Σ,100)
    Φ,Φ0,x0,Σ2,n = .1,.2,.3,.4,n
    xar = ar(arsim(Φ,Φ0,x0,n;Σ2),1)
    @test isapprox(xar.Φ,Φ; atol = atol)
    @test isapprox(xar.Φ0,Φ0; atol = atol)
    @test isapprox(xar.Σ2,Σ2; atol = atol)

    Φ,Φ0,x0,Σ2,n = [.1,.2],.3,[.4,.5],.6,n
    xar = ar(arsim(Φ,Φ0,x0,n;Σ2),2)
    @test isapprox(xar.Φ,Φ; atol = atol)
    @test isapprox(xar.Φ0,Φ0; atol = atol)
    @test isapprox(xar.Σ2,Σ2; atol = atol)

    Φ,Φ0,x0,Σ2,n = [.1 .2; .3 .4],[.5, .6],[.7,.8],[.9 .10; .10 .9],n
    xar = ar(arsim(Φ,Φ0,x0,n;Σ2),1)
    @test isapprox(xar.Φ,Φ; atol = atol)
    @test isapprox(xar.Φ0,Φ0; atol = atol)
    @test isapprox(xar.Σ2,Σ2; atol = atol)

    Φ,Φ0,x0,Σ2,n = [.1 .2; .3 .4],[.0, .0],[.7,.8],[.9 .10; .10 .9],n
    xar = ar(arsim(Φ,Φ0,x0,n;Σ2),1,false)
    @test isapprox(xar.Φ,Φ; atol = atol)
    @test isapprox(xar.Φ0,Φ0; atol = atol)
    @test isapprox(xar.Σ2,Σ2; atol = atol)

    Φ,Φ0,x0,Σ2,n = reshape([[.1 -.1; .05 -.1] [.15 -.4; .3 .6]],2,2,2),
    [.9, .10],[.11 .12; .13 .14],[.9 .10; .10 .9],n
    xar = ar(arsim(Φ,Φ0,x0,n;Σ2),2)
    @test isapprox(xar.Φ,Φ; atol = atol)
    @test isapprox(xar.Φ0,Φ0; atol = atol)
    @test isapprox(xar.Σ2,Σ2; atol = atol)

    Φ,Φ0,x0,Σ2,n = reshape([[.01 -.01 .02; .05 -.01 .03; .01 -.05 .02]
                           [.015 -.04 .06; .03 .03 .06; .01 .04 -.1]],3,3,2),
    [.0, .0, .0],[.11 .12; .2 .13; .14 .6],[1 0.1 0.5; 0.1 1 0.1; 0.5 0.1 1],2*n
    xar = ar(arsim(Φ,Φ0,x0,n;Σ2),2,false)
    @test isapprox(xar.Φ,Φ; atol = atol)
    @test isapprox(xar.Φ0,Φ0; atol = atol)
    @test isapprox(xar.Σ2,Σ2; atol = atol)

    # ar(Φ,Φ0,x0,E,100)
    E1 = MvLogNormal(MvNormal(1,1))

    Φ,Φ0,x0,n = .1,.2,.3,n
    xar = ar(log.(arsim(Φ,Φ0,x0,n;E=E1)),1)
    @test xar isa AR

    Φ,Φ0,x0,n = [.1,.2],.3,[.4,.5],n
    xar = ar(log.(arsim(Φ,Φ0,x0,n;E=E1)),2)
    @test xar isa AR

    E2 = MvLogNormal(MvNormal(2,1))
    Φ,Φ0,x0,n = [.1 .2; .3 .4],[.5, .6],[.7,.8],n
    xar = ar(log.(arsim(Φ,Φ0,x0,n;E=E2)),1)
    @test xar isa AR

    # ar(Φ,n) fixed
    Φ,Φ0,x0,n = .5,0.0,1.,n
    x = arsim(Φ,Φ0,x0,n)
    xar  = ar(x,10)
    xarfixed = ar(x,10; dΦ=(xar.Φ,xar.Φ), dΦ0=(xar.Φ0, 0.0))
    xarfalse = ar(x,10,false)
    @test xarfixed.Φ == xarfalse.Φ
    @test xarfixed.Φ0 == xarfalse.Φ0
    @test xarfixed.Φse == xarfalse.Φse
    @test xarfixed.Σ2 == xarfalse.Σ2

    Φ,Φ0,x0,n = .5,0.0,1.,n
    x = arsim(Φ,Φ0,x0,n)
    xar  = ar(x,10)
    fΦ = copy(xar.Φ)
    fΦ[3] = 6.0
    fxar = ar(x,10; dΦ=(xar.Φ,fΦ), dΦ0 = (xar.Φ0, 10.0))
    @test fxar.Φ[3] == 6.0
    @test fxar.Φ0 == 10.0
    @test fxar.Φ0se[1] == 0.0
    @test fxar.Φse[3] == 0.0

    Φ,Φ0,x0,n = .5,.5,.5,n
    x = arsim(Φ,Φ0,x0,n)
    xar  = ar(x,1)
    fΦ = copy(xar.Φ)
    fΦ = 1.0
    @test_throws AssertionError ar(x,1; dΦ=(xar.Φ,fΦ), dΦ0 = (xar.Φ0, [1.0]))

    Φ,Φ0,x0,Σ2,n = reshape([[.01 -.01 .02; .05 -.01 .03; .01 -.05 .02]
                           [.015 -.04 .06; .03 .03 .06; .01 .04 -.1]],3,3,2),
    [.9, .10, .5],[.11 .12; .2 .13; .14 .6],[1 0.1 0.1; 0.1 1 0.1; 0.1 0.1 1],n
    x = arsim(Φ,Φ0,x0,n;Σ2)
    xar  = ar(x,2)
    fΦ = copy(xar.Φ)
    fΦ[1,3,1] = 6.0
    fΦ[3,1,2] = 9.0
    fxar = ar(x,2; dΦ=(xar.Φ,fΦ))
    @test fxar.Φ[1,3,1] == 6.0
    @test fxar.Φ[3,1,2] == 9.0

end


text:
"""
defines generic Dynamic type
"""

module DynamicDefinition

using ValidatedNumerics
using TaylorSeries:Taylor1
export Dynamic, MarkovDynamic, der, der_der, der_n, preim, nbranches, plottable, is_full_branch, domain, derivative, distorsion

abstract type Dynamic end
abstract type MarkovDynamic <: Dynamic end

function domain(S::Dynamic) end # declares a function with no methods; this should be better practice than @error "Not Implemented", we will switch later
nbranches(S::Dynamic) = @error "Not implemented"
plottable(S::Dynamic) = @error "Not implemented"
preim(S::Dynamic, k, y, ϵ) = @error "Not implemented"
is_full_branch(S::Dynamic) = @error "Not implemented"

# Derivative and distorsion of a generic function (*not* a dynamic). Here for convenience,
# since subtypes will need them.

# the isempty check is required because otherwise derivative(x -> 4*x, ∅) == 4.
"""
Nth derivative of a function (or a dynamic)
"""
derivative(f, x) = derivative(1, f, x)
derivative(n, f::Function, x) = isempty(x) ?  ∅ : f(Taylor1([x, 1], n))[n] * factorial(n)

"""
Distorsion of a function (or a dynamic), i.e., |f′ / f′′^2|
"""
function distorsion(f::Function, x)
	if isempty(x)
		return ∅
	end
	series = f(Taylor1([x, 1], 2))
	f′ = series[1]
	f′′ = 2*series[2]
	return abs(f′′ / f′^2)
end

# TODO: these do not necessarily work properly, since T() for a Mod1Dynamic contains the unquotiented map. Better not to use them at all.

# function iterate(T, x, ::Val{n}) where {n}
# 	for i in 1:n
# 		x=T(x)
# 	end
# 	return x
# end
#
# iterate(T, x, n)=iterate(T, x, Val(n))

end

max_stars_repo_name: orkolorko/ResponseManneville

max_issues_repo_name: orkolorko/ResponseManneville

max_forks_repo_name: orkolorko/ResponseManneville


text:
module TrajOptPlots

using MeshCat
# using GeometryTypes
using GeometryBasics
using Rotations
using CoordinateTransformations
using TrajectoryOptimization
using RecipesBase
using StaticArrays
using FileIO
using MeshIO
using RobotDynamics
using RobotZoo
using Colors

import RobotDynamics: orientation

export
    visualize!,
    waypoints!,
    traj3!

include("meshes.jl")
include("rigid_bodies.jl")
include("2d_vis.jl")
include("models.jl")

end # module


text:
using Gadfly

xs = 1:10.
ys = xs
zs = Float64[x^2*log(y) for x in xs, y in ys]
plot(x=xs, y=ys, z=zs, Geom.contour, Scale.color_none)


text:
# Height of the game window
HEIGHT = 400
# Width of the game window
WIDTH = 400
# Background color of the game window
BACKGROUND = colorant"purple"

# Globals to store the velocity of the actor
dx = 2
dy = 2

# Create an `Actor` object with an image
a=Actor("alien.png")

# Start playing background music
play_music("radetzky_ogg")

# The draw function is called by the framework. All we do here is draw the Actor
function draw(g::Game)
    draw(a)
end

# The update function is called every frame. Within the function, we
# * change the position of the actor by the velocity
# * if the actor hits the edges, we invert the velocity, and play a sound
# * if the up/down/left/right keys are pressed, we change the velocity to move the actor in the direction of the keypress
function update(g::Game)
    global dx, dy
    a.position.x += dx
    a.position.y += dy
    if a.x > 400-a.w || a.x < 2
        dx = -dx
        play_sound("eep")
    end
    if a.y > 400-a.h || a.y < 2
        dy = -dy
        play_sound("eep")
    end

    if g.keyboard.DOWN
        dy = 2
    elseif g.keyboard.UP
        dy = -2
    elseif g.keyboard.LEFT
        dx = -2
    elseif g.keyboard.RIGHT
        dx = 2
    end

end

# If the "space" key is pressed, change the displayed image to the "hurt" variant.
# Also schedule an event to change it back to normal after one second.
function on_key_down(g, k)
    if k == Keys.SPACE
        alien_hurt()
        schedule_once(alien_normal, 1)
    end
end

# We define functions to change the image for the actor. These functions are called from the keydown and scheduled events.
alien_hurt() = a.image = "alien_hurt.png"
alien_normal() = a.image = "alien.png"


text:
#!/usr/local/bin/julia
# author: zhwang
# date: 2022-03-01
# description: 分析主仓库的解答文件，比如统计作者名和提交总数之类。

function get_info(body::AbstractString)
    ## 获取代码内容
    code_reg = r"## @lc code=start\n([\s\S]*)\n## @lc code=end"
    code = match(code_reg, body)
    isnothing(code) && throw("未识别到代码内容")
    code = code.captures[1]
    ## 获取函数内容
    func_reg1 = r"^function (\w+!?\([\w:{}, ]*\))"
    func_reg2 = r"^(\w+!?\([\w:{}, ]*\))[\w: ]*=" ## one-line function
    funcs = String[]
    for line in split(code, '\n')
        (func = match(func_reg1, line)) ≢ nothing && push!(funcs, func.captures[1])
        (func = match(func_reg2, line)) ≢ nothing && push!(funcs, func.captures[1])
    end
    ## 获取信息部分
    author = match(r"# author: ([\w ]+)", body).captures[1]
    date = match(r"# date: ([\w-]+)", body).captures[1]
    any(isempty, [date, author]) && throw("未检索到信息！")
    return (code, unique!(funcs)), (author, date)
end

### 检查和准备阶段 ###
## 检查脚本位置 ##
cd(Base.source_dir()[1:end-5])
current_files = readdir()
!all(file in current_files for file in ["src", "tools"]) && throw("脚本位置有误")
## 获取主仓库文件信息 ##
println("检查主仓库的函数信息")
main_problem_path = "../LeetCode.jl/src/problems/"
main_problems = readdir(main_problem_path)
isempty(main_problems) && throw("未能读取到主仓库文件，脚本位置有误")
deleteat!(main_problems, length(main_problems)) ## 忽略 problems.jl
sort!(main_problems; by=i -> parse(Int, split(i, '.')[1]))
total_num = length(main_problems)

### 提取阶段 ###
# Idnig, 1008, Indig, 91, 918
main_texts = String[]
for file in main_problems
    # println("正在读取文件 $file")
    push!(main_texts, read(open(main_problem_path * file, "r"), String))
    _, (author, _) = get_info(main_texts[end])
end

### 统计作者和次数 ###
authors = Dict{String, Int}()
for text in main_texts
    _, (author, _) = get_info(text)
    if haskey(authors, author)
        authors[author] += 1
    else
        authors[author] = 1
    end
end

println("读取完毕，共 $(total_num) 个文件，共 $(length(authors)) 个作者提交了解答：")
println("
| author \t| number of commits |
| :----: \t| :--------------: |")
for (author, i) in authors
    println("| $author \t| $i |")
end


text:
import LinearAlgebra.reflectorApply!

# this should suffice to handle simple qr()

const qr_mt_threshold = Ref(64.0)
mt_thresholds[:qr] = qr_mt_threshold;
function reflectorApply!(x::AbstractVector{DT}, τ::Number, A::StridedMatrix{DT}
                         ) where {DT <: Union{DoubleFloat{T},
                                              Complex{DoubleFloat{T}}}} where T
    has_offset_axes(x) && throw(ArgumentError("not implemented "
                                              * "for offset axes"))
    m, n = size(A)
    if length(x) != m
        throw(DimensionMismatch("reflector has length $(length(x)), "
               * "which must match the first dimension of matrix A, $m"))
    end
    use_threads = (nthreads() > 1) &&
            (Float64(m)*Float64(n) > qr_mt_threshold[])
    if use_threads
        @threads for j = 1:n
            _mt_refl_loop1(τ,A,x,m,j)
        end
    else
        @inbounds begin
            for j = 1:n
                vAj = conj(τ)*(A[1, j] + dot(view(x,2:m), view(A,2:m,j)))
                A[1, j] -= vAj
                axpy!( -vAj, view(x,2:m), view(A,2:m,j))
                # for i = 2:m
                #    A[i,j] -= vAj * x[i]
                # end
            end
        end
    end
    return A
end
function _mt_refl_loop1(τ,A,x,m,j)
    @inbounds begin
        vAj = conj(τ)*(A[1, j] + dot(uview(x,2:m), uview(A,2:m,j)))
        A[1, j] -= vAj
        # axpy!( -vAj, uview(x,2:m), uview(A,2:m,j))
        for i = 2:m
            A[i,j] -= vAj * x[i]
        end
    end
end

import LinearAlgebra.generic_matvecmul!

const gemv_mt_threshold = Ref(512.0)
mt_thresholds[:gemv] = gemv_mt_threshold;
const gemtv_mt_threshold = Ref(64.0)
mt_thresholds[:gemtv] = gemtv_mt_threshold;

function generic_matvecmul!(C::AbstractVector{DoubleFloat{T}}, tA, A::AbstractVecOrMat{DoubleFloat{T}}, B::AbstractVector{DoubleFloat{T}}) where {T <: AbstractFloat}
    has_offset_axes(C, A, B) && throw(ArgumentError("offset axes are not supported"))
    mB = length(B)
    mA, nA = lapack_size(tA, A)
    if mB != nA
        throw(DimensionMismatch("matrix A has dimensions ($mA,$nA), vector B has length $mB"))
    end
    if mA != length(C)
        throw(DimensionMismatch("result C has length $(length(C)), needs length $mA"))
    end
    if (tA == 'T') || (tA == 'C')
        use_threads = (nthreads() > 1) &&
            (Float64(mB)*Float64(mA) > gemtv_mt_threshold[])

        if use_threads
            liA = LinearIndices(A)
            @threads for k = 1:mA
                @inbounds C[k] = _dot(nA,A,liA[1,k],B,1,Vec{Npref,T})
            end
        else
            @inbounds for k = 1:mA
                C[k] = dot(uview(A,:,k),B)
            end
        end
    else
        fill!(C,zero(T))
        use_threads = (nthreads() > 1) &&
            (Float64(mB)*Float64(mA) > gemv_mt_threshold[])

        if use_threads
            nt = nthreads()
            nd,nr = divrem(mA, nt)
            liA = LinearIndices(A)
            @threads for it=1:nt
            #    for it=1:nt # DEBUG
                j1 = it*nd
                j0 = j1-nd+1
                _mt_gemv_loop1(nA,A,liA,B,C,j0,j1)
            end

            if nr > 0
                j0 = nt*nd+1
                @inbounds for i = 1:nA
                    _axpy!(nr,B[i],A,liA[j0,i],C,j0,Vec{Npref,T})
                end
            end
        else
            @inbounds begin
                astride = stride(A,2)
                for k=1:mB
                    ioff = (k-1)*astride
                    b = B[k]
                    for i = 1:mA
                        C[i] += A[ioff + i] * b
                    end
                end
            end
#            liA = LinearIndices(A)
#            @inbounds for i = 1:nA
#                _axpy!(mA,B[i],A,liA[1,i],C,1,Vec{Npref,T})
#            end
        end
    end
    C
end

function _mt_gemv_loop1(nA,A::AbstractVecOrMat{DoubleFloat{T}},liA,
                        B,C,j0,j1) where {T}
# Julia v1.0+ compiler doesn't need help here
#    nd = j1-j0+1
#    @inbounds for i = 1:nA
#         _axpy!(nd,B[i],A,liA[j0,i],C,j0,Vec{Npref,T})
#    end
    @inbounds for i=1:nA
        b = B[i]
        for j=j0:j1
            C[j] += b * A[j,i]
        end
    end
end


text:
using Plots; pyplot()
using DataFrames, JLD2
using SolidStateDetectors
using SolidStateDetectors: Cartesian, Cylindrical

fn_SOR_update_benchmark_df = joinpath(ENV["HOME"], "SSD_SOR_update_benchmark.jld2")
fn_pot_calc_benchmark_df = joinpath(ENV["HOME"], "SSD_potential_calculation_benchmark.jld2")

df_SOR_update = load(fn_SOR_update_benchmark_df, "df_SOR_update")
df_pot_calc = load(fn_pot_calc_benchmark_df, "df_SOR_update")

function plot_benchmark(df::DataFrame; kwargs...)
    ys = df.time
    ys ./= minimum(ys)
    pos = eachindex(ys)
    plot(pos, ys,
        xticks = (pos, df.backend),
        ylabel = "Time [a.u.]",
        st = :bar,
        # ylims = (0.001, max(ys)),
        # fillrange=1e-10,
        yscale = :identity,
        # yscale = :log10,
        legend = false,
        title = "$(df.S[1]) - Grid size: $(df.grid_size[1])";
        kwargs...
    )
end

plot(
    plot_benchmark(filter(row -> row.S == Cartesian,   df_SOR_update)),
    plot_benchmark(filter(row -> row.S == Cylindrical, df_SOR_update)),
    size = (1200, 500),
    layout = (1, 2),
    guidefontsize = 16,
    tickfontsize = 12,
    titlefontsize = 18
)
savefig("/home/iwsatlas1/lhauert/Documents/sor_update_benchmark.pdf")
savefig("/home/iwsatlas1/lhauert/Documents/sor_update_benchmark.png")

plot(
    plot_benchmark(filter(row -> row.S == Cartesian,   df_SOR_update)),
    plot_benchmark(filter(row -> row.S == Cylindrical, df_SOR_update)),
    plot_benchmark(filter(row -> row.S == Cartesian,   df_pot_calc)),
    plot_benchmark(filter(row -> row.S == Cylindrical, df_pot_calc)),
    size = (1000, 1000),
    layout = (2, 2),
)


text:
# For imposing
# E[Y(d) | D = d′, Z = z]
#
# Slightly different than the "s-function" formulation in the paper
# Usually equivalent if fully saturated
#
# Useful here for the PRTE misspecification exercise to impose MC on
# E[Y(d) | D = d', Z = z]
# even when Pr[Z = z] = 0
function compute_Γₘ(bases::Array{Tuple{MTRBasis, MTRBasis}, 1}, dgp::DGP)
    [compute_Γₘ(basis[d + 1], dgp) for basis in bases, d in 0:1]
end

function compute_Γₘ(basis::MTRBasis, dgp::DGP)
    Γₘ = zeros(2, size(dgp.suppZ, 1), length(basis.a), length(basis.b))

    for (i,z) in enumerate(eachrow(dgp.suppZ))
        p = dgp.pscore[i]
        # d′ = 0
        Γₘ[1, i, :, :] = [aj(z) * ibk(p, 1) / (1 - p)
                          for aj in basis.a, ibk in basis.ib]
        # d′ = 1
        Γₘ[2, i, :, :] = [aj(z) * ibk(0, p) / p
                          for aj in basis.a, ibk in basis.ib]
    end
    return Γₘ
end


text:
using SymbolicUtils, Test
using SymbolicUtils: Term, Sym, istree, operation, arguments, symtype

SymbolicUtils.istree(ex::Expr) = ex.head == :call
SymbolicUtils.operation(ex::Expr) = ex.args[1]
SymbolicUtils.arguments(ex::Expr) = ex.args[2:end]

for f ∈ [:+, :-, :*, :/, :^]
    @eval begin
        Base.$f(x::Union{Expr, Symbol}, y::Number) = Expr(:call, $f, x, y)
        Base.$f(x::Number, y::Union{Expr, Symbol}) = Expr(:call, $f, x, y)
        Base.$f(x::Union{Expr, Symbol}, y::Union{Expr, Symbol}) = (Expr(:call, $f, x, y))
    end
end

ex = 1 + (:x - 2)

@test simplify(ex) == ex

SymbolicUtils.symtype(::Expr) = Real
SymbolicUtils.symtype(::Symbol) = Real
@test simplify(ex) == -1 + :x
@test simplify(:a * (:b + -1 * :c) + -1 * (:b * :a + -1 * :c * :a), expand=true) == 0


text:
# Structures of Vector calculus operators store all the operators required during computations.

# Operator for calculating gradients of a N-dimensional function

struct GradientOperator{T,N,O}
    ops :: O
end

function Gradient(approximation_order :: Int, dx::Union{NTuple{N,AbstractVector{T}},NTuple{N,T}},
        len::NTuple{N,Int}; coeff_func=1) where {T<:Real, N}

    ops = permutedims([CenteredDifference{n}(1, approximation_order, dx[n], len[n], coeff_func) for n in 1:N])

    GradientOperator{T,N,typeof(ops)}(
        ops
        )
end

# Operator for calculating curls of a given 3-dimensional vector stored as space-tensor

struct CurlOperator{T,O}
    ops :: O
end

function Curl(approximation_order :: Int, dx::Union{NTuple{3,AbstractVector{T}},NTuple{3,T}},
    len::NTuple{3,Int}; coeff_func=1 ) where {T<:Real}

    @assert len[1] == len[2] && len[2] == len[3] "All dimensions must have equal no. of grid points"
    ops = permutedims([CenteredDifference{n}(1, approximation_order, dx[n], len[n], coeff_func) for n in 1:3])

    CurlOperator{T,typeof(ops)}(
        ops
        )

end

# Operator for calculating divergence of a given N-dimensional vector stored as space-tensor

struct DivergenceOperator{T,N,O}
    ops :: O
end

function Divergence(approximation_order :: Int, dx::Union{NTuple{N,AbstractVector{T}},NTuple{N,T}},
    len::NTuple{N,Int}; coeff_func=1) where {T<:Real, N}

    ops = permutedims([CenteredDifference{n}(1, approximation_order, dx[n], len[n], coeff_func) for n in 1:N])

    DivergenceOperator{T,N,typeof(ops)}(
        ops
    )

end

function *(A::GradientOperator{T},M::AbstractArray{T,N}) where {T<:Real,N}

    size_x_temp = [size(M)...].-2

    x_temp = zeros(T,size_x_temp...,N)

    mul!(x_temp,false,A,M)
    return x_temp
end

function *(A::CurlOperator{T},M::AbstractArray{T,4}) where {T<:Real}

    size_x_temp = [size(M)...].-2
    size_x_temp[4] += 2
    x_temp = zeros(T,size_x_temp...)
    mul!(x_temp, A, M, overwrite = false)
    return x_temp
end

function *(A::DivergenceOperator{T},M::AbstractArray{T,N}) where {T<:Real, N}

    size_x_temp = [size(M)[1:end-1]...].-2

    x_temp = zeros(T,size_x_temp...)

    mul!(x_temp,true,A,M)
    return x_temp
end

function *(c::Number, A::GradientOperator{T,N}) where {T,N}
    ops = permutedims([c*A.ops[i] for i in 1:N])
    GradientOperator{T,N,typeof(ops)}(
        ops
        )
end

function *(c::Number, A::CurlOperator{T}) where {T}
    ops = permutedims([c*A.ops[i] for i in 1:3])
    CurlOperator{T,typeof(ops)}(
        ops
        )
end

function *(c::Number, A::DivergenceOperator{T,N}) where {T,N}
    ops = permutedims([c*A.ops[i] for i in 1:N])
    DivergenceOperator{T,N,typeof(ops)}(
        ops
        )
end


text:
using Test
using DelimitedFiles
using CategoricalTimeSeries

#testing the serial dependences functions by reproducing the results from C. Weiss's book "An Introduction to Discrete-Valued Time Series".
#I was not able to get my hands the full time-series, C. weiss says it is ~1300 elements long, which explains the slight numerical differences in values.
pewee = Int64.(readdlm("pewee.txt", ',')[1,:])
@test round(cramer_coefficient(pewee, 4)[1], digits = 2) == 0.46
@test round(cohen_coefficient(pewee, 4)[1], digits = 2) == 0.55
#this one was not in the book, but the plot correctly reproduces the results.
@test round(theils_u(pewee,[1])[1], digits = 2) == 0.55
@test round(H(pewee), digits = 2) == 1.49

#testing spectral envelope method by reproducing David's stoffer results.
DNA = readdlm("DNA_data.txt", ',')[1,:]
x,y,e = spectral_envelope(DNA; m=0)
@test round(spectral_envelope(DNA)[2][5]; digits = 3) == round(0.175; digits = 3)

#testing integerIB
#bach chorale data, taken from Nori Jacoby's webpage.
bach_histogram = [0.00001 392 14 582 896 262 106; 12 0.0001 15 5 674 17 182; 13 6 0.0001 44 12 32 3; 239 134 16 0.0001 380 13 173; 2099 25 46 93 0.00001 211 2; 96 206 25	95	172	0.00001 36; 499 1 4 9 24 20 0.00001]
pxy = bach_histogram./sum(bach_histogram)
model = IB(pxy, 0.95, "DIB")
brute_optimize!(model)
h, ixt, iyt, L = calc_metrics(model)
@test size(model.qt_x, 1) == 5
@test round(h, digits = 2) == 2.06
@test round(ixt, digits = 2) == 2.06
@test round(iyt, digits = 2) == 0.78
@test round(L, digits = 2) == 1.32


text:
# solver returns ALMOST_OPTIMAL when seed=0
Random.seed!(1)

#sig = [1 2; 2 2]
#sig = [1 1; 2 3]
#sig = [2 3]
#sig = [2 2]
sig = [3 2; 2 3]

S = random_S0Graph(sig)
T = complement(S)

w = random_element(S.S1)
w = w*w'
@test w in S.S1

@time opt0 = dsw(S, w, eps=solver_eps)[1]
@time opt1, x, y = dsw_via_complement(T, w, eps=solver_eps)
@test opt1 ≈ opt0  atol=tol
@time opt2 = dsw(T, y, eps=solver_eps)[1]
@test opt2 ≈ 1  atol=tol
@test real(tr(w * √S.D * y * √S.D)) ≈ opt0 * opt2  atol=tol

max_stars_repo_name: dstahlke/NoncommutativeGraphs

max_issues_repo_name: dstahlke/NoncommutativeGraphs

max_forks_repo_name: dstahlke/NoncommutativeGraphs


text:
blas_set_num_threads(1) # because small matrices
using DataFrames, Distributions#, Gadfly

const dat = readdlm("../data/dat.txt")
n,k1 = size(dat)
const k = k1-1

const y = dat[:,1]
const X = dat[:,2:end]

const XXi = inv(X'X)
const s = 100
const mle = XXi*X'y

a = 1
b = 1
s2 = 10
csb = 4XXi
S = chol(csb)'
css = 1

function ll(be::Array{Float64,1},sig2::Float64)
  c = y-X*be
  c'c/(-2sig2)-n*log(sig2)/2
end

lpb(be::Array{Float64,1}) = -be'XXi*be/2s2
lps(sig2::Float64) = (a-1)*log(s2)-s2/b
mvrnorm(M::Array{Float64,1}) = M+S*randn(k)

function mh(B=100000)
  accb = 0; accs = 0
  bb = Array(Float64,(k,B))
  ss = Array(Float64,B)
  bcur = bb[:,1]
  scur = 1.0

  println("Starting Metropolis...")
  @time for i in 1:B

    # Update β̂:
    candb = mvrnorm(bcur)
    q = ll(candb,scur)+lpb(candb) -ll(bcur,scur)-lpb(bcur)
    if q[1]>log(rand())
      bcur = candb
      accb += 1
    end

    # Update ŝ²:
    cands = rand(Normal(scur,sqrt(css)))
    if cands>0
      q = ll(bcur,cands)+lps(cands) -ll(bcur,scur)-lps(scur)
      if q[1]>log(rand())
        scur = cands
        accs += 1
      end
    end

    @inbounds bb[:,i] = bcur
    @inbounds ss[i]  = scur

    if i%(B/10)==0 print("\r",round(100*i/B),"%") end
  end # End of loops
  println("End of Metropolis.\n\n")

  return (bb,ss,accb,accs,B)
end # End of mh function

bb,ss,accb,accs,B = @time mh();

println("β̂: \n", mean(bb[:,Int(B*.9):end],2),"\n")
println("ŝ²: ",  mean(ss[Int(B*.9):end]),"\n")

println("Acceptance rate for β̂: ",accb/B)
println("Acceptance rate for ŝ²:",accs/B)

max_stars_repo_name: luiarthur/padawan

max_issues_repo_name: luiarthur/padawan

max_forks_repo_name: luiarthur/padawan


text:
using FreeTypeAbstraction, StaticArrays, Colors, ColorVectorSpace
using Test
using FreeTypeAbstraction: Vec

face = newface(joinpath(@__DIR__, "hack_regular.ttf"))
f = unsafe_load(face[])

img, metric = renderface(face, 'C')
@test size(img) == (15, 23)
@test typeof(img) == Array{UInt8,2}
@test metric == FontExtent(
    Vec(-8,4),
    Vec(2,23),
    Vec(19,31),
    Vec(15,23)
)

a = renderstring!(zeros(UInt8,20,100), "helgo", face, (10,10), 10, 10)
@test any(a[3:12,:] .!= 0)
@test all(a[vcat(1:2,13:20),:] .== 0)
@test any(a[:,11:40] .!= 0)
@test all(a[:,vcat(1:10,41:100)] .== 0)
a = renderstring!(zeros(UInt8,20,100), "helgo", face, (10,10), 15, 70)
@test any(a[8:17,:] .!= 0)
@test all(a[vcat(1:7,18:20),:] .== 0)
@test any(a[:,71:100] .!= 0)
@test all(a[:,1:70] .== 0)

a = renderstring!(zeros(UInt8,20,100), "helgo", face, (10,10), 10, 50, valign=:vtop)
@test all(a[1:10,:] .== 0)
@test any(a[11:20,:] .!= 0)
a = renderstring!(zeros(UInt8,20,100), "helgo", face, (10,10), 10, 50, valign=:vcenter)
@test all(a[vcat(1:5,16:end),:] .== 0)
@test any(a[6:15,:] .!= 0)
a = renderstring!(zeros(UInt8,20,100), "helgo", face, (10,10), 10, 50, valign=:vbaseline)
@test all(a[vcat(1:2,13:end),:] .== 0)
@test any(a[3:12,:] .!= 0)
a = renderstring!(zeros(UInt8,20,100), "helgo", face, (10,10), 10, 50, valign=:vbottom)
@test any(a[1:10,:] .!= 0)
@test all(a[11:20,:] .== 0)
a = renderstring!(zeros(UInt8,20,100), "helgo", face, (10,10), 10, 50, halign=:hleft)
@test all(a[:,1:50] .== 0)
@test any(a[:,51:100] .!= 0)
a = renderstring!(zeros(UInt8,20,100), "helgo", face, (10,10), 10, 50, halign=:hcenter)
@test all(a[:,vcat(1:35,66:end)] .== 0)
@test any(a[:,36:65] .!= 0)
a = renderstring!(zeros(UInt8,20,100), "helgo", face, (10,10), 10, 50, halign=:hright)
@test any(a[:,1:50] .!= 0)
@test all(a[:,51:100] .== 0)

a = renderstring!(zeros(UInt8,20,100), "helgo", face, (10,10), 10, 50, fcolor=0x80)
@test maximum(a)<=0x80
a = renderstring!(zeros(UInt8,20,100), "helgo", face, (10,10), 10, 50, fcolor=0x80, bcolor=0x40)
@test any(a .== 0x40)
a = renderstring!(fill(0x01,20,100), "helgo", face, (10,10), 10, 50, bcolor=nothing)
@test !any(a .== 0x00)

a = renderstring!(zeros(Float32,20,100), "helgo", face, (10,10), 10, 50)
@test maximum(a) <= 1.0
a = renderstring!(zeros(Float64,20,100), "helgo", face, (10,10), 10, 50)
@test maximum(a) <= 1.0

renderstring!(zeros(Gray,20,100), "helgo", face, (10,10), 10, 50)
renderstring!(zeros(Gray{Float64},20,100), "helgo", face, (10,10), 10, 50, fcolor=Gray(0.5))

renderstring!(zeros(UInt8,20,100), "helgo", face, (10,10), 0, 0, halign=:hcenter, valign=:vcenter)
renderstring!(zeros(UInt8,20,100), "helgo", face, (10,10), 25, 80)

# Find fonts
# these fonts should be available on all platforms:

# debug travis... does it even have fonts?
fontpaths = FreeTypeAbstraction.fontpaths()

isempty(fontpaths) && println("OS doesn't have any font folder")

if Sys.islinux()
    fonts = [
        "dejavu sans",
    ]
else # OSX + windows have some more fonts installed per default
    fonts = [
        "Times New Roman",
        "Arial",
        "Comic Sans MS",
        "Impact",
        "Tahoma",
        "Trebuchet MS",
        "Verdana",
        "Courier New",
    ]
end

@testset "finding fonts" begin

    for font in fonts
        @testset "finding $font" begin
            @test findfont(font) != nothing
        end
    end
    @testset "find in additional dir" begin
        @test findfont("Hack") == nothing
        @test findfont("Hack", additional_fonts = @__DIR__) != nothing
    end
end

@testset "loading lots of fonts" begin
    for i = 1:10
        for font in fonts
            @time findfont(font)
        end
    end
    @test "No Error" == "No Error"
end